Lesson 11.1Module 11: Deployment and production
Model inference
Learning objectives
- Describe the two phases of LLM inference, prefill and decode, and why they behave so differently.
- Explain what the KV cache saves, what it costs in memory, and why it does not change the output.
- Use the serving metrics that matter: time to first token, tokens per second, throughput and cost per token.
- Recognise the main serving techniques (batching, paged KV cache, speculative decoding) and what is and is not known about how Claude is served.
Every module so far has been about making a model: its maths, its architecture, its training. This module is about using one, reliably and cheaply, for real people. The first step is to understand inference, the act of running a trained model to produce output. Training happens once (or occasionally); inference happens every time anyone sends a message, so for any successful product it is where most of the compute, latency and money end up.
You have already run inference many times: the generation loop of lesson 5.7, the journey of a message in lesson 1.5. This lesson looks at the same loop with a performance engineer's eyes.
Analogy: a simultaneous interpreter
An interpreter at a conference first listens to the whole question from the audience. Hearing goes fast, and they can take it all in at once. Then they answer, and speaking is slow: one word after another, each depending on the words already said. A good interpreter also keeps notes of what has been said so far, so they never have to ask the speaker to repeat the question for every new word. Reading the prompt is the fast, parallel "listening" phase; writing the answer is the slow, one-word-at-a-time "speaking" phase; and the notes are the KV cache.
Two phases: prefill and decode
A request to a language model goes through the same steps whether it runs on your laptop or in a data centre. The text is tokenised; the tokens go through the network; the model produces a probability distribution for the next token; one token is chosen; it is appended and the process repeats until a stop condition. What makes inference interesting is that the first pass and the following passes do very different amounts of work.
- Prefill processes the whole prompt in one forward pass. All prompt tokens are known in advance, so the model can compute them in parallel as big matrix-matrix multiplications. A GPU is very good at this: prefill is usually compute-bound, limited by how many multiply-adds per second the chip can do. Its result is the first output token and, as a by-product, the keys and values of every prompt token in every layer.
- Decode produces the answer one token at a time. Each step processes a single new token, so the arithmetic is small (matrix-vector products), but the model still has to read all of its weights from memory for every token. Decode is usually memory-bandwidth-bound: the chip waits for data more than it computes. Lesson 11.3 turns this into a formula you can use to predict speed.
This split explains the two numbers users feel. Time to first token (TTFT) is mostly queueing plus prefill, and grows with the prompt length. Inter-token latency (or its inverse, output tokens per second) is the decode speed, and decides how fast the text streams. A chat with a 20,000-token document attached has a slow start and then streams at normal speed; a short question starts fast.
- Request
- The full conversation the app sends: the model remembers nothing between requests (lesson 7.1), so every turn resends the history.
- Tokenizer
- Turns text into token ids with the model's own vocabulary (lesson 1.6). It runs on the CPU and is cheap.
- Prefill
- One forward pass over every prompt token in parallel. Compute-bound. Its length sets most of the time to first token.
- KV cache
- The keys and values of every token so far, for every layer. Kept in accelerator memory so decode steps never recompute them.
- Decode step
- A forward pass for one new token. Reads all the weights and the whole KV cache, but does little arithmetic. Memory-bandwidth-bound.
- Sampler
- Chooses the next token from the probabilities: greedy, or random with temperature, top-k or top-p (lessons 5.7 and 5.8). Stops at an end token or the max_tokens limit.
- Detokenize
- Turns ids back into text. Several tokens may form one character, so streaming servers buffer partial UTF-8 sequences.
- Stream
- Text is sent to the client as it is produced, for example as Server-Sent Events (lesson 7.5).
- The app sends the whole conversation; the server tokenises it.
- Prefill reads every prompt token at once and fills the KV cache. The first output token appears: this is the time to first token.
- Each decode step adds one token, reads the cache, and appends its own key and value to it.
- Tokens are turned back into text and streamed until a stop token or max_tokens.
The KV cache, measured
In attention (lesson 4.5), every token computes a query, a key and a value. A new token needs the keys and values of all earlier tokens, but those never change once computed: in a causal model, token 5 cannot be influenced by token 9. So a server computes them once and stores them in the KV cache, as you saw in lesson 4.9. Without it, step would redo the work of all earlier positions, and generating a long answer would cost time proportional to the square of its length.
The script below generates 20 tokens with a tiny random one-layer "transformer", once by recomputing everything at each step and once with a cache, and counts the multiply-adds by hand.
Simplified implementation Simplified
One layer, one head, a 32-token vocabulary and random weights: the generated tokens are meaningless. What carries over to real models is the bookkeeping: identical outputs, far less arithmetic, and a cache that grows by one entry per token.
# @run
# Greedy generation with and without a KV cache on a tiny random NumPy "transformer"
# (one attention layer, one head). Both versions must produce the same tokens; the cached
# version does far fewer multiply-adds because it never recomputes old keys and values.
import numpy as np
rng = np.random.default_rng(0)
VOCAB, D = 32, 16 # tiny vocabulary and model width
E = rng.normal(0, 0.5, (VOCAB, D)) # token embeddings
P = rng.normal(0, 0.1, (64, D)) # learned positions (max 64 tokens)
Wq, Wk, Wv, Wo = (rng.normal(0, D ** -0.5, (D, D)) for _ in range(4))
W_out = rng.normal(0, D ** -0.5, (D, VOCAB)) # hidden state -> logits
ops = {"count": 0} # multiply-adds, counted by hand
def matmul(a, b):
ops["count"] += a.shape[0] * a.shape[1] * b.shape[1]
return a @ b
def softmax(x):
x = x - x.max(axis=-1, keepdims=True)
e = np.exp(x)
return e / e.sum(axis=-1, keepdims=True)
def forward_full(tokens):
"""No cache: run the whole sequence and return logits for the last position."""
x = E[tokens] + P[: len(tokens)]
q, k, v = matmul(x, Wq), matmul(x, Wk), matmul(x, Wv)
scores = matmul(q, k.T) / np.sqrt(D)
mask = np.triu(np.ones((len(tokens), len(tokens))), 1) * -1e9 # causal mask
h = x + matmul(matmul(softmax(scores + mask), v), Wo)
return matmul(h[-1:], W_out)[0]
def generate_no_cache(prompt, n_new):
tokens = list(prompt)
for _ in range(n_new):
tokens.append(int(np.argmax(forward_full(tokens))))
return tokens
def step_cached(token, pos, cache):
"""With cache: process ONE new token, append its key/value, attend over all cached ones."""
x = (E[token] + P[pos])[None, :]
q = matmul(x, Wq)
cache["k"].append(matmul(x, Wk)[0])
cache["v"].append(matmul(x, Wv)[0])
K, V = np.array(cache["k"]), np.array(cache["v"])
att = softmax(matmul(q, K.T) / np.sqrt(D)) # no mask needed: the cache only holds the past
h = x + matmul(matmul(att, V), Wo)
return matmul(h, W_out)[0]
def generate_cached(prompt, n_new):
cache = {"k": [], "v": []}
tokens = list(prompt)
for pos, t in enumerate(prompt): # prefill: fill the cache from the prompt
logits = step_cached(t, pos, cache)
prefill_ops = ops["count"]
for _ in range(n_new): # decode: one token per step
nxt = int(np.argmax(logits))
tokens.append(nxt)
logits = step_cached(nxt, len(tokens) - 1, cache)
return tokens, prefill_ops, len(cache["k"])
prompt = [3, 14, 15, 9, 26, 5]
N_NEW = 20
ops["count"] = 0
a = generate_no_cache(prompt, N_NEW)
no_cache_ops = ops["count"]
ops["count"] = 0
b, prefill_ops, cached = generate_cached(prompt, N_NEW)
cache_ops = ops["count"]
print("prompt tokens: ", prompt)
print("generated (no cache):", a[len(prompt):])
print("generated (cache): ", b[len(prompt):])
print("identical outputs: ", a == b)
print()
print(f"multiply-adds without cache: {no_cache_ops:>9,}")
print(f"multiply-adds with cache: {cache_ops:>9,} (prefill {prefill_ops:,})")
print(f"speed-up in arithmetic: {no_cache_ops / cache_ops:9.1f}x")
print(f"positions held in the cache: {cached}")
kv_floats = 2 * cached * D
print(f"KV cache size: 2 x {cached} positions x {D} dims = {kv_floats} floats = {kv_floats * 4} bytes in float32")
print()
print("Work per decode step grows with the sequence when there is no cache:")
for n in (8, 16, 24):
ops["count"] = 0
forward_full(list(range(n)))
full = ops["count"]
ops["count"] = 0
step_cached(1, n - 1, {"k": [np.zeros(D)] * (n - 1), "v": [np.zeros(D)] * (n - 1)})
print(f" length {n:2d}: full recompute {full:6,} vs one cached step {ops['count']:5,}")E,P,Wq…W_out: embeddings, positions and the projection matrices of a single attention layer, drawn with a fixed seed so every run is identical.matmul(a, b): a normal matrix product that also addsrows × inner × colsto a counter, so we can compare the two methods without timing noise.forward_full(tokens): the no-cache path. It recomputes queries, keys and values for the whole sequence and applies a causal mask, then keeps only the last position's logits.step_cached(token, pos, cache): the cached path. It computes the query, key and value for one new token only, appends the key and value to the cache, and attends over everything cached. No mask is needed because the cache only contains the past.generate_cached: first a prefill loop over the prompt (here done token by token for clarity; real engines do it in one batched pass), then the decode loop.- The final loop compares the cost of one step at lengths 8, 16 and 24: the full recompute grows with the length, the cached step barely does.
prompt tokens: [3, 14, 15, 9, 26, 5]
generated (no cache): [28, 3, 19, 29, 23, 29, 23, 29, 23, 29, 23, 29, 23, 27, 23, 27, 23, 29, 23, 29]
generated (cache): [28, 3, 19, 29, 23, 29, 23, 29, 23, 29, 23, 29, 23, 27, 23, 27, 23, 29, 23, 29]
identical outputs: True
multiply-adds without cache: 502,720
multiply-adds with cache: 51,168 (prefill 9,888)
speed-up in arithmetic: 9.8x
positions held in the cache: 26
KV cache size: 2 x 26 positions x 16 dims = 832 floats = 3328 bytes in float32
Work per decode step grows with the sequence when there is no cache:
length 8: full recompute 10,752 vs one cached step 1,792
length 16: full recompute 25,088 vs one cached step 2,048
length 24: full recompute 43,520 vs one cached step 2,304Both methods generate exactly the same 20 tokens, and the cached version does about a tenth of the arithmetic. The gap grows with length: at 24 tokens one full recompute costs 19 times more than one cached step. The price is memory. Our toy cache holds 3,328 bytes; a real model has dozens of layers and several key/value heads, so the cache for one long conversation is measured in gigabytes. For an 8-billion-parameter model with grouped-query attention it is roughly 1 GB per 8,000 tokens in 16-bit precision (lesson 11.3 computes it), and that memory is reserved for one user. The KV cache, not the weights, is often what limits how many people one GPU can serve at once.
The numbers that describe a deployment
| Metric | What it measures | Mostly decided by |
|---|---|---|
| TTFT (time to first token) | how long the user stares at a spinner | queue wait + prefill (prompt length, compute) |
| Output tokens/s per request | how fast text streams | decode speed: memory bandwidth ÷ bytes read per step |
| End-to-end latency | time until the full answer | TTFT + output length ÷ decode speed |
| Throughput (tokens/s per GPU) | how many users one machine serves | batching, KV cache memory, scheduling |
| Cost per million tokens | what each answer costs | hardware price ÷ throughput, or the provider's price list |
The first three matter to a user; the last two matter to whoever pays for the hardware, and they pull in opposite directions. Serving one user at a time gives the fastest stream but wastes the GPU, which is idle most of each decode step waiting for memory. Serving many users together raises throughput enormously but each user gets their tokens a little slower. Try the trade-off between prompt length and speed below.
A simple model of one request: TTFT = queue + prompt ÷ prefill speed; then the answer streams at the decode speed. The speeds are rough examples; lesson 11.3 shows how to estimate them for real hardware.
Choosing the next token
The network only produces probabilities. A sampler turns them into a choice. Greedy decoding always takes the most likely token: deterministic, good for extraction and code, prone to loops in long free text (the toy script above falls into a repeating "29, 23" loop for exactly this reason). Sampling draws at random from the distribution, usually reshaped by a temperature (divide the logits by T before the softmax: below 1 sharpens, above 1 flattens) and truncated by top-k (keep the k most likely) or top-p (keep the smallest set whose probabilities add up to p). You built all of these and can play with them in lessons 5.7 and 5.8.
Open-weight runtimes such as Ollama and Hugging Face transformers expose these knobs, and you will set them in lessons 11.4 and 11.5. Hosted APIs differ: on the API version this course uses (2026-10-21), the Claude Messages API rejects temperature, top_p and top_k with a 400 error, so you steer Claude's output with the prompt, max_tokens, stop sequences and structured outputs instead. The mechanism of sampling is the same everywhere; which knobs a provider lets you touch is a product decision.
Two more controls end generation. max_tokens is a hard cap on output length, and since output tokens are billed and take decode time, it is also a cap on cost and latency. Stop sequences end the answer early when a given string appears. A response cut off by max_tokens reports that as its stop reason (lesson 7.5); always check it, because a truncated JSON object is worse than no object.
How serving engines squeeze more out of a GPU
Batching. In a decode step, reading the weights costs the same whether one sequence or sixty-four use them. So servers process many users' next tokens in one step. Simple static batching waits for a whole batch to finish, which wastes slots when one answer is long and the others are short. Continuous batching (also called in-flight batching, introduced in the Orca serving system, OSDI 2022) adds and removes sequences at every step, keeping the batch full Industry practice.
Paged KV cache. Reserving one contiguous block of memory per request for its maximum length wastes most of it. vLLM's PagedAttention (Kwon et al., 2023, arXiv:2309.06180) stores the cache in fixed-size pages, like virtual memory in an operating system, so memory is allocated as tokens arrive and identical prefixes can share pages. The same idea makes prefix caching possible: requests that start with the same system prompt reuse its keys and values instead of recomputing them, which is the mechanism behind provider prompt caching (lesson 6.8).
Speculative decoding. A small, fast "draft" model guesses several tokens ahead; the large model checks all of them in one forward pass (which costs about the same as generating one token, because decode is memory-bound) and keeps the longest prefix it agrees with. With the right acceptance rule the output distribution is exactly that of the large model (Leviathan et al., 2022, arXiv:2211.17192; Chen et al., 2023). It speeds up decode when the draft guesses well.
Kernels and parallelism. FlashAttention (Dao et al., 2022) computes attention without materialising the full score matrix; tensor parallelism splits each layer across several GPUs when a model does not fit on one; prefill and decode are sometimes even run on different machines ("disaggregated serving") because they stress hardware differently.
What about Claude? Anthropic serves Claude through its API and cloud partners, and documents features such as streaming, prompt caching and batch processing Public. How the models are actually served (which accelerators, how requests are batched, whether and how weights are quantised, how speculative decoding or caching is implemented internally) has not been published Not public. Everything in this deeper section describes general practice in open-source engines such as vLLM, TGI and llama.cpp, not Anthropic's systems.
Common mistakes and debugging tips
Measuring only the average latency
A dashboard says "average response 2.1 s" while users complain. Averages hide the slow tail, and for a streaming product the wait before the first word matters more than the total.
Fix: record TTFT and total latency separately, and look at percentiles (p50, p95, p99), as lesson 11.8 shows.
Huge prompts "because the context window allows it"
Every prompt token is prefill work on every turn, and it is resent with the whole history each time. A 100,000-token context makes every turn slow to start and expensive, even if the answer is one line.
Fix: retrieve only what is relevant (module 8), trim old turns (lesson 7.4) and use prompt caching for the parts that stay the same.
Forgetting the KV cache when sizing memory
The weights fit in the GPU, the server starts, and it crashes with out-of-memory as soon as a few users send long conversations.
Fix: budget memory as weights + KV cache × concurrent users × context + overhead. Limit the maximum context and the number of parallel requests in the server's settings.
Not capping output length
A prompt bug makes the model repeat itself until it hits a very large limit: slow, and billed per token.
Fix: set max_tokens to what the feature really needs, and treat a max_tokens stop reason as an error to log.
Key takeaways
- Prefill reads the prompt in parallel and is compute-bound; decode writes one token at a time and is memory-bandwidth-bound.
- The KV cache gives identical output with far less work, at the price of memory that grows with every token of every active conversation.
- Measure TTFT, tokens per second, throughput and cost per token; latency for one user and throughput for the GPU trade against each other.
- Batching, paged caches and speculative decoding are standard in open engines; how Claude is served is not public.
Exercise: count the cost of no cache
1) In kv_cache_inference.py, change N_NEW from 20 to 60. Before running it, predict whether the speed-up will be larger or smaller than 9.8×, then run it. 2) A chat product sends prompts of 6,000 tokens and answers of 250 tokens. With a prefill speed of 3,000 tokens/s and a decode speed of 50 tokens/s, what are the TTFT and the total time? Which half would you attack first to make it feel faster?
Hint
Without a cache, step n costs work proportional to n, so the total grows with the square of the length; with a cache it grows roughly linearly. For part 2 use the formula in the timeline demo (no queue).
Show a solution
1) The speed-up grows (to roughly 25×), because the no-cache cost is quadratic in length and the cached cost is close to linear. The outputs remain identical.
2) TTFT = 6,000 ÷ 3,000 = 2 s; decode = 250 ÷ 50 = 5 s; total 7 s. The text starts streaming after 2 s, which users notice most: shrink the prompt (retrieve less, trim history) or cache its stable prefix. Faster decode needs faster hardware, a smaller or quantised model (lesson 11.2), or speculative decoding.
Check your understanding
Why is the decode phase usually limited by memory bandwidth rather than by compute?
- Because decoding uses larger matrices than prefill
- Because the sampler runs on the CPU
- Because each step reads all the weights to process just one new token, so there is little arithmetic per byte read
What does the KV cache change about the generated text?
- Nothing: it only avoids recomputing keys and values that cannot change
- It makes the text slightly less accurate to save time
- It makes the model remember earlier conversations
A user attaches a long document and the answer takes a long time to start, then streams at normal speed. Which phase is responsible for the delay?
- Decode
- Prefill (plus any queueing)
- Detokenisation
Lesson 11.2Module 11: Deployment and production
Quantization
Learning objectives
- Compute how much memory a model needs from its parameter count and the bytes per number.
- Quantise weights to int8 and int4 by hand: scales, zero points, rounding and clipping.
- Explain why outliers make naive quantisation fail and how per-channel and group-wise scales fix it.
- Compare inference formats and methods (GGUF k-quants, GPTQ, AWQ, int8 with outlier handling) and choose a quality/size trade-off.
In module 3 you stored every weight as a 64-bit or 32-bit float, and we promised that large models are kept in 16-bit or even smaller formats. In lesson 10.5 you met one such format, NF4, used to train adapters on top of a frozen 4-bit model. This lesson is about quantisation for inference: making a trained model smaller and faster to run, usually with little loss in quality. It is the single most important reason an 8-billion-parameter model runs on a laptop.
Analogy: rounding prices to the nearest coin
A shop that prices everything to a hundredth of a cent needs long price tags. Rounding every price to the nearest 5 cents makes the tags short, and almost no customer notices. But if one item costs 2,000 dollars and the shop uses a single rounding rule for the whole store, say "the nearest 100 dollars", every cheap item rounds to zero. The fix is a different rounding step for each shelf: cents on the sweets shelf, dollars on the electronics shelf. Quantisation is rounding weights to a few levels; group-wise scales are the per-shelf rounding steps.
Bytes per number decide everything
The weights of a model are just numbers, so their memory is simply number of parameters × bytes per parameter. An 8-billion-parameter model is 32 GB in float32, 16 GB in 16-bit (float16 or bfloat16, the usual release format), 8 GB in 8-bit and about 4.5 GB in a typical 4-bit format (4 bits per weight plus a little for the scales). A 70B model goes from 140 GB in 16-bit, which needs two data-centre GPUs, to about 40 GB at 4 bits, which fits on one large GPU or a high-memory laptop.
Size is not the only gain. Decode speed is limited by how many bytes must be read from memory per token (lesson 11.1), so a model that is four times smaller also generates up to about four times faster on the same hardware. That is why quantised models are the default for local inference, and widely used in production serving too Industry practice.
| Format | Bits per weight | 8B model | 70B model | Typical use |
|---|---|---|---|---|
| float32 | 32 | 32 GB | 280 GB | training master copies, small models |
| bfloat16 / float16 | 16 | 16 GB | 140 GB | release format, GPU serving |
| int8 / FP8 | 8 to 8.5 | 8 GB | 70 GB | serving with almost no quality loss |
| 4-bit (GGUF Q4_K_M, GPTQ, AWQ) | about 4.5 to 4.9 | about 4.5 to 5 GB | about 40 to 43 GB | local inference, cheaper serving |
| 2 to 3-bit | about 2.5 to 3.5 | about 3 GB | about 25 GB | squeezing a model onto small hardware; visible quality loss |
All sizes are weights only. Add the KV cache and a runtime overhead (lesson 11.3), and remember that numbers like these are approximate: each file format stores its scales slightly differently.
How quantisation works
Picture the weights of one matrix spread along a number line, mostly tiny values around zero. Quantisation lays a ruler with a fixed number of marks over that range (256 marks for 8 bits, 16 for 4 bits) and moves every weight to its nearest mark. Only the mark's index is stored, a small integer, plus the spacing between marks, called the scale. To use the weight, multiply the integer by the scale.
In the symmetric scheme the ruler is centred on zero and its end is the largest absolute weight:
In words: divide each weight by the scale, round to the nearest integer, keep it inside the allowed range (−127…127 for int8, −7…7 for int4), and multiply back by the scale when you need the value. The difference between and is the quantisation error.
The asymmetric scheme adds a zero point so the ruler can cover a range that is not centred on zero, such as activations after a ReLU. Either way, the rounding error for a weight is at most half a step, so a smaller scale means smaller errors. And the scale is set by the largest value in the group, which is the whole problem.
Outliers and group-wise scales
Real weight matrices contain a few values far larger than the rest. With one scale for the whole tensor, that single outlier stretches the ruler, the step becomes huge compared with ordinary weights, and most of them round to zero. The cure is to use more scales: one per output row (per-channel) or one per small block of consecutive weights (group-wise, typically 32 to 128 weights). An outlier then only spoils its own group. The extra cost is one scale per group: with 16-bit scales and groups of 32, that is half a bit per weight, which is why "4-bit" formats really use about 4.5 bits.
Sixteen weights (outlined) and their quantised values (filled). Change the bits and the number of groups, and add an outlier to see why group-wise scales exist.
Outline = original weight · filled = after quantisation · red = rounded to zero · dashed line = group boundary.
Quantise a real-sized matrix
The script quantises a 256 × 512 matrix of small random weights with one planted outlier, in several ways, and measures two errors: how far the weights moved (relative error) and, more importantly, how far the output of a matrix-vector product moved, since that is what the next layer sees.
# @run
# Quantise a weight matrix to int8 and 4-bit and measure what we lose.
# Symmetric: q = round(w / s), s = max|w| / qmax (zero maps to 0)
# Asymmetric: q = round(w / s) + z, s = (max - min) / (qmax - qmin), z = qmin - round(min / s)
# Group-wise: one scale per group of G consecutive weights instead of one per tensor.
import numpy as np
rng = np.random.default_rng(0)
ROWS, COLS = 256, 512
W = rng.normal(0, 0.02, (ROWS, COLS)).astype(np.float32) # typical small weights
W[3, 7] = 0.35 # one outlier, like real models have
x = rng.normal(0, 1, (COLS,)).astype(np.float32) # an input vector for a matmul test
def quant_symmetric(w, bits, axis=None):
qmax = 2 ** (bits - 1) - 1 # int8: 127, int4: 7
amax = np.abs(w).max(axis=axis, keepdims=axis is not None)
s = np.maximum(amax, 1e-12) / qmax
q = np.clip(np.round(w / s), -qmax, qmax).astype(np.int8)
return q, s
def quant_asymmetric(w, bits):
qmin, qmax = 0, 2 ** bits - 1 # uint8: 0..255
lo, hi = float(w.min()), float(w.max())
s = (hi - lo) / (qmax - qmin)
z = int(qmin - round(lo / s))
q = np.clip(np.round(w / s) + z, qmin, qmax).astype(np.int32)
return q, s, z
def quant_groupwise(w, bits, group):
g = w.reshape(-1, group) # every row of g is one group
q, s = quant_symmetric(g, bits, axis=1)
return q, s
def report(name, w_hat, bytes_used):
err = W - w_hat
rel = np.linalg.norm(err) / np.linalg.norm(W)
y, y_hat = W @ x, w_hat @ x
out_err = np.linalg.norm(y - y_hat) / np.linalg.norm(y)
print(f"{name:<28} {bytes_used / 1024:7.1f} KiB max|err| {np.abs(err).max():.5f} "
f"rel err {rel * 100:5.2f}% output err {out_err * 100:5.2f}%")
fp32_bytes = W.size * 4
print(f"weight matrix {ROWS}x{COLS} = {W.size:,} weights")
print(f"{'method':<28} {'memory':>11}")
report("float32 (original)", W, fp32_bytes)
report("float16", W.astype(np.float16).astype(np.float32), W.size * 2)
q, s = quant_symmetric(W, 8)
report("int8 symmetric, per-tensor", q * s, W.size + 4)
q, s, z = quant_asymmetric(W, 8)
report("uint8 asymmetric, per-tensor", (q - z) * s, W.size + 8)
q, s = quant_symmetric(W, 8, axis=1)
report("int8 symmetric, per-row", q * s, W.size + ROWS * 4)
q, s = quant_symmetric(W, 4)
report("int4 symmetric, per-tensor", q * s, W.size // 2 + 4)
for G in (128, 32):
q, s = quant_groupwise(W, 4, G)
n_groups = W.size // G
report(f"int4 group-wise (G={G})", (q * s).reshape(W.shape), W.size // 2 + n_groups * 2)
print()
print("A worked example: 6 weights, int8 symmetric")
w = np.array([0.12, -0.50, 0.03, 0.81, -0.27, 0.00], dtype=np.float32)
q, s = quant_symmetric(w, 8)
print(" weights :", np.round(w, 3))
print(f" scale : {float(s):.6f} (= 0.81 / 127)")
print(" int8 :", q.astype(int))
print(" restored :", np.round(q * s, 4))
print()
print("Why the outlier hurts per-tensor int4:")
q, s = quant_symmetric(W, 4)
zeros = float(np.mean(q == 0)) * 100
print(f" per-tensor scale {float(s):.4f}: {zeros:.1f}% of weights round to 0")
q, s = quant_groupwise(W, 4, 32)
zeros = float(np.mean(q == 0)) * 100
print(f" group-wise (32) scales: {zeros:.1f}% of weights round to 0")
print()
print("Whole-model weight memory (weights only, no KV cache):")
for params_b in (8, 70):
row = []
for name, bits in (("fp16", 16), ("int8", 8), ("4-bit", 4.5)): # 4.5: k-quants keep scales too
row.append(f"{name} {params_b * 1e9 * bits / 8 / 1e9:6.1f} GB")
print(f" {params_b:>2}B params: " + " ".join(row))W[3, 7] = 0.35: one outlier about 17 standard deviations from zero. Real models have such values, and they matter (deleting them breaks the model).quant_symmetric(w, bits, axis): the formula above. Withaxis=Nonethere is one scale for the tensor; withaxis=1one scale per row. The codes are stored inint8here even for 4 bits; a real format packs two 4-bit codes per byte, which the memory column accounts for.quant_asymmetric: the zero-point variant over the range 0…255.quant_groupwise(w, bits, group): reshape into rows ofgroupconsecutive weights and give each row its own scale.report(...): memory, the largest single error, the relative weight error and the relative error ofW @ x.- The last block repeats the whole-model memory arithmetic for 8B and 70B models.
weight matrix 256x512 = 131,072 weights
method memory
float32 (original) 512.0 KiB max|err| 0.00000 rel err 0.00% output err 0.00%
float16 256.0 KiB max|err| 0.00010 rel err 0.02% output err 0.02%
int8 symmetric, per-tensor 128.0 KiB max|err| 0.00138 rel err 3.96% output err 4.32%
uint8 asymmetric, per-tensor 128.0 KiB max|err| 0.00086 rel err 2.48% output err 2.56%
int8 symmetric, per-row 129.0 KiB max|err| 0.00138 rel err 0.79% output err 0.83%
int4 symmetric, per-tensor 64.0 KiB max|err| 0.02500 rel err 70.13% output err 80.37%
int4 group-wise (G=128) 66.0 KiB max|err| 0.02495 rel err 11.99% output err 12.55%
int4 group-wise (G=32) 72.0 KiB max|err| 0.02454 rel err 9.81% output err 9.89%
A worked example: 6 weights, int8 symmetric
weights : [ 0.12 -0.5 0.03 0.81 -0.27 0. ]
scale : 0.006378 (= 0.81 / 127)
int8 : [ 19 -78 5 127 -42 0]
restored : [ 0.1212 -0.4975 0.0319 0.81 -0.2679 0. ]
Why the outlier hurts per-tensor int4:
per-tensor scale 0.0500: 78.8% of weights round to 0
group-wise (32) scales: 13.2% of weights round to 0
Whole-model weight memory (weights only, no KV cache):
8B params: fp16 16.0 GB int8 8.0 GB 4-bit 4.5 GB
70B params: fp16 140.0 GB int8 70.0 GB 4-bit 39.4 GBRead it from the top. Float16 is essentially free (0.02% error). Int8 with one scale already loses 4% because of the outlier, while int8 with one scale per row loses under 1% for the same memory. At 4 bits the difference is dramatic: one scale for the whole tensor destroys the layer (80% output error, with 79% of the weights rounded to zero), while groups of 32 bring it back to about 10% for an extra 8 KiB. Real 4-bit formats do better still than our plain rounding, using the tricks below, but the lesson holds: how you choose scales matters as much as how many bits you keep.
Formats and methods you will meet
The plain rounding in our script is called round-to-nearest (RTN). Practical methods improve on it in two ways: smarter storage formats, and smarter choices of what to round where, using a little calibration data.
- GGUF is the single-file format of the llama.cpp project, used by Ollama and LM Studio Public. One file holds the quantised tensors plus metadata: architecture, tokenizer, and usually the chat template. Its quantisation types have names like
Q8_0,Q5_K_MorQ4_K_M. Conceptually, the "K" types use blocks inside larger super-blocks, with the block scales themselves quantised, and the suffix (S, M, L) says how many of the most sensitive tensors are kept at higher precision.Q4_K_Mis a common default, at roughly 4.8 bits per weight. These are weight-only formats aimed at CPUs and Apple and consumer GPUs. - GPTQ (Frantar et al., 2022, arXiv:2210.17323) quantises a model layer by layer using a few hundred calibration examples. After rounding each column it adjusts the not-yet-rounded weights to compensate for the error, using approximate second-order information. It makes 4-bit GPU inference with small quality loss practical Industry practice.
- AWQ (Lin et al., 2023, arXiv:2306.00978, "activation-aware weight quantization") observes that a small fraction of weight channels, the ones multiplied by large activations, matter most, and scales them up before quantising so they lose less precision Industry practice.
- Int8 and FP8 for weights and activations. LLM.int8() (Dettmers et al., 2022) keeps the few outlier activation features in 16-bit and the rest in int8; SmoothQuant (Xiao et al., 2022) moves the outlier difficulty from activations into weights so both can be 8-bit. Newer data-centre GPUs support 8-bit floating point (FP8) natively, which servers use to speed up the compute-bound prefill too Industry practice.
- NF4, from QLoRA, is a 4-bit format whose 16 levels follow a normal distribution. It is mainly used to hold a frozen model during fine-tuning (lesson 10.5); for serving, the methods above are more common.
Weight-only quantisation (GGUF, GPTQ, AWQ) shrinks memory and speeds up memory-bound decode; the arithmetic itself still happens in 16-bit after the weights are expanded on the fly. Quantising activations as well (W8A8) also speeds up compute-bound prefill, but is harder to do without quality loss.
Quality versus size: how to choose
A useful rule of thumb from community testing of open models is that 8-bit is very close to the 16-bit original, 5 and 4-bit "K" quantisations lose a little (often hard to notice in chat, more visible in maths, code and long reasoning), and below 4 bits quality drops quickly. Another rule is that a larger model at 4 bits usually beats a smaller model at 16 bits that takes the same memory. Treat both as starting points rather than laws: the effect depends on the model, the method and the task. The only reliable answer is to run your evaluation set (lesson 10.8) on the candidate quantisations and compare quality, speed and memory.
Why outliers exist, KV cache quantisation, and the limits of perplexity
Large transformers develop a few outlier features: specific hidden dimensions with values tens of times larger than the rest, appearing consistently across tokens. Dettmers et al. (2022, arXiv:2208.07339) reported that they emerge as models grow past a few billion parameters and that zeroing them destroys performance. They sit mostly in activations, which is why weight-only 4-bit works well while naive 8-bit activations do not.
The KV cache can be quantised too, to 8 bits or lower, which halves its memory and doubles the number of concurrent long conversations a GPU can hold. Engines such as vLLM and llama.cpp offer this as an option; it costs a little accuracy on long contexts Industry practice.
Quantisation quality is often reported as perplexity on a text corpus, or as the KL divergence between the quantised and original output distributions. These are convenient but can hide damage on specific skills: a model can keep its perplexity and still lose accuracy on arithmetic or rare languages. Task-level evaluations are more trustworthy.
Finally, whether and how Anthropic quantises Claude when serving it is not public Not public. Everything here applies to open-weight models you run yourself.
Common mistakes and debugging tips
Judging a quantisation by one chat
A 3-bit model answers "hello" nicely, so it is shipped. A week later users report wrong totals in calculations and broken JSON.
Fix: evaluate on a fixed set of real tasks, including the hard ones (maths, code, structured output, long inputs), and compare against the 16-bit or 8-bit version.
Forgetting that "4-bit" is not 4 bits
An 8B model at "4 bits" is planned as 4 GB and does not fit, because scales add 0.5 to 1 bit per weight, some tensors are kept at higher precision, and the KV cache and runtime need memory too.
Fix: use the real file size, plus KV cache and about 1 GB of overhead, as lesson 11.3 does.
Quantising with one scale per tensor
Home-made quantisation code uses abs(W).max() for the whole matrix and the model outputs gibberish, exactly as in the script's "int4 per-tensor" row.
Fix: use per-channel or group-wise scales, or better, an established tool (llama.cpp's quantiser, a GPTQ or AWQ library) rather than writing your own.
Mixing up the chat template after conversion
A converted model rambles or never stops. The weights are fine; the file lost or changed its chat template, so prompts are formatted wrongly.
Fix: check the template in the model's metadata (lesson 11.5) against the original model card.
Key takeaways
- Memory = parameters × bytes per parameter; 4-bit makes a model about 3.5× smaller than 16-bit and decodes faster for the same reason.
- Quantisation stores small integers plus scales; the scale is set by the largest value, so outliers need per-channel or group-wise scales.
- GGUF k-quants, GPTQ and AWQ improve on plain rounding; 8-bit is near-lossless, 4-bit is the usual sweet spot, below that quality falls quickly.
- Choose a quantisation by measuring on your own tasks; how Claude itself is served is not public.
Exercise: find the sweet spot
1) In quantize.py, add rows for int4 group-wise with G = 64 and G = 16, and for 3-bit group-wise with G = 32. Compute their memory with 16-bit scales. Which gives the best output error per KiB? 2) Remove the outlier line (W[3, 7] = 0.35) and run again: which rows improve most, and why?
Hint
3-bit codes take W.size * 3 // 8 bytes. Each group adds one 2-byte scale. quant_symmetric already accepts any number of bits.
Show a solution
1) Add for G in (128, 64, 32, 16): and a separate 3-bit call: q, s = quant_groupwise(W, 3, 32); report("int3 group-wise (G=32)", (q * s).reshape(W.shape), W.size * 3 // 8 + W.size // 32 * 2). You should see about 12% output error for G = 64 (68 KiB), 9.3% for G = 16 (80 KiB) and about 24% for 3-bit with G = 32 (56 KiB). Smaller groups lower the error but each halving of the group size buys less while costing more scale memory; groups of 32 to 64 are a good balance, which is why real formats use blocks of about that size. Dropping to 3 bits more than doubles the error.
2) Without the outlier, the per-tensor rows improve enormously: int8 per-tensor falls from about 4.3% to 1.2% output error, and int4 per-tensor from about 80% to 20%, because the scale is no longer stretched by one value. Int4 per-tensor is still worse than group-wise (about 10 to 13%), since even normal random weights have a few large values in a 131,072-weight matrix. The group-wise rows barely change: they were already protected.
Check your understanding
About how much memory do the weights of a 70-billion-parameter model need at roughly 4.5 bits per weight?
- About 9 GB
- About 40 GB
- About 140 GB
Why does one outlier weight hurt per-tensor 4-bit quantisation so badly?
- Because outliers cannot be stored in integers
- Because 4-bit formats have no sign bit
- Because it sets the scale, making the step so large that most ordinary weights round to zero
You have one 24 GB GPU. Which is usually the better choice for quality?
- A 14B-parameter model in 8-bit or a 30B-class model in 4-bit
- A 7B model in 32-bit floats
- A 70B model in 2-bit
Lesson 11.3Module 11: Deployment and production
CPU vs GPU inference
Learning objectives
- Explain why GPUs are faster than CPUs for LLMs, in terms of memory bandwidth and parallel compute.
- Estimate decode and prefill speed for a model on given hardware with two simple formulas.
- Add up the memory a deployment needs: weights, KV cache and overhead, and decide whether it fits.
- Choose sensibly between CPU, Apple unified memory, consumer GPUs and data-centre GPUs for a given job.
"Do I need a GPU?" is the first question everyone asks before running a model themselves. The honest answer is "it depends on the model size, how fast you need answers, and how many people use it at once", and this lesson turns that vague answer into arithmetic you can do in a minute. The surprise for most people is that the deciding number is usually not the famous TFLOPS figure on the box, but memory bandwidth.
Analogy: a kitchen and its pantry
A CPU is a kitchen with a few excellent chefs; a GPU is a kitchen with thousands of line cooks who can each do simple things very fast. But to cook each new dish (each token), every cook needs ingredients from the pantry (the weights in memory). If the corridor to the pantry is narrow, the thousands of cooks stand around waiting, and the dish takes as long as the trips to the pantry. A GPU's real advantage for LLMs is not only its many cooks but its very wide corridor: high-bandwidth memory delivering ten to fifty times more data per second than a laptop's RAM.
Why GPUs win
A CPU has a handful of powerful cores (8 to 64 or so) built for complicated, branching code, with large caches to hide memory delays. A GPU has thousands of simple arithmetic units built to apply the same operation to huge arrays at once, which is exactly what matrix multiplications are. Modern data-centre GPUs add tensor cores, units specialised for small matrix products in 16-bit or 8-bit precision. The result is roughly one to three orders of magnitude more arithmetic per second than a CPU.
The second difference matters even more for generating text. In lesson 11.1 you saw that each decode step reads every weight once to produce one token. A laptop's dual-channel DDR5 memory moves something like 60 to 100 GB/s; Apple's unified memory roughly 100 to 800 GB/s depending on the chip; a consumer GPU's GDDR memory around 500 to 1,800 GB/s; a data-centre GPU's high-bandwidth memory (HBM) around 2,000 to 8,000 GB/s (all approximate, as of 2026). The ratio of these numbers is, almost exactly, the ratio of their decode speeds.
Two formulas for speed
For a single user, every decode step must read the weights (and the KV cache) once, so the best possible speed is the bandwidth divided by the bytes read. Real software reaches perhaps 50 to 80% of the peak, so we multiply by an efficiency factor:
In words: a 4.8 GB model on memory that delivers 270 GB/s can be read about 56 times per second; at 60% efficiency that is about 34 tokens per second. Halve the model size (quantisation, lesson 11.2) and the speed roughly doubles.
Prefill is different: all prompt tokens share each weight read, so it is limited by arithmetic. A forward pass costs about 2 floating-point operations per parameter per token (one multiply and one add), so:
In words: an 8B model needs about 16 billion operations per prompt token; a chip that sustains 15 trillion operations per second can read roughly 560 prompt tokens per second at 60% efficiency. This is why long prompts are so much slower on a CPU, which has little compute, than on a GPU.
Will it fit? Weights + KV cache + overhead
Speed is irrelevant if the model does not fit in the memory the processor can use quickly: VRAM for a GPU, RAM for a CPU, the shared pool for Apple's unified memory. (If a model spills from VRAM into system RAM, runtimes such as llama.cpp can split layers between GPU and CPU, but the CPU part then sets the pace.) The total is:
- Weights: parameters × bits per weight ÷ 8 (lesson 11.2).
- KV cache: 2 (keys and values) × layers × KV heads × head dimension × tokens × bytes per number, for each active conversation. Grouped-query attention (GQA), used by most current open models, shares each key/value head among several query heads and cuts this by 4 to 8 times (lesson 6.8).
- Overhead: the runtime, temporary buffers and the operating system: budget at least 1 GB, more on a GPU shared with a desktop.
The same arithmetic appears in lesson 10.6 for training, where gradients and optimiser states make the numbers far larger. Inference needs only the weights and the cache.
An estimator in Python
The script applies both formulas, plus the memory check, to three model configurations on five classes of hardware. The hardware numbers are rough representatives of each class, not benchmarks of specific products.
# @run
# Rough tokens/second and memory estimates for running an LLM on different hardware.
# Decode is usually memory-bandwidth bound: every new token reads (almost) all weights once,
# tokens/s ~ efficiency * bandwidth / bytes_of_weights
# Prefill is usually compute bound: about 2 * params FLOPs per prompt token,
# prompt tokens/s ~ efficiency * peak_FLOPs / (2 * params)
# All hardware numbers are approximate, as of 2026. Real results vary by software, settings and model.
from dataclasses import dataclass
BITS = {"fp16": 16.0, "q8_0": 8.5, "q4_k_m": 4.8} # effective bits per weight incl. scales
@dataclass
class Hardware:
name: str
mem_gb: float # memory the model can use (VRAM, or RAM for CPU / unified memory)
bw_gbs: float # memory bandwidth, GB/s
tflops: float # usable dense fp16 TFLOPs (rough)
HARDWARE = [
Hardware("Laptop CPU, DDR5 dual channel", 32, 80, 1.0),
Hardware("Apple M-series Pro (unified)", 36, 270, 15),
Hardware("Apple M-series Max (unified)", 64, 540, 30),
Hardware("Consumer GPU, 24 GB", 24, 1000, 150),
Hardware("Data-centre GPU, 80 GB", 80, 3300, 900),
]
def weight_gb(params_b, quant):
return params_b * 1e9 * BITS[quant] / 8 / 1e9
def kv_cache_gb(layers, kv_heads, head_dim, context, bytes_per=2):
# 2 (K and V) x layers x kv_heads x head_dim x tokens x bytes
return 2 * layers * kv_heads * head_dim * context * bytes_per / 1e9
def estimate(params_b, quant, hw, kv_gb, efficiency=0.6):
w = weight_gb(params_b, quant)
need = w + kv_gb + 1.0 # +1 GB runtime overhead (rough)
if need > hw.mem_gb:
return w, need, None, None
decode = efficiency * hw.bw_gbs / w # tokens per second, one user
prefill = efficiency * hw.tflops * 1e12 / (2 * params_b * 1e9)
return w, need, decode, prefill
# A Llama-style 8B model: 32 layers, 8 KV heads (grouped-query attention), head_dim 128
kv8 = kv_cache_gb(32, 8, 128, 8192)
print(f"KV cache for an 8B GQA model at 8,192 tokens (fp16): {kv8:.2f} GB")
print(f"Same model WITHOUT GQA (32 KV heads): {kv_cache_gb(32, 32, 128, 8192):.2f} GB")
print()
for params_b, quant in ((8, "q4_k_m"), (8, "fp16"), (70, "q4_k_m")):
kv = kv8 if params_b == 8 else kv_cache_gb(80, 8, 128, 8192)
print(f"== {params_b}B model, {quant}: weights {weight_gb(params_b, quant):.1f} GB ==")
for hw in HARDWARE:
w, need, dec, pre = estimate(params_b, quant, hw, kv)
if dec is None:
print(f" {hw.name:<32} needs ~{need:5.1f} GB > {hw.mem_gb:.0f} GB: does not fit")
else:
print(f" {hw.name:<32} ~{dec:6.1f} tok/s decode ~{pre:8,.0f} tok/s prefill")
print()
# Time for a typical chat turn: 1,000-token prompt, 300-token answer
hw = HARDWARE[1]
w, need, dec, pre = estimate(8, "q4_k_m", hw, kv8)
ttft = 1000 / pre
total = ttft + 300 / dec
print(f"8B q4_k_m on '{hw.name}': 1,000-token prompt + 300-token answer")
print(f" time to first token ~{ttft:.2f} s, whole answer ~{total:.1f} s")
print()
print("Batching on a GPU: weights are read once per step for the whole batch")
print("(ignores KV-cache reads, which grow with batch x context):")
hw = HARDWARE[3]
w = weight_gb(8, "q4_k_m")
for batch in (1, 8, 32, 128):
step = max(w / (0.6 * hw.bw_gbs), batch * 2 * 8e9 / (0.6 * hw.tflops * 1e12))
print(f" batch {batch:3d}: ~{batch / step:7,.0f} tok/s total, ~{1 / step:5.0f} tok/s per user")BITS: effective bits per weight for three common formats, including the space taken by scales.Hardware: usable memory, bandwidth and dense 16-bit TFLOPS for each class (approximate, as of 2026).kv_cache_gb(...): the KV cache formula above, in 16-bit.estimate(...): checks that weights + cache + 1 GB fit; if so, applies the decode formula (bandwidth ÷ weight bytes) and the prefill formula (FLOP/s ÷ 2 × parameters), both with 60% efficiency.- The batching loop at the end: a decode step for a batch costs the larger of "read the weights once" and "do the arithmetic for every sequence in the batch".
KV cache for an 8B GQA model at 8,192 tokens (fp16): 1.07 GB
Same model WITHOUT GQA (32 KV heads): 4.29 GB
== 8B model, q4_k_m: weights 4.8 GB ==
Laptop CPU, DDR5 dual channel ~ 10.0 tok/s decode ~ 38 tok/s prefill
Apple M-series Pro (unified) ~ 33.8 tok/s decode ~ 562 tok/s prefill
Apple M-series Max (unified) ~ 67.5 tok/s decode ~ 1,125 tok/s prefill
Consumer GPU, 24 GB ~ 125.0 tok/s decode ~ 5,625 tok/s prefill
Data-centre GPU, 80 GB ~ 412.5 tok/s decode ~ 33,750 tok/s prefill
== 8B model, fp16: weights 16.0 GB ==
Laptop CPU, DDR5 dual channel ~ 3.0 tok/s decode ~ 38 tok/s prefill
Apple M-series Pro (unified) ~ 10.1 tok/s decode ~ 562 tok/s prefill
Apple M-series Max (unified) ~ 20.2 tok/s decode ~ 1,125 tok/s prefill
Consumer GPU, 24 GB ~ 37.5 tok/s decode ~ 5,625 tok/s prefill
Data-centre GPU, 80 GB ~ 123.8 tok/s decode ~ 33,750 tok/s prefill
== 70B model, q4_k_m: weights 42.0 GB ==
Laptop CPU, DDR5 dual channel needs ~ 45.7 GB > 32 GB: does not fit
Apple M-series Pro (unified) needs ~ 45.7 GB > 36 GB: does not fit
Apple M-series Max (unified) ~ 7.7 tok/s decode ~ 129 tok/s prefill
Consumer GPU, 24 GB needs ~ 45.7 GB > 24 GB: does not fit
Data-centre GPU, 80 GB ~ 47.1 tok/s decode ~ 3,857 tok/s prefill
8B q4_k_m on 'Apple M-series Pro (unified)': 1,000-token prompt + 300-token answer
time to first token ~1.78 s, whole answer ~10.7 s
Batching on a GPU: weights are read once per step for the whole batch
(ignores KV-cache reads, which grow with batch x context):
batch 1: ~ 125 tok/s total, ~ 125 tok/s per user
batch 8: ~ 1,000 tok/s total, ~ 125 tok/s per user
batch 32: ~ 4,000 tok/s total, ~ 125 tok/s per user
batch 128: ~ 5,625 tok/s total, ~ 44 tok/s per userThree lessons hide in this output. First, a 4-bit 8B model is genuinely usable on a laptop CPU (about 10 tokens per second, roughly reading speed), but long prompts are slow there: 38 prompt tokens per second means a 1,000-token prompt waits almost half a minute. Second, the 16-bit version of the same model is three times slower everywhere, purely because it is three times bigger. Third, a 70B model is out of reach for most personal hardware even at 4 bits, except machines with 64 GB or more of fast unified memory.
The batching table shows why GPUs are economical for serving many people. Up to a point, adding users is almost free, because the weights are read once per step for the whole batch: 32 users get the same per-user speed as one, and the GPU produces 32 times more tokens. Only past a batch of about 45 (between the 32 and 128 rows) does the arithmetic catch up, so per-user speed falls at 128. A CPU has too little compute for this to help much, which is why CPU inference suits one person, and GPU inference suits a service.
Pick a model and hardware, or type your own machine's memory and bandwidth. The estimate uses the formulas above with 60% efficiency and assumes grouped-query attention. Treat the result as a rough guide, not a benchmark.
Choosing hardware
| Option | Good for | Limits |
|---|---|---|
| CPU only (any laptop or server) | learning, small models (1 to 8B at 4 bits), batch jobs where speed does not matter, privacy on modest hardware | slow prefill, a few to about 15 tokens/s, no benefit from batching |
| Apple silicon (unified memory) | personal use of mid-size and even 70B models on high-memory machines; quiet and power-efficient | less compute than a big GPU, so long prompts are slower; not a multi-user server |
| Consumer GPU (8 to 32 GB) | fast local inference of models that fit in VRAM; small team servers | VRAM is the hard ceiling; offloading layers to the CPU slows everything down |
| Data-centre GPUs (rented) | serving many users, large models, high throughput with vLLM, TGI or similar | cost per hour (rent only while needed), operational effort |
| A hosted API (such as Claude) | frontier quality, no hardware to manage, pay per token | data leaves your machine, per-token cost at very high volume, provider limits |
As a rough guide to cost, a single data-centre GPU rents for a few dollars per hour (approximate, as of 2026; prices vary a lot by provider and commitment). An idle rented GPU costs the same as a busy one, so self-hosting only pays when it is kept busy, a point lesson 11.9 returns to. For occasional or low-volume use, an API is almost always cheaper than owning or renting hardware.
The roofline model and arithmetic intensity
Whether an operation is limited by compute or by memory depends on its arithmetic intensity: floating-point operations per byte moved. Each chip has a "ridge point", its peak FLOP/s divided by its bandwidth. Below that intensity it is memory-bound; above it, compute-bound. For a data-centre GPU with about 900 TFLOP/s and 3.3 TB/s, the ridge is around 270 operations per byte.
A decode step for one sequence with 16-bit weights does 2 operations per weight per 2 bytes read: an intensity of about 1, hundreds of times below the ridge, so the GPU's compute sits mostly idle. A batch of B sequences reuses each weight B times, raising the intensity to about B; prefill with P prompt tokens raises it to about P. That is the whole reason batching and long prompts use the hardware well, and the reason the batching table above stops scaling between batch 32 and 128 for the consumer GPU: its ridge is about 150 operations per byte, and with 4-bit weights (about 0.6 bytes each) a batch of B gives an intensity of about 3.3 × B, which crosses the ridge near B = 45.
Two refinements matter at scale. The KV cache is also read every step, and for long contexts and big batches it can exceed the weights, making decode memory-bound again however large the batch. And splitting a model across several GPUs (tensor parallelism) adds the bandwidth of every GPU but also communication between them over fast links, which is why multi-GPU servers use special interconnects.
Common mistakes and debugging tips
Comparing hardware by TFLOPS alone
A chip with twice the compute but the same memory bandwidth generates single-user text at the same speed, because decode is memory-bound.
Fix: for chat-style use compare bandwidth first; compare compute for long prompts and batched serving.
The model "runs on the GPU" but is slow
The runtime silently put part of the model on the CPU because it did not fit in VRAM, or the GPU driver is missing and everything runs on the CPU.
Fix: check how many layers were offloaded (ollama ps shows the CPU/GPU split; llama.cpp prints it at start-up), use a smaller quantisation or a shorter context, and confirm the GPU is visible (nvidia-smi on NVIDIA systems).
Sizing for one user and serving twenty
It worked in testing; in production, twenty concurrent conversations with long histories exhaust memory with their KV caches.
Fix: multiply the KV cache by the expected concurrency and context, cap both in the server configuration, and load-test before launch.
Ignoring the prompt side on CPUs
A CPU setup streams at 10 tokens/s, which looks fine, but a RAG prompt with 4,000 tokens of retrieved text waits over a minute before the first word.
Fix: estimate prefill too. On CPUs keep prompts short, or move to a GPU or unified-memory machine for document-heavy work.
Key takeaways
- Decode speed ≈ efficiency × bandwidth ÷ model bytes; prefill speed ≈ efficiency × FLOP/s ÷ (2 × parameters).
- Memory needed = weights + KV cache per user × users + overhead; it must fit in fast memory.
- CPUs and unified memory suit one person; GPUs shine when batching many users, because weights are read once per step for the whole batch.
- All hardware numbers here are approximate (as of 2026): measure on your own machine.
Exercise: size a small team server
A team of 10 wants a private assistant on a 14B model at 4 bits (about 4.8 bits per weight), with up to 4 people chatting at once and 16,000 tokens of context each. The model has 48 layers, 8 KV heads and a head dimension of 128. 1) How much memory does it need? 2) Would a 24 GB consumer GPU do? 3) What single-user decode speed would you expect on it? Use kv_cache_gb from the script or the demo.
Hint
Weights: 14 × 10⁹ × 4.8 ÷ 8 bytes. KV cache: 2 × 48 × 8 × 128 × 16,000 × 2 bytes per user. Then add 1 GB.
Show a solution
1) Weights ≈ 8.4 GB; KV cache ≈ 3.1 GB per user, 12.6 GB for four; plus 1 GB overhead ≈ 22 GB. 2) It fits a 24 GB GPU, with little room to spare: quantising the KV cache to 8 bits or capping the context at 8,000 tokens would add safety. 3) About 0.6 × 1,000 ÷ 8.4 ≈ 70 tokens per second for one user, staying close to that for a few users thanks to batching.
Check your understanding
Two machines have the same compute but one has twice the memory bandwidth. For one person chatting with a model that fits on both, which statement is right?
- Both generate text at the same speed
- The higher-bandwidth machine generates about twice as fast
- The higher-bandwidth machine only helps with long prompts
Why does batching 16 users on a GPU barely slow each user down?
- Each decode step reads the weights once for the whole batch, and the GPU has spare compute while it waits for memory
- Each user gets their own copy of the weights
- Batching skips the KV cache
An 8B model at 4 bits runs at 10 tokens/s on a laptop CPU. What will most limit a RAG feature that adds 5,000 tokens of documents to each prompt?
- The decode speed
- The tokenizer
- The prefill time: a CPU has little compute, so reading 5,000 prompt tokens takes a long time
Lesson 11.4Module 11: Deployment and production
Running open-source LLMs locally
Learning objectives
- Decide when a local open-weight model is the right choice and when a hosted model such as Claude is better.
- Choose a model family, size and quantisation that fit your hardware and task, and check its licence.
- Install and run a model with Ollama, and call it from Python and from the module 7 Mini Chat.
- Run a local model server safely: what to expose, what never to expose, and how to compare models fairly.
In module 1 you sent the same conversation to Claude and to a small open model on your own computer, and we said that the open model "makes more mistakes, but is free, private and runs offline". In module 5 you saw how far your tiny GPT was from real models. This lesson is about running real open-weight models properly: picking one, running it, measuring it and connecting it to your apps.
Analogy: cooking at home or eating at a restaurant
A top restaurant (a frontier model behind an API) cooks better than you, needs no kitchen, and you pay for each meal. Cooking at home (a local model) is cheaper per meal once you own the kitchen, completely private, works when the restaurants are closed, and you can change any recipe. But your kitchen is smaller, and some dishes are simply beyond it. Most people do both, choosing per meal. The skill is knowing which meal is which.
Local or hosted?
Reasons to run locally
- Privacy and compliance: prompts and documents never leave your machine or your network.
- Offline: works on a plane, in a lab, behind an air gap.
- Cost at volume: no per-token bill; a busy GPU you own can be cheaper than an API for large, simple workloads.
- Control: a fixed model version that never changes under you, any sampling settings, fine-tuning with LoRA (lesson 10.5).
- Learning: you can see everything, from the chat template to the logits.
Reasons to use a hosted model
- Quality: frontier models such as Claude are much stronger at hard reasoning, long agentic tasks and coding than models that fit on personal hardware.
- No operations: no hardware, drivers, updates or scaling to manage.
- Long context and features: very large context windows, tool use, citations, prompt caching and batch processing come built in.
- Low or spiky volume: paying per token beats paying for idle hardware.
A small open model makes more mistakes than a frontier model: it follows complex instructions less reliably, invents facts more often and loses track in long tasks. For classification, extraction, summarising short texts, simple chat and drafting, a good 7 to 14B model is often enough; for multi-step reasoning across a codebase, it usually is not. Many products route between both, as lesson 11.9 shows.
Choosing a model
Open-weight means the trained weights can be downloaded; it does not always mean "open source" in the software sense, since the training data and code are usually not released and the licence may restrict use. The best-known families, each released in several sizes, include Meta's Llama, Mistral's models, Alibaba's Qwen, Google's Gemma, Microsoft's Phi and DeepSeek's models. New versions appear every few months, so check current rankings and model cards rather than trusting any list, including this one.
- Pick the instruct (chat) version, not the base model, unless you plan to fine-tune (lesson 10.1).
- Pick a size that fits your memory at 4 to 8 bits, with room for the KV cache (lesson 11.3). On a 16 GB laptop that means roughly 3 to 8B; on 32 to 36 GB up to about 14 to 32B; 70B needs about 48 GB or more.
- Check the abilities you need: languages, tool calling (only some models are trained for it; lesson 9.9 used one), vision, context length, coding.
- Read the licence on the model card: some allow any use, some restrict commercial use above a number of users, require attribution, or forbid certain uses.
- Measure two or three candidates on your own examples (lesson 10.8) before choosing.
Tell it about your machine and your job. It suggests a size class and quantisation using the memory rules from lesson 11.3 (approximate; real models of the same size differ).
The local toolbox
- Your app
- Anything that can send HTTP: the module 7 Mini Chat (its Ollama provider), the agent of lesson 9.9, or the Python client below.
- Local HTTP API
- Ollama listens on port 11434 of localhost by default. It has its own API (/api/chat, /api/generate) and an OpenAI-compatible one under /v1.
- Ollama server
- Downloads models, loads them into memory on first use, keeps them loaded for a few minutes, and unloads them when idle or when memory is needed.
- Inference engine
- Ollama builds on llama.cpp-style kernels for CPUs, Apple Metal and CUDA/ROCm GPUs. llama.cpp can also be used directly (llama-server, llama-cli).
- Model files
- Quantised weights plus metadata (tokenizer, chat template, defaults) in GGUF, stored in Ollama's model folder.
- Hardware
- Layers go to the GPU if they fit; any that do not run on the CPU, which then sets the pace (lesson 11.3).
- CLI
- The ollama command talks to the same server: pull downloads, run chats in the terminal, ps shows what is loaded and where.
- Ollama (ollama.com): the simplest way to start. One install, a library of ready-quantised models, a local API. Used in this course since module 1.
- llama.cpp: the C/C++ engine and GGUF format underneath many local tools; its
llama-serverexposes an OpenAI-compatible API and gives fine control over threads, GPU layers and context. - LM Studio and similar desktop apps: a graphical way to download and chat with GGUF models, plus a local server.
- Hugging Face transformers: the Python library for running (and fine-tuning) models in their original format; flexible, best with a GPU (lesson 11.5).
- vLLM, TGI and similar servers: built for throughput on GPUs with continuous batching and paged KV caches (lesson 11.1). Choose these when many people share a model.
Run a model with Ollama
Install Ollama from its website, then in a terminal:
ollama pull llama3.2 # download a small instruct model once (a couple of GB)
ollama run llama3.2 # chat in the terminal; type /bye to leave
ollama list # models on disk, with sizes
ollama ps # models in memory, and how much is on the GPU vs the CPU
curl http://localhost:11434/api/chat -d '{"model":"llama3.2","stream":false,
"messages":[{"role":"user","content":"Say hello in five words."}]}'Model names have tags for size and quantisation (for example a model name followed by :3b or :8b, sometimes with a quantisation such as q8_0); the library page of each model on ollama.com lists them. The default tag is usually a 4-bit quantisation of the most popular size. The same commands work for any model in the library.
From code, Ollama's native chat endpoint streams one JSON object per line (NDJSON, which you parsed in lesson 7.5). This client uses only the standard library:
# Call a local Ollama server from Python with only the standard library.
# needs: Ollama running (ollama serve) and a pulled model (ollama pull llama3.2)
import json
import urllib.request
URL = "http://localhost:11434/api/chat"
def chat(messages, model="llama3.2", temperature=0.7):
body = {"model": model, "messages": messages, "stream": True,
"options": {"temperature": temperature}}
req = urllib.request.Request(URL, data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"})
reply = []
with urllib.request.urlopen(req, timeout=120) as resp:
for line in resp: # NDJSON: one JSON object per line
chunk = json.loads(line)
piece = chunk.get("message", {}).get("content", "")
print(piece, end="", flush=True)
reply.append(piece)
if chunk.get("done"):
print(f"\n[{chunk.get('eval_count', 0)} tokens generated]")
break
return "".join(reply)
if __name__ == "__main__":
history = [{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain a KV cache in two sentences."}]
answer = chat(history)
history.append({"role": "assistant", "content": answer})This file needs a running Ollama server, so our automated tests only check that it compiles; they did not execute it.
URL = "http://localhost:11434/api/chat": Ollama's native chat endpoint on the default port.body: the model name, the messages (the same role/content shape as Claude's Messages API, but here asystemmessage goes inside the list),"stream": True, andoptions. For local models you may settemperatureand other sampling options freely.for line in resp: each line is one JSON object with a piece of the answer inmessage.content.if chunk.get("done"): the last object also carries statistics such aseval_count(output tokens) and timings, useful for measuring tokens per second.history.append(...): as with any chat model, the server keeps no memory: your app resends the history every turn (lesson 7.2).
Expected output (it differs on every run, since sampling is random):
A KV cache stores the attention keys and values of tokens already processed, so each new
token only computes its own. This makes generation much faster at the cost of extra memory.
[38 tokens generated]Your module 7 Mini Chat already speaks to Ollama: choose its Ollama provider (or the OpenAI-compatible one pointed at http://localhost:11434/v1), and allow the page's origin when starting the server, as lesson 7.10 explains. The same is true of most tools that support "OpenAI-compatible" endpoints: you can swap a hosted model for a local one by changing a base URL.
Running a local server safely
By default Ollama listens only on 127.0.0.1, so only programs on your own computer can reach it. Its API has no authentication: anyone who can reach the port can use your hardware, download models and read the names of what you have. If you set OLLAMA_HOST=0.0.0.0 to share it on a network, put it behind something that checks who is calling (the API server of lesson 11.6, or a reverse proxy with authentication), and never expose it directly to the internet. Treat models you download like software: get them from the official library or the original publisher's page, and prefer the safetensors or GGUF formats, which contain only data (lesson 11.5).
Comparing local models fairly, and what "open" really means
Comparisons between models are easy to get wrong. Use the same prompts, the same chat template (each model's own), the same sampling settings (greedy or a fixed temperature and seed), the same quantisation level, and enough examples to see a real difference. Ollama's final stream object reports prompt and output token counts and durations, so you can compute prefill and decode speed for each model on your hardware. Public leaderboards are a useful first filter, but popular benchmarks leak into training data over time (lesson 10.8).
"Open" covers a spectrum. Some releases include only weights under a custom licence; some use standard permissive licences such as Apache 2.0 or MIT; a few also publish training code and data. The Open Source Initiative published an "Open Source AI Definition" in 2024 that requires much more than weights. When it matters, for example for a product, read the actual licence text rather than the label. Claude's weights are not released; it is available only as a hosted service Public.
Common mistakes and debugging tips
Expecting frontier quality from a 3B model
A small model is asked to refactor a whole project and produces confident nonsense; the conclusion is "local models are useless".
Fix: match the job to the model. Use small models for narrow tasks, try a larger quantised model if memory allows, and route hard tasks to a frontier model.
Slow first answer, fast afterwards
The first request after a pause takes many seconds: the model is being loaded from disk into memory. Ollama unloads idle models after a few minutes.
Fix: expected behaviour. For a service, send a warm-up request at start-up and set the keep-alive time (the keep_alive request field or the OLLAMA_KEEP_ALIVE setting) to keep it loaded.
Answers cut off or forgetting the start of long inputs
The runtime's default context length is smaller than the model's maximum, so long prompts are silently truncated.
Fix: set the context length explicitly (in Ollama the num_ctx option), remembering that a longer context needs more KV cache memory.
Exposing the Ollama port to the network
A server is started with OLLAMA_HOST=0.0.0.0 on a cloud machine for convenience; strangers find it and use the GPU for free.
Fix: keep it on localhost or a private network, and put an authenticated API in front (lessons 11.6 and 11.7).
Key takeaways
- Local models give privacy, offline use, control and low marginal cost; hosted frontier models give quality, features and no operations.
- Choose an instruct model that fits your memory at 4 to 8 bits, has the abilities you need, and a licence you can accept; then measure it.
- Ollama is the quickest start: pull, run, and call
localhost:11434; its OpenAI-compatible endpoint lets many tools swap in a local model. - A local model server has no authentication of its own: never expose it directly.
Exercise: a local model bake-off
Pull two small instruct models of different families (for example a Llama and a Qwen or Gemma model of similar size). Write five prompts typical of a job you care about, one of which needs exact output (for example "reply with only a JSON object with keys name and age"). Run each prompt on both models with the same settings, and record: whether the answer is right, the time to first token, and the output tokens per second. Which would you deploy, and would any prompt still go to a hosted model?
Hint
Modify ollama_client.py to send "options": {"temperature": 0, "seed": 1} and to print prompt_eval_count, prompt_eval_duration, eval_count and eval_duration from the final chunk (durations are in nanoseconds).
Show a solution
Decode speed = eval_count / (eval_duration / 1e9); prefill speed = prompt_eval_count / (prompt_eval_duration / 1e9). Typical findings: models of the same size differ more in instruction-following (the JSON prompt) than in speed; speed is mostly set by size and quantisation. A reasonable decision records accuracy first, then speed, then licence, and keeps the hardest prompts (multi-step reasoning, long documents) for a hosted model.
Check your understanding
Which job is the best fit for a 7B open model running locally?
- Planning and executing a change across twenty files of a large codebase
- Classifying thousands of private support emails into ten categories
- Answering questions that need knowledge of yesterday's news
What is true of Ollama's local API by default?
- It listens only on localhost and has no authentication
- It requires an API key on every request
- It is reachable from the internet so phones can use it
What does "open-weight" guarantee?
- The training data is published
- Any commercial use is allowed
- The trained weights can be downloaded; the licence still decides how you may use them
Lesson 11.5Module 11: Deployment and production
Ollama and Hugging Face concepts
Learning objectives
- Explain what is inside a model repository on the Hugging Face Hub: config, tokenizer, chat template, weight shards and model card.
- Run an open model with the transformers library and say what each step does.
- Customise a model in Ollama with a Modelfile (system prompt, parameters, template).
- Understand chat templates and safe weight formats well enough to debug a model that rambles, never stops or will not load.
Lesson 11.4 got a model running in a few commands. This lesson opens the box. Two ecosystems cover most of the open-model world: the Hugging Face Hub, where almost every open model is published in its original form, and Ollama (with llama.cpp and GGUF), where models are packaged for easy local use. Knowing how each is organised turns mysterious failures into five-minute fixes.
Analogy: a publisher's warehouse and a ready-meal shop
The Hugging Face Hub is like a publisher's warehouse: every book (model) in its original edition, with the author's notes, the exact typesetting rules and the licence on the first page. You can do anything with it, but you assemble it yourself. Ollama is like a shop selling ready meals made from those books: already cooked (quantised), portioned to fit your fridge (memory) and labelled with how to serve them (the chat template and defaults). Most of the time the ready meal is what you want; when it is wrong, you go back to the warehouse to see the original recipe.
What is inside a Hugging Face model repository
The Hub (huggingface.co) hosts models, datasets and demo apps as Git repositories with large-file storage. A model is named organisation/model-name, for example Qwen/Qwen2.5-0.5B-Instruct. A typical causal language model repository contains:
| File | What it holds |
|---|---|
README.md (the model card) | what the model is for, how it was trained and evaluated, limitations, the licence, and usage examples. Read it first. |
config.json | the architecture: number of layers, hidden size, attention and KV heads, vocabulary size, maximum positions. Everything you need for the memory maths of lesson 11.3. |
tokenizer.json, tokenizer_config.json | the vocabulary and merge rules (module 5), special tokens and, usually, the chat template. |
generation_config.json | default generation settings such as end-of-sequence tokens and recommended sampling values. |
model-00001-of-00004.safetensors … | the weights, split into shards of a few GB, plus an index file saying which tensor is in which shard. |
Some repositories are gated: you must accept the licence on the website and authenticate with an access token (usually through the HF_TOKEN environment variable or a login command) before downloading. Downloads are cached on disk (by default under ~/.cache/huggingface), so the second from_pretrained is instant. Many community repositories also publish ready-quantised versions of popular models: GGUF files for llama.cpp and Ollama, or GPTQ and AWQ versions for GPU servers (lesson 11.2).
Safe weight formats
Older repositories store weights as PyTorch .bin files, which use Python's pickle format. Loading a pickle can run arbitrary code hidden in the file, so a malicious "model" can take over your machine. safetensors was designed to hold only tensors and a small header, so loading it cannot execute code; GGUF is likewise a data-only format. Prefer them, and treat any pickle-based file from an unknown source as you would an unknown executable.
Running a model with transformers
The transformers library loads any supported architecture from its repository name. This is the most flexible way to run open models in Python, and the same objects are used for fine-tuning (lesson 10.5).
# Run an open-weight model with Hugging Face transformers.
# needs: pip install torch transformers accelerate (and a few GB of free disk + RAM/VRAM)
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct" # small, permissively licensed; check the model card first
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
device_map="auto", # GPU if present, else CPU (needs accelerate)
)
messages = [{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "What is quantization, in one sentence?"}]
# The chat template turns messages into the exact token format this model was trained on
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True,
return_tensors="pt").to(model.device)
with torch.no_grad():
out = model.generate(inputs, max_new_tokens=80, do_sample=True, temperature=0.7)
print(tokenizer.decode(out[0][inputs.shape[-1]:], skip_special_tokens=True))
# The one-line version (same thing, less control):
# from transformers import pipeline
# pipe = pipeline("text-generation", model=MODEL_ID)
# print(pipe(messages, max_new_tokens=80)[0]["generated_text"][-1]["content"])This script needs PyTorch, transformers and a model download of about 1 GB, so our tests only check that it compiles; they did not run it.
AutoTokenizer.from_pretrained(MODEL_ID): downloads (or reads from the cache) the tokenizer files and builds the right tokenizer class for this model.AutoModelForCausalLM.from_pretrained(..., torch_dtype=..., device_map="auto"): readsconfig.json, builds the architecture, loads the safetensors shards in 16-bit on a GPU (32-bit on a CPU), and places layers on the available devices.tokenizer.apply_chat_template(messages, add_generation_prompt=True, ...): renders the conversation with this model's own template and appends the header that tells the model "now the assistant speaks". This is the step most often done wrong by hand.model.generate(inputs, max_new_tokens=80, do_sample=True, temperature=0.7): the generation loop of lesson 11.1, with a KV cache and sampling. On your own model you may set any sampling options.out[0][inputs.shape[-1]:]:generatereturns prompt + answer; slicing keeps only the new tokens before decoding them to text.
Expected output (varies between runs because of sampling):
Quantization reduces the precision of a model's numbers, for example from 16-bit to 4-bit,
so it uses less memory and runs faster with only a small loss in quality.Chat templates: the format the model was trained on
A chat model never sees "messages". It sees one long token sequence in which special tokens mark who is speaking, exactly the format used during its supervised fine-tuning (lesson 6.3 and lesson 10.3). Each family uses its own markers. Give a model the wrong format and it may answer badly, continue the user's text, or never produce its end token and ramble until max_tokens. The template is stored with the model (in tokenizer_config.json as a small Jinja program, and in GGUF metadata), so libraries can apply it for you.
Type a system prompt and a user message, pick a family, and see roughly the text the model actually receives. Simplified: real templates also handle tools, multiple turns and edge cases; always use the model's own template.
Ollama concepts: models, Modelfiles and options
An Ollama model is a bundle of layers: the GGUF weights, the chat template, a default system prompt and default parameters. A Modelfile describes such a bundle, much as a Dockerfile describes an image (lesson 11.7). You can make your own variant of any model in a few lines:
# Modelfile: a support assistant built on a local model
FROM llama3.2
PARAMETER temperature 0.3
PARAMETER num_ctx 8192
SYSTEM """You are the support assistant for Acme Tools. Answer in at most three sentences.
If you are not sure, say so and suggest contacting support@acme.example."""ollama create acme-support -f Modelfile # build the variant (shares the weights, no copy)
ollama run acme-support # chat with it
ollama show llama3.2 --modelfile # see the template and parameters a model ships withFROM: the base model (a library name, or a local GGUF file path, for example one you converted or downloaded from the Hub).PARAMETER: defaults such astemperature,num_ctx(context length) orstopsequences. Requests can still override them throughoptions.SYSTEM: a default system prompt; a system message in the request replaces it.TEMPLATE: the chat template in Go template syntax. You rarely need to touch it; when a model you imported from a raw GGUF file rambles, a missing or wrong template is the usual cause.ADAPTER: a LoRA adapter to apply on top of the base model, such as one you trained in module 10 (converted to a format Ollama supports).
At run time a few more ideas matter: models are loaded on first use and kept in memory for a keep-alive period, several models can be loaded if memory allows, and the server can process a few requests in parallel. These settings live in environment variables of the server and in request fields, and their defaults change between versions, so check the current documentation on ollama.com when tuning them.
| Task | Hugging Face transformers | Ollama |
|---|---|---|
| Get a model | from_pretrained("org/name") or a download command | ollama pull name |
| Weights format | safetensors, usually 16-bit | GGUF, usually 4-bit |
| Chat formatting | apply_chat_template | automatic, from the model's template |
| Generation settings | generate(max_new_tokens=…, temperature=…) | options in the request or PARAMETER in a Modelfile |
| Serving | your own code, or a server such as vLLM or TGI | built in, on localhost:11434 |
| Best for | research, fine-tuning, full control, GPUs | local apps, laptops, quick experiments |
From a Hub checkpoint to a GGUF file, and how templates are executed
The usual path from a Hugging Face repository to a local quantised model goes through llama.cpp's tools: a conversion script reads config.json, the tokenizer files and the safetensors shards and writes a 16-bit GGUF file with all metadata (architecture, tokenizer, chat template); then a quantisation tool rewrites it to a type such as Q4_K_M. Some quantisation types benefit from an "importance matrix" computed on calibration text, similar in spirit to the calibration data of GPTQ and AWQ. Ollama can import the resulting file with FROM ./model.gguf. Not every new architecture is supported on day one; support arrives when the engine implements its layers.
On the Hub, chat templates are Jinja programs that loop over the messages and emit the special tokens. They can contain logic: Gemma-style templates fold the system prompt into the first user turn because the format has no system role; tool-capable templates render tool definitions and tool results in a model-specific way, which is why tool calling works only with models trained for it (lesson 9.9). Ollama re-expresses templates in Go's template language. If you build prompts by hand instead of using these templates, compare your string with apply_chat_template(..., tokenize=False) character by character.
Hosted APIs such as Claude's hide the template entirely: you send structured messages and the provider formats them. How Claude's conversations are formatted internally is not public Not public.
Common mistakes and debugging tips
Building the prompt string by hand
A developer writes "User: …\nAssistant:" for a model trained on ChatML. Answers are worse and sometimes the model writes the next "User:" line itself.
Fix: always use apply_chat_template (or a runtime that applies the model's template), with add_generation_prompt=True.
The model never stops
The end-of-turn token is not configured as a stop token, often after converting a model or writing a custom template.
Fix: check generation_config.json for the end tokens (some models have more than one), pass them to generate or as stop parameters, and set max_new_tokens as a safety net.
Loading pickle files from unknown repositories
An unofficial re-upload of a popular model contains .bin files; loading them can run code on your machine.
Fix: download from the original publisher, prefer safetensors or GGUF, and keep transformers' safe-loading defaults.
Out of memory when loading
A 7B model in float32 needs 28 GB; on a CPU, transformers loads 32-bit by default in this script.
Fix: use a smaller model, 16-bit on a GPU, a quantised GGUF through Ollama or llama.cpp on CPUs, or 4-bit loading on a GPU (module 10's bitsandbytes setup).
Key takeaways
- A Hub repository holds the model card, config, tokenizer with chat template, generation defaults and safetensors weight shards.
- transformers loads any supported model with
from_pretrained;apply_chat_templateproduces the exact format the model expects. - Ollama packages GGUF weights with a template and defaults; a Modelfile makes your own variant with
FROM,PARAMETER,SYSTEM. - Prefer data-only formats (safetensors, GGUF); a wrong template or missing stop token explains most "weird" model behaviour.
Exercise: build and inspect your own variant
1) Write a Modelfile that turns a local model into a "commit message writer": it must reply with a single line in the imperative mood, at most 72 characters. Create it with Ollama and try it on three diffs. 2) Run ollama show with --modelfile on the base model and identify its template's special tokens. Which template style from the demo does it use?
Hint
Use SYSTEM for the rules, a low temperature, and a PARAMETER stop on a newline so that the answer cannot run to a second line. Compare the tokens you see with the four styles in the renderer.
Show a solution
FROM llama3.2
PARAMETER temperature 0.2
PARAMETER stop "\n"
SYSTEM """Write one git commit message for the diff the user sends.
Imperative mood, at most 72 characters, no quotes, no trailing period."""Then ollama create commit-writer -f Modelfile and paste a diff after ollama run commit-writer. A Llama 3.x model shows <|start_header_id|> and <|eot_id|> markers: the Llama 3 style. Small models still break the 72-character rule sometimes, so a real tool would also check the length in code and retry.
Check your understanding
Where does a Hugging Face model usually store the format that turns messages into its token sequence?
- In
config.json - In the safetensors shards
- As the chat template in
tokenizer_config.json
config.json describes the architecture; the shards hold only tensors.Why is safetensors preferred over pickle-based .bin weight files?
- Loading it cannot execute code hidden in the file
- It makes the model more accurate
- It is the only format Ollama can read
In a Modelfile, what does PARAMETER num_ctx 8192 change?
- The number of model layers
- The context length the runtime allocates for the model
- The maximum number of users
num_ctx sets the context window the runtime uses, and with it the size of the KV cache. The architecture cannot be changed by a parameter, and concurrency is a server setting.Lesson 11.6Module 11: Deployment and production
API design
Learning objectives
- Design the contract of an LLM API: endpoints, request and response shapes, versioning and limits.
- Return errors clients can act on: the right status codes, one error format, request ids and Retry-After.
- Stream answers with Server-Sent Events and handle timeouts and cancellation at every hop.
- Read a complete FastAPI server that puts a local model or Claude behind your own authenticated API.
So far your apps have talked to a model directly: the browser to a proxy in module 7, Python scripts to Ollama or Claude. Real products put their own API in between. It is the one place where you decide who may call, how much, with which inputs, and what happens when something fails. This lesson designs that API and builds it with FastAPI; the next lessons package it (11.7), watch it (11.8) and defend it (11.9).
Analogy: a restaurant's front counter
Customers never walk into the kitchen. They order at a counter with a printed menu (the API contract): what you can order, what each dish contains, what it costs. The counter checks that you have paid (authentication), refuses impossible orders politely with a clear reason (validation errors), tells you to come back later when the kitchen is full (429 with Retry-After), gives you a ticket number so complaints can be traced (request ids), and does not charge twice if you repeat your order because you did not hear the first answer (idempotency). The kitchen behind it, a local model or Claude, can change without the menu changing.
The contract
An API is a promise. Clients (your web app, mobile app, other teams, scripts) are written against it, so changing it breaks them. Decide these things on purpose:
- Endpoints: keep them few. A chat API needs
POST /v1/chat(send messages, get an answer) andGET /healthz(is it alive?). Put the version in the path (/v1/) so you can add/v2/later without breaking existing clients. - Request shape: a list of messages with roles, an optional system prompt, a
max_tokens, and whether to stream. Mirror the shape providers use (role and content), so switching provider later changes only your server, not your clients. - Limits: maximum messages, characters per message, system prompt length and output tokens. Every unlimited field is a way to make you pay for someone else's tokens.
- Unknown fields: reject them (or at least never forward them). Forwarding arbitrary fields to a provider lets clients use features you did not plan for, including ones that cost money, which is why the module 7 proxy builds a fresh body with only the fields it allows (lesson 7.10).
- Response shape: for a non-streamed request, JSON with the answer, a request id and the model; for a streamed one, a defined sequence of events.
FastAPI turns such a contract into code: you describe the request as typed classes, it validates incoming JSON against them, and it publishes an OpenAPI description and interactive documentation for free. The script below shows the same contract with only the standard library, so you can run it and see each rule fire.
# @run
# The contract of a small chat API, written with the standard library only so it runs anywhere:
# - validate a request body and return clear errors (what FastAPI + pydantic do for you in server.py)
# - errors as RFC 9457 "problem details" JSON, always with a request id
# - streamed answers as Server-Sent Events (SSE) frames
# - idempotency keys, so a client that retries after a timeout is not charged twice
import json
LIMITS = {"max_messages": 50, "max_chars": 20_000, "max_system": 4_000, "max_tokens_cap": 1024}
ROLES = {"user", "assistant"}
def validate_chat(body):
"""Return (clean_request, None) or (None, list_of_errors). Unknown fields are rejected, not ignored."""
errors = []
if not isinstance(body, dict):
return None, ["body: must be a JSON object"]
allowed = {"messages", "system", "max_tokens", "stream"}
for key in sorted(set(body) - allowed):
errors.append(f"{key}: unknown field")
msgs = body.get("messages")
if not isinstance(msgs, list) or not msgs:
errors.append("messages: must be a non-empty list")
msgs = []
elif len(msgs) > LIMITS["max_messages"]:
errors.append(f"messages: at most {LIMITS['max_messages']} items")
for i, m in enumerate(msgs):
if not isinstance(m, dict) or m.get("role") not in ROLES:
errors.append(f"messages[{i}].role: must be 'user' or 'assistant'")
continue
text = m.get("content")
if not isinstance(text, str) or not text.strip():
errors.append(f"messages[{i}].content: must be a non-empty string")
elif len(text) > LIMITS["max_chars"]:
errors.append(f"messages[{i}].content: at most {LIMITS['max_chars']:,} characters")
if msgs and isinstance(msgs[-1], dict) and msgs[-1].get("role") != "user":
errors.append("messages: the last message must come from the user")
system = body.get("system", "You are a helpful assistant.")
if not isinstance(system, str) or len(system) > LIMITS["max_system"]:
errors.append(f"system: a string of at most {LIMITS['max_system']:,} characters")
max_tokens = body.get("max_tokens", 512)
if not isinstance(max_tokens, int) or isinstance(max_tokens, bool) or not 1 <= max_tokens <= LIMITS["max_tokens_cap"]:
errors.append(f"max_tokens: an integer from 1 to {LIMITS['max_tokens_cap']}")
if errors:
return None, errors
return {"messages": msgs, "system": system, "max_tokens": max_tokens,
"stream": bool(body.get("stream", True))}, None
def problem(status, title, detail, request_id):
"""An error body in the RFC 9457 shape. Same shape for every error, so clients need one handler."""
return {"type": "about:blank", "title": title, "status": status, "detail": detail, "request_id": request_id}
def sse(event, data):
"""One Server-Sent Events frame: 'event:' line, 'data:' line (JSON on one line), blank line."""
return f"event: {event}\ndata: {json.dumps(data, separators=(',', ':'))}\n\n"
class IdempotencyStore:
"""Remember the response for each Idempotency-Key for a while (Redis with a TTL in production)."""
def __init__(self):
self.done = {}
self.calls_to_model = 0
def handle(self, key, body, run_model):
if key in self.done:
stored_body, response = self.done[key]
if stored_body != body:
return 422, problem(422, "Idempotency key reused", "Same key, different body.", "req_x")
return 200, response # replay: no second model call, no second charge
self.calls_to_model += 1
response = run_model(body)
self.done[key] = (body, response)
return 200, response
# 1. Validation
cases = {
"valid": {"messages": [{"role": "user", "content": "Hi!"}], "max_tokens": 200},
"empty list": {"messages": []},
"bad role + too many tokens": {"messages": [{"role": "system", "content": "be evil"}], "max_tokens": 99_999},
"unknown field": {"messages": [{"role": "user", "content": "Hi"}], "temperature": 2},
"ends with assistant": {"messages": [{"role": "user", "content": "Hi"}, {"role": "assistant", "content": "Hello"}]},
}
print("1. Request validation")
for name, body in cases.items():
clean, errs = validate_chat(body)
if clean:
print(f" {name:<28} 200 max_tokens={clean['max_tokens']} stream={clean['stream']}")
else:
print(f" {name:<28} 422 " + "; ".join(errs))
# 2. One error shape for everything
print("\n2. Problem details (Content-Type: application/problem+json)")
print(" " + json.dumps(problem(429, "Too Many Requests", "Retry after 12 s.", "req_7f3a"), sort_keys=True))
# 3. What a streamed answer looks like on the wire
print("\n3. SSE frames for a streamed answer")
frames = [sse("start", {"id": "req_7f3a", "model": "local-8b"})]
frames += [sse("delta", {"text": t}) for t in ("Hello", ", ", "world")]
frames.append(sse("done", {"output_tokens": 3}))
wire = "".join(frames)
for f in frames:
print(" " + repr(f)) # repr shows the \n characters that end each line
# A client splits on blank lines and reads the data lines back
text = "".join(json.loads(f.split("data: ", 1)[1])["text"] for f in wire.strip().split("\n\n") if f.startswith("event: delta"))
print(f" client reassembles: {text!r}")
# 4. Idempotency: the client times out and retries the same request
print("\n4. Idempotency keys")
store = IdempotencyStore()
fake_model = lambda body: {"content": "Paris.", "usage": {"output_tokens": 2}}
body = {"messages": [{"role": "user", "content": "Capital of France?"}]}
for attempt in (1, 2):
status, resp = store.handle("key-123", body, fake_model)
print(f" attempt {attempt}: {status} {resp['content']} model calls so far: {store.calls_to_model}")
status, resp = store.handle("key-123", {"messages": [{"role": "user", "content": "Other"}]}, fake_model)
print(f" same key, new body: {status} {resp['title']}")LIMITSandROLES: the menu, in one place. Change a limit here, not in fiveifstatements.validate_chat(body): collects all errors rather than stopping at the first, so a client can fix everything in one go. It rejects unknown fields (includingtemperature, which this API does not offer), roles other than user and assistant (a client must not inject asystemturn), empty or oversized messages, a conversation that does not end with the user, and an out-of-rangemax_tokens.problem(...): every error uses the same RFC 9457 "problem details" shape with arequest_id, so clients need one error handler and support can find the log line.sse(event, data): one Server-Sent Events frame, the format you parsed in lesson 7.5.IdempotencyStore: remembers the answer for eachIdempotency-Key, so a retried request returns the stored answer without a second model call, and refuses the same key with a different body.
1. Request validation
valid 200 max_tokens=200 stream=True
empty list 422 messages: must be a non-empty list
bad role + too many tokens 422 messages[0].role: must be 'user' or 'assistant'; messages: the last message must come from the user; max_tokens: an integer from 1 to 1024
unknown field 422 temperature: unknown field
ends with assistant 422 messages: the last message must come from the user
2. Problem details (Content-Type: application/problem+json)
{"detail": "Retry after 12 s.", "request_id": "req_7f3a", "status": 429, "title": "Too Many Requests", "type": "about:blank"}
3. SSE frames for a streamed answer
'event: start\ndata: {"id":"req_7f3a","model":"local-8b"}\n\n'
'event: delta\ndata: {"text":"Hello"}\n\n'
'event: delta\ndata: {"text":", "}\n\n'
'event: delta\ndata: {"text":"world"}\n\n'
'event: done\ndata: {"output_tokens":3}\n\n'
client reassembles: 'Hello, world'
4. Idempotency keys
attempt 1: 200 Paris. model calls so far: 1
attempt 2: 200 Paris. model calls so far: 1
same key, new body: 422 Idempotency key reusedErrors clients can act on
A client can only react sensibly if the status code tells it whose problem it is and whether trying again could help, the same distinction you used for retries in lesson 7.8.
| Status | Meaning | Client should |
|---|---|---|
| 400 / 422 | the request is malformed or breaks a rule | fix the request; never retry unchanged |
| 401 / 403 | no valid key / key not allowed to do this | fix credentials; do not retry |
| 413 | body too large | send less (trim history, smaller file) |
| 429 | rate limit or budget exceeded | wait for Retry-After seconds, then retry |
| 500 | a bug in your server | retry a little later; you fix the bug |
| 502 / 503 / 504 | the model provider failed, is overloaded or timed out | retry with backoff and jitter |
Two habits make errors debuggable. Give every request an id (accept a sane one from the caller or generate one), return it in a header and in every error body, and put it on every log line (lesson 11.8). And never return internal details (stack traces, provider error bodies, keys, file paths) to the client: log them, and return a short, safe message.
Streaming, timeouts and cancellation
Streaming makes a slow model feel fast: the first words appear after the time to first token instead of after the whole answer (lesson 11.1). With SSE the response starts with status 200 and then sends events. That has one awkward consequence: once the stream has started, you can no longer change the status code. An error halfway through must be sent as an event (event: error), and the client must handle it, as the module 7 app does.
Every hop needs a timeout: client to your API, your API to the model. Without one, a stuck upstream ties up a worker forever. Use separate limits for connecting (a few seconds) and for waiting between chunks (tens of seconds for a model), rather than one total limit that a long, healthy answer could exceed. And handle cancellation: when the user presses Stop or closes the tab, close the upstream request too, or you keep paying for tokens nobody will read. The module 7 proxy does this with an AbortController.
- The client sends its key in the Authorization header. No key, or an unknown one: 401.
- The key's token bucket is checked (lesson 11.9). Empty: 429 with Retry-After.
- The body is validated against the contract. Broken rules: 422 with every problem listed.
- Only now is the model called, with a timeout. Tokens are forwarded to the client as SSE events as they arrive.
- Every outcome, success or error, is logged once with the request id, tokens and latency.
A complete server with FastAPI
Here is the same design as a real service. It authenticates clients with their own keys, applies a per-key token bucket (from lesson 11.9's rate_limiter.py), validates with pydantic, streams SSE, and talks either to Ollama or to Claude depending on one environment variable.
# A small production-style chat API in front of a model provider.
# needs: pip install -r requirements.txt (FastAPI, uvicorn, httpx, anthropic). Not executed by the course tests.
# Run: CHAT_API_KEYS=dev-key-123 uvicorn server:app --host 127.0.0.1 --port 8000
# Provider: PROVIDER=ollama (default, talks to OLLAMA_URL) or PROVIDER=anthropic (uses ANTHROPIC_API_KEY).
# Secrets (CHAT_API_KEYS, ANTHROPIC_API_KEY) come from the environment only: never from code, never from the client.
import json
import logging
import os
import re
import time
import uuid
from typing import List, Literal
import httpx
from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, Field
from rate_limiter import PerKeyLimiter, TokenBucket
PROVIDER = os.getenv("PROVIDER", "ollama")
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://localhost:11434")
MODEL = os.getenv("MODEL", "llama3.2")
API_KEYS = {k for k in os.getenv("CHAT_API_KEYS", "").split(",") if k} # keys for YOUR clients
MAX_OUTPUT_TOKENS = int(os.getenv("MAX_OUTPUT_TOKENS", "1024"))
TIMEOUT = httpx.Timeout(connect=5.0, read=60.0, write=10.0, pool=5.0)
logging.basicConfig(level=logging.INFO, format="%(message)s")
log = logging.getLogger("chat-api")
# In-memory limiter: correct for ONE process. With several workers or replicas, keep the buckets in Redis.
limiter = PerKeyLimiter(lambda: TokenBucket(capacity=10, refill_per_sec=0.5, clock=time.monotonic))
app = FastAPI(title="Chat API", version="1.0.0")
class Message(BaseModel):
role: Literal["user", "assistant"]
content: str = Field(min_length=1, max_length=20_000)
class ChatRequest(BaseModel):
messages: List[Message] = Field(min_length=1, max_length=50)
system: str = Field(default="You are a helpful assistant.", max_length=4_000)
max_tokens: int = Field(default=512, ge=1, le=MAX_OUTPUT_TOKENS)
temperature: float = Field(default=0.7, ge=0.0, le=1.0) # used for local models only (see below)
stream: bool = True
def problem(status, title, detail, request_id, headers=None):
"""Errors as RFC 9457 problem+json, always with the request id."""
body = {"type": "about:blank", "title": title, "status": status, "detail": detail, "request_id": request_id}
return JSONResponse(body, status_code=status, media_type="application/problem+json", headers=headers)
def log_event(event, **fields):
log.info(json.dumps({"event": event, "ts": round(time.time(), 3), **fields}, sort_keys=True))
@app.get("/healthz")
async def healthz():
return {"status": "ok", "provider": PROVIDER, "model": MODEL}
@app.post("/v1/chat")
async def chat(req: ChatRequest, request: Request, authorization: str = Header(default="")):
rid = request.headers.get("x-request-id", "") # accept a caller's id only if it looks sane
request_id = rid if re.fullmatch(r"[A-Za-z0-9_-]{1,64}", rid) else "req_" + uuid.uuid4().hex[:12]
key = authorization.removeprefix("Bearer ").strip()
if not key or key not in API_KEYS:
return problem(401, "Unauthorized", "Send 'Authorization: Bearer <your key>'.", request_id)
allowed, retry_after = limiter.allow(key)
if not allowed:
log_event("chat.rate_limited", request_id=request_id, retry_after_s=round(retry_after, 1))
return problem(429, "Too Many Requests", "Slow down.", request_id,
headers={"Retry-After": str(max(1, int(retry_after + 0.999)))})
started = time.monotonic()
messages = [m.model_dump() for m in req.messages]
gen = stream_ollama(req, messages) if PROVIDER == "ollama" else stream_anthropic(req, messages)
if not req.stream: # collect the whole answer, return JSON
try:
text = "".join([piece async for piece in gen])
except httpx.TimeoutException:
return problem(504, "Gateway Timeout", "The model did not answer in time.", request_id)
except httpx.HTTPError as exc:
return problem(502, "Bad Gateway", f"Model provider error: {type(exc).__name__}", request_id)
log_event("chat.completed", request_id=request_id, model=MODEL, stream=False,
output_chars=len(text), latency_ms=int((time.monotonic() - started) * 1000))
return {"id": request_id, "model": MODEL, "content": text}
async def sse():
first = None
chars = 0
yield f"event: start\ndata: {json.dumps({'id': request_id, 'model': MODEL})}\n\n"
try:
async for piece in gen:
if first is None:
first = time.monotonic()
chars += len(piece)
yield f"event: delta\ndata: {json.dumps({'text': piece})}\n\n"
yield "event: done\ndata: {}\n\n"
status = 200
except httpx.TimeoutException:
yield f"event: error\ndata: {json.dumps({'title': 'Gateway Timeout', 'status': 504})}\n\n"
status = 504
except httpx.HTTPError as exc:
yield f"event: error\ndata: {json.dumps({'title': 'Bad Gateway', 'detail': type(exc).__name__})}\n\n"
status = 502
log_event("chat.completed", request_id=request_id, model=MODEL, stream=True, status=status,
output_chars=chars, latency_ms=int((time.monotonic() - started) * 1000),
ttft_ms=int((first - started) * 1000) if first else None)
return StreamingResponse(sse(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Request-Id": request_id})
async def stream_ollama(req, messages):
"""Ollama's /api/chat streams one JSON object per line (NDJSON)."""
payload = {"model": MODEL, "stream": True,
"messages": [{"role": "system", "content": req.system}] + messages,
"options": {"temperature": req.temperature, "num_predict": req.max_tokens}}
async with httpx.AsyncClient(timeout=TIMEOUT) as client:
async with client.stream("POST", f"{OLLAMA_URL}/api/chat", json=payload) as resp:
resp.raise_for_status()
async for line in resp.aiter_lines():
if not line:
continue
chunk = json.loads(line)
if chunk.get("message", {}).get("content"):
yield chunk["message"]["content"]
if chunk.get("done"):
break
async def stream_anthropic(req, messages):
"""The Claude API through the official SDK; reads ANTHROPIC_API_KEY from the environment."""
import anthropic
client = anthropic.AsyncAnthropic(timeout=60.0, max_retries=2) # retries 429 / 529 with backoff
# No temperature here: on API version 2026-10-21 the Messages API rejects sampling parameters with a 400.
async with client.messages.stream(model=os.getenv("CLAUDE_MODEL", "claude-haiku-5-5"),
max_tokens=req.max_tokens, system=req.system,
messages=messages) as stream:
async for text in stream.text_stream:
yield text
@app.exception_handler(RequestValidationError)
async def validation_error(request: Request, exc: RequestValidationError):
first = exc.errors()[0] if exc.errors() else {}
where = ".".join(str(p) for p in first.get("loc", []))
return problem(422, "Invalid request", f"{where}: {first.get('msg', 'invalid value')}",
request.headers.get("x-request-id", "-"))
@app.exception_handler(HTTPException)
async def http_error(request: Request, exc: HTTPException):
return problem(exc.status_code, "Error", str(exc.detail), request.headers.get("x-request-id", "-"))Our tests check that this file compiles but did not run it, since that needs FastAPI and a model provider. Run it yourself with the command in its first lines.
- Configuration comes from environment variables: the provider, model, the set of client keys and the output cap. No secret appears in the code.
TIMEOUT = httpx.Timeout(connect=5.0, read=60.0, ...): separate limits for connecting and for waiting for the next chunk.MessageandChatRequest: the contract as pydantic classes.Literal["user", "assistant"]and theFieldlimits do whatvalidate_chatdid by hand; FastAPI answers 422 automatically, reshaped into problem details byvalidation_error.chat(...): request id, then the key check (401), then the rate limit (429 withRetry-After), then the model call. Model errors become 502, timeouts 504.sse(): forwards text pieces asdeltaevents and records the time to first token. An upstream failure mid-stream becomes anerrorevent, because the 200 status has already been sent.stream_ollama: reads Ollama's NDJSON stream withhttpx;temperatureandnum_predictgo inoptions.stream_anthropic: the official SDK's streaming helper with the key fromANTHROPIC_API_KEY. It sends notemperature, because the API version this course uses rejects sampling parameters, and it relies on the SDK's built-in retries for 429 and overload errors.
A call looks like this (the key is one you put in CHAT_API_KEYS, not a provider key):
curl -N http://127.0.0.1:8000/v1/chat \
-H "Authorization: Bearer dev-key-123" -H "Content-Type: application/json" \
-d '{"messages":[{"role":"user","content":"Hello!"}],"max_tokens":100}'A simulated API in your browser with the same rules as api_contract.py and a token bucket of 5 requests refilling 1 per 2 seconds. Edit the body, change the key, or press Send quickly to hit the rate limit. Nothing is sent over the network.
Idempotency, backpressure, provider abstraction and API evolution
Idempotency. Chat requests are not naturally idempotent: sending the same message twice produces two (different) answers and two bills. When a client times out it cannot know whether the server finished, so it retries. An Idempotency-Key header (a random id the client generates per logical request) lets the server store the result for a while, typically in Redis with an expiry, and replay it. This pattern is common in payment APIs Industry practice.
Backpressure. A model server can only handle so many concurrent generations. Rather than accepting everything and letting latency explode, cap concurrent upstream calls (a semaphore), queue briefly, and return 503 with Retry-After when the queue is full. A fast, honest "try again in 10 seconds" is better than a 60-second timeout.
Provider abstraction. server.py hides the provider behind two small async generators with the same signature. That is the seed of the configurable providers you will build in the capstone (module 12): one interface ("stream text for these messages"), several adapters (Claude, Ollama, any OpenAI-compatible server), and a fallback when one fails. Keep provider-specific features (tool formats, caching, sampling knobs) inside the adapters.
Evolving the API. Adding optional fields and new event types is safe if clients ignore what they do not know; removing or renaming fields, changing types or making optional fields required is a breaking change that needs a new version. Publish the OpenAPI document, keep a changelog, and give old versions a deprecation period.
Common mistakes and debugging tips
Passing the client's body straight to the provider
A thin proxy forwards whatever JSON arrives. Clients start sending huge max_tokens, other models, tools or a system prompt that overrides yours.
Fix: build a new upstream request from validated fields only, with server-side caps and an allow-list of models.
200 OK with an error inside
The API returns status 200 and {"error": "rate limited"}. Clients, retry libraries and monitoring all treat it as success.
Fix: use real status codes before the stream starts; only mid-stream failures go into an error event.
No timeout on the upstream call
The model server hangs; every request waits forever, workers run out, and the whole API stops answering, including health checks.
Fix: connect and read timeouts on every outbound call, mapped to 504, plus a cap on concurrent upstream calls.
Leaking internals in error messages
An unhandled exception returns a stack trace containing the provider URL, a file path and part of a key.
Fix: catch exceptions at the edge, log the details with the request id, and return a generic problem body.
Key takeaways
- Your own API is where you control who calls, how much, and with what: version it, limit every field, reject unknown ones.
- Use real status codes and one error shape (problem details with a request id); 429 and 503 carry Retry-After.
- Stream with SSE, send mid-stream failures as events, set timeouts on every hop and cancel upstream calls when clients leave.
- Hide providers behind one small interface so Claude, a local model or a fallback can be swapped without changing clients.
Exercise: extend the contract
1) Add an optional metadata field to validate_chat: an object with at most 5 string keys and string values of at most 100 characters each, for clients to tag requests (for example {"feature": "summarise"}). 2) Add a test case that sends 6 metadata entries and check that it is rejected with a clear message. 3) Explain why this field should never be forwarded to the model provider.
Hint
Add "metadata" to allowed, then check isinstance(md, dict), len(md) <= 5 and every key and value with isinstance(..., str) and a length check. Include it in the returned clean request.
Show a solution
md = body.get("metadata", {})
if not isinstance(md, dict) or len(md) > 5:
errors.append("metadata: an object with at most 5 entries")
elif any(not isinstance(k, str) or not isinstance(v, str) or len(v) > 100 for k, v in md.items()):
errors.append("metadata: string keys and string values of at most 100 characters")Metadata is for you: logs, cost reports per feature (lesson 11.9), debugging. Forwarding it would waste tokens, might leak internal labels or user data to a third party, and could even act as a prompt-injection channel if it reached the model's context.
Check your understanding
A streamed answer fails halfway because the model server crashes. How should your API report it?
- Change the HTTP status to 502
- Send an error event in the stream, since the 200 status was already sent
- Silently end the stream
Which status code tells a well-behaved client to wait and try again?
- 400
- 401
- 429 with a Retry-After header
Why does the server reject a system role inside messages from the client?
- So clients cannot override the operator's instructions by injecting their own system turn
- Because system messages cost more tokens
- Because JSON cannot represent them
Lesson 11.7Module 11: Deployment and production
Docker deployment
Learning objectives
- Explain images, containers, layers and volumes, and why containers suit AI services.
- Write a sound Dockerfile for the chat API: pinned base image, cached dependency layer, non-root user, no baked-in secrets, a health check.
- Run the API and a local model server together with Docker Compose, with model files on a volume and GPU access when available.
- Spot and fix the most common Dockerfile mistakes before they reach production.
The server from lesson 11.6 runs on your machine because your machine has the right Python, the right packages and the right environment variables. The next machine will not. Docker packages an application with everything it needs into an image that runs the same way on a laptop, a test server or a cloud service. This lesson containerises the chat API and runs it next to Ollama.
Analogy: a shipping container
Before standard shipping containers, every cargo was loaded differently, and every port needed to know how to handle sacks, barrels and crates. A container has one standard shape: the crane does not care whether it holds bananas or laptops. A Docker image is the packed container (your code plus its exact runtime); a running container is that box on a ship; the Dockerfile is the packing list. The ports (laptops, servers, cloud platforms) all know how to lift the standard box.
Images, containers, layers and volumes
- An image is a read-only file system plus settings (which command to run, which user, which port). It is built from a Dockerfile, one instruction per step.
- Each instruction creates a layer. Layers are cached: if an instruction and everything before it are unchanged, Docker reuses the layer instead of rebuilding it. Ordering instructions from "rarely changes" to "often changes" makes rebuilds take seconds instead of minutes.
- A container is a running instance of an image, isolated from the host and from other containers. Anything it writes is lost when it is removed, unless written to a volume, storage that lives outside the container.
- A registry stores images (Docker Hub, or your cloud provider's registry) so servers can pull them by name and tag.
For AI services two facts matter. Model weights are huge (gigabytes), so they belong on a volume or are downloaded at start-up, not copied into the image: an image with a 5 GB model inside is slow to build, push and pull. And the inference server and your API are separate processes with different needs (one wants a GPU and lots of memory, the other wants many small CPU workers), so they run as separate containers.
A Dockerfile for the chat API
# syntax=docker/dockerfile:1
# A small, pinned base image. For fully repeatable builds pin the digest too: python:3.12.8-slim-bookworm@sha256:...
FROM python:3.12.8-slim-bookworm
# No .pyc files; logs go straight to stdout, where Docker collects them
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PIP_DISABLE_PIP_VERSION_CHECK=1
WORKDIR /app
# 1. Dependencies first: this layer is reused from the cache until requirements.txt changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# 2. Then the code, which changes often. Owned by root, so the app user cannot modify it.
COPY server.py rate_limiter.py ./
# 3. Run as an unprivileged user, never as root
RUN useradd --create-home --uid 10001 app
USER app
# No secrets here: CHAT_API_KEYS and ANTHROPIC_API_KEY are passed in at run time (docker run -e / compose env_file)
EXPOSE 8000
# Docker marks the container unhealthy if /healthz stops answering (python is in the image; curl is not)
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2)"
# One worker: the in-memory rate limiter is per process. Scale with more containers plus a shared store (Redis).
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]FROM python:3.12.8-slim-bookworm: an exact, small base image. A floating tag such aspython:latestchanges under you; the "slim" variant leaves out compilers and tools you do not need, which also means fewer security vulnerabilities. Pinning the digest (@sha256:…) makes the build fully repeatable.ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1: no.pycfiles, and output is not buffered, so log lines appear immediately indocker logs.COPY requirements.txt .thenRUN pip install …: dependencies in their own layer, before the code. Editingserver.pydoes not reinstall packages.COPY server.py rate_limiter.py ./: only the files the service needs, copied as root so the running user cannot modify its own code.RUN useradd … appandUSER app: the process runs as an unprivileged user. If an attacker finds a hole in your code, they do not get root inside the container.- No
ENV ANTHROPIC_API_KEY=…line: secrets are given at run time. Anything written in a Dockerfile, including build arguments, can be read by anyone who has the image. HEALTHCHECK … /healthz: Docker calls the health endpoint every 30 seconds and marks the container unhealthy if it stops answering. It uses Python because the slim image has no curl.CMD [… "--workers", "1"]: the exec form (a JSON list) so signals such as "stop" reach uvicorn directly. One worker because the in-memory rate limiter lives in one process; scale with more containers and a shared store.
Two small files complete the image. requirements.txt pins versions so every build installs the same code; .dockerignore keeps the build context small and, crucially, keeps .env files with secrets out of the image:
# Pinned so every build gets the same versions (upgrade on purpose, then re-test).
# These are the versions the course code was written against; run `pip freeze` in your tested venv and pin those.
fastapi==0.115.6
uvicorn[standard]==0.32.1
httpx==0.27.2
pydantic==2.10.3
anthropic>=2,<3 # the 2.x SDK sends API version 2026-10-21; replace with the exact version you tested# Keep the build context small and secret-free
__pycache__/
*.pyc
*.out.txt
.env
.env.*
.git
*.gguf
models/Build and run it. Docker and these commands were not run by our automated tests; they are the standard commands, shown for you to try.
docker build -t chat-api:1.0 . # build the image (fast after the first time)
echo "CHAT_API_KEYS=dev-key-123" > .env # secrets live in a file that is never committed or copied
docker run --rm -p 127.0.0.1:8000:8000 --env-file .env \
-e PROVIDER=ollama -e OLLAMA_URL=http://host.docker.internal:11434 chat-api:1.0
docker ps # STATUS shows (healthy) once /healthz answershost.docker.internal lets a container reach a server on your own computer (built into Docker Desktop; on Linux add --add-host=host.docker.internal:host-gateway). The cleaner way is to run Ollama in a container too.
The API and the model together: Docker Compose
Docker Compose describes several containers, their networks and volumes in one YAML file and starts them with one command.
# docker compose up -d --build
# API on http://127.0.0.1:8000 (this machine only; put a TLS reverse proxy in front for the internet).
# Ollama is reachable only inside the compose network. Pull a model once:
# docker compose exec ollama ollama pull llama3.2
services:
api:
build: .
ports:
- "127.0.0.1:8000:8000" # not 0.0.0.0: nothing outside this machine can reach it directly
env_file: .env # CHAT_API_KEYS=... (and ANTHROPIC_API_KEY=... if PROVIDER=anthropic); never commit it
environment:
PROVIDER: ollama
OLLAMA_URL: http://ollama:11434 # service name = hostname on the compose network
MODEL: llama3.2
read_only: true # the app writes nothing to disk
security_opt:
- no-new-privileges:true
depends_on:
ollama:
condition: service_healthy
restart: unless-stopped
ollama:
image: ollama/ollama:0.12.3 # pin a tag you have tested (see the tags on Docker Hub), never :latest
volumes:
- ollama-models:/root/.ollama # downloaded models survive restarts and rebuilds
healthcheck:
test: ["CMD", "ollama", "list"]
interval: 30s
timeout: 5s
retries: 5
start_period: 20s
restart: unless-stopped
# NVIDIA GPU: needs the NVIDIA Container Toolkit on the host. Uncomment to use it.
# deploy:
# resources:
# reservations:
# devices:
# - driver: nvidia
# count: all
# capabilities: [gpu]
volumes:
ollama-models:api.build: .: build the image from the Dockerfile in this folder.ports: "127.0.0.1:8000:8000": publish the API on this machine only. A bare"8000:8000"would listen on every network interface. In production a reverse proxy with TLS sits in front.env_file: .env: client keys and, if used, the Claude key come from a file outside version control.OLLAMA_URL: http://ollama:11434: on the Compose network each service is reachable by its name. Ollama has noports:entry, so nothing outside the network can reach its unauthenticated API (lesson 11.4).read_only: trueandno-new-privileges: the API container cannot write to its own file system or gain privileges, which limits what an attacker can do.depends_on … condition: service_healthy: start the API only after Ollama's health check passes.image: ollama/ollama:0.12.3: a pinned version you have tested, notlatest. Check the published tags and update deliberately.volumes: ollama-models:/root/.ollama: downloaded models live on a named volume and survive container rebuilds.- The commented
deploy.resourcesblock gives the container NVIDIA GPUs; it needs the NVIDIA Container Toolkit on the host.
docker compose up -d --build # build and start both services
docker compose exec ollama ollama pull llama3.2 # download a model into the volume (once)
docker compose logs -f api # follow the API's JSON logs
docker compose down # stop; the model volume is keptPaste or edit a Dockerfile and check it against the rules in this lesson. A small set of text rules runs in your browser, nothing like a full linter such as hadolint, but enough to catch the classic mistakes.
From your laptop to a server
Once the image works locally, deployment is mostly about where it runs. You push the image to a registry with a version tag (chat-api:1.0.3, never only latest), and a platform pulls and runs it: a single virtual machine with Compose, a managed container service from a cloud provider, or Kubernetes for larger fleets. The same rules apply everywhere: secrets from the platform's secret store injected as environment variables, logs to standard output for the platform to collect (lesson 11.8), health checks wired to the platform's restarts and load balancer, and more replicas instead of bigger containers when traffic grows, with any shared state (rate limits, budgets, idempotency keys) moved to a shared store such as Redis. GPU workloads need hosts or node pools with GPUs and the matching drivers, and are much more expensive per hour, so many teams run their API on cheap CPU containers and either call a hosted model or keep a separate, carefully sized GPU service.
Multi-stage builds, image scanning, and model weights in production
Multi-stage builds use one stage with compilers to build wheels or assets, then copy only the results into a clean, small runtime stage. The final image contains no build tools, which shrinks it and removes attack surface. For pure-Python services like ours a single slim stage is usually enough.
Scanning and provenance. Base images and packages get security fixes all the time. Image scanners compare an image's packages against vulnerability databases; run one in CI, rebuild regularly to pick up patched base images, and pin dependencies with hashes (pip install --require-hashes) when supply-chain risk matters. Signing images and generating a software bill of materials (SBOM) are increasingly common in regulated settings Industry practice.
Model weights. Three patterns exist: download at start-up into a volume (simple, but slow cold starts and a dependency on the model host); bake weights into a separate, versioned "model image" or artefact (reproducible, large); or mount them from shared network storage (fast to roll out across many servers). Whichever you choose, record exactly which model file (name, quantisation, checksum) each deployment uses, so a quality regression can be traced to a model change rather than a code change.
Common mistakes and debugging tips
Baking secrets into the image
ENV ANTHROPIC_API_KEY=sk-ant-… or COPY .env . puts the key into a layer. Anyone who pulls the image, or reads its history, has your key, even if a later layer deletes the file.
Fix: pass secrets at run time (--env-file, env_file:, the platform's secret store), list .env in .dockerignore, and rotate any key that was ever baked in.
Running as root
Without a USER line the process runs as root inside the container, so a vulnerability in your code gives an attacker full control of the container and a better position to attack the host.
Fix: create an unprivileged user and switch to it; add read_only and no-new-privileges where possible.
Every build reinstalls all packages
COPY . . comes before pip install, so any code change invalidates the dependency layer.
Fix: copy requirements.txt and install first, then copy the code.
"Connection refused" between containers
The API tries localhost:11434, but inside a container localhost is the container itself.
Fix: use the Compose service name (http://ollama:11434), or host.docker.internal for a server on the host. Also make the server inside a container listen on 0.0.0.0, not 127.0.0.1, or nothing outside it can connect.
Key takeaways
- An image packages code with its exact runtime; layers are cached, so put rarely changing steps first.
- A sound AI-service Dockerfile: pinned slim base, dependencies before code, non-root user, health check, exec-form command, no secrets.
- Compose runs the API and the model server together; publish only the API, keep models on a volume, give GPUs explicitly.
- Secrets and model files are injected at run time, never baked in.
Exercise: fix a risky Dockerfile
Load the risky example in the checker above. List every problem, then rewrite it until the checker passes. For each fix, write one sentence on what could have gone wrong in production without it.
Hint
Look at the base image tag, the order of COPY and RUN, how the key is provided, which user runs the process, how the container's health is checked, and the form of the CMD line.
Show a solution
The risky file uses python:latest (unpinned and large: builds change silently), copies everything before installing (slow builds, and it copies .env into the image), sets the API key with ENV (anyone with the image can read it), runs as root (a breach gives full control), has no HEALTHCHECK (a hung server keeps receiving traffic) and uses the shell form of CMD (stop signals do not reach the server, so shutdowns are killed abruptly after a timeout). The lesson's Dockerfile, loaded with the second button, fixes all six.
Check your understanding
Why is COPY requirements.txt followed by RUN pip install placed before copying the application code?
- Python requires packages to be installed before files exist
- It makes the image more secure
- The dependency layer stays cached when only the code changes, so rebuilds are fast
A colleague deletes the API key in a later Dockerfile step (RUN rm .env). Is the key gone from the image?
- No: earlier layers still contain the file and can be extracted
- Yes: the final file system no longer has it
- Only if the image is pushed to a private registry
In the Compose file, why does the Ollama service have no ports: entry?
- Ollama does not use network ports
- So its unauthenticated API is reachable only by other containers on the Compose network, not from outside
- Because Compose forbids two services with ports
Lesson 11.8Module 11: Deployment and production
Monitoring and logging
Learning objectives
- Distinguish logs, metrics and traces, and know which questions each answers.
- Write structured, privacy-safe log events for every LLM request, with secrets and personal data redacted.
- Measure latency with percentiles, define an SLO and an error budget, and alert on symptoms.
- Monitor what is special about LLMs: tokens, cost, time to first token, truncation, and answer quality over time.
A deployed service is a black box unless it tells you what it is doing. When a user writes "the assistant was really slow yesterday afternoon and gave me a wrong answer", you need to find that request, see how long each step took, which model and prompt version answered, how many tokens it used and whether anything failed. That is observability, and like tests, it has to be built in before you need it.
Analogy: a car's dashboard, its service log and a dashcam
A car's dashboard shows a few numbers continuously (speed, fuel, temperature) and lights up a warning when one goes wrong: those are metrics and alerts. The service log records each event in detail (date, what was done, which part was replaced): those are logs. A dashcam records one particular journey from start to finish, so you can see exactly what happened at the junction: that is a trace. You glance at the dashboard all the time, read the log when something is wrong, and watch the dashcam footage to understand one incident.
Logs, metrics and traces
| Signal | What it is | Answers | Example |
|---|---|---|---|
| Logs | one record per event, with details | what happened to this request? | {"event":"chat.completed","request_id":"req_0001","output_tokens":231,…} |
| Metrics | numbers aggregated over time | how is the service doing overall? | requests per second, error rate, p95 latency, tokens per minute, GPU memory |
| Traces | the timed steps of one request across components | where did the time go? | auth 2 ms → retrieval 180 ms → model 3.1 s (TTFT 420 ms) → tool call 600 ms |
They are linked by the request id from lesson 11.6: a metric shows a spike, the logs from that minute show which requests failed, and the trace of one of them shows which step was slow. Traces matter most for agents and RAG pipelines, where one user request becomes several model calls, searches and tool executions (lesson 9.7). OpenTelemetry is the common open standard for producing all three signals, and it has semantic conventions for generative AI calls that many tools understand Industry practice.
- Chat API
- Emits one structured event per request, plus metrics and spans. In a container it writes logs to standard output and lets the platform collect them.
- Logs
- Searchable records with the request id, model, tokens, latency and status. Raw prompts and answers are left out by default.
- Metrics
- Cheap aggregates: counts, rates and histograms. Good for dashboards and alerts over long periods.
- Traces
- Timed spans for each step of a request: retrieval, each model call, each tool. Essential for agents.
- Dashboards
- A small set of graphs people actually look at: traffic, errors, latency percentiles, tokens and cost.
- Alerts
- Wake a human only for user-visible problems: SLO burn, a spike in errors, a spending anomaly.
- Quality review
- LLM answers can be wrong with status 200. Sample conversations (with consent), user feedback and automatic evals catch that.
What to log for every LLM request
Log one structured event (a JSON object, not a sentence) when each request ends, with fields you can search and aggregate:
- Identity: request id, a pseudonymous user or API-key id, the feature or endpoint.
- What ran: provider, model id and version (and quantisation for local models), the prompt version (so a quality change can be tied to a prompt change).
- Size and cost: input tokens, output tokens, cached input tokens, computed cost. Providers report token usage in each response; use their numbers rather than your own estimates.
- Time: time to first token, total latency, time spent in each step for multi-step requests.
- Outcome: HTTP status, stop reason (end of turn, max tokens, tool use, refusal), error type, retries, and the provider's own request id for support cases.
Just as important is what you do not log. Prompts and answers often contain personal data, confidential documents and sometimes secrets users pasted by mistake. Log their length by default, not their content; if you must keep conversations for debugging or evaluation, do it in a separate, access-controlled store with user consent, a stated purpose and a short retention period. API keys and authorization headers must never appear at all.
# @run
# Structured (JSON) logs for an LLM API: one event per request, secrets and PII redacted,
# a request id on every line, and latency percentiles (p50 / p95 / p99) computed from samples.
import json
import re
import numpy as np
REDACTIONS = [
(re.compile(r"sk-[A-Za-z0-9_-]{16,}"), "[REDACTED_KEY]"), # API-key shaped strings
(re.compile(r"(?i)bearer\s+[A-Za-z0-9._-]+"), "Bearer [REDACTED]"),
(re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+"), "[EMAIL]"),
(re.compile(r"\+?\d[\d\s-]{8,}\d"), "[PHONE]"),
(re.compile(r"\b(?:\d[ -]?){13,16}\b"), "[CARD]"),
]
SECRET_FIELDS = {"api_key", "authorization", "password", "x-api-key"}
DROP_FIELDS = {"prompt", "completion"} # never log raw text by default
def redact(value):
if isinstance(value, str):
for pattern, replacement in REDACTIONS:
value = pattern.sub(replacement, value)
return value
if isinstance(value, dict):
out = {}
for k, v in value.items():
if k.lower() in SECRET_FIELDS:
out[k] = "[REDACTED]"
elif k in DROP_FIELDS:
out[k + "_chars"] = len(v) # keep the size, not the content
else:
out[k] = redact(v)
return out
if isinstance(value, list):
return [redact(v) for v in value]
return value
class JsonLogger:
def __init__(self, service, clock):
self.service = service
self.clock = clock
self.lines = []
def log(self, level, event, **fields):
record = {"ts": self.clock(), "level": level, "service": self.service, "event": event}
record.update(redact(fields))
line = json.dumps(record, sort_keys=True, separators=(",", ":"))
self.lines.append(line)
print(line)
def percentile(samples, p):
return float(np.percentile(np.asarray(samples), p))
# A fixed clock so the output is identical on every run (use datetime.now(timezone.utc) for real)
ticks = iter(f"2026-11-12T10:00:{s:02d}Z" for s in range(60))
log = JsonLogger("chat-api", clock=lambda: next(ticks))
print("--- three request events ---")
log.log("info", "chat.completed", request_id="req_0001", user="u_42", model="local-8b-q4",
prompt_version="support-v3", input_tokens=812, output_tokens=231, ttft_ms=420,
latency_ms=3110, cost_usd=0.0, status=200,
prompt="My email is jane.doe@example.com, can you reset my order?",
headers={"authorization": "Bearer abc.def.ghi", "user-agent": "app/1.4"})
log.log("warn", "chat.rate_limited", request_id="req_0002", user="u_7", status=429,
retry_after_s=12, note="client sent key sk-live_ABCDEFGHIJKLMNOPQRST in the body")
log.log("error", "provider.timeout", request_id="req_0003", user="u_42", model="local-8b-q4",
status=504, latency_ms=30000, error="upstream did not answer within 30 s (user bob@example.org)",
completion="Call me on +44 7700 900123 tomorrow")
print()
print("--- latency percentiles from 1,000 simulated requests ---")
rng = np.random.default_rng(0)
latency = rng.lognormal(mean=np.log(1800), sigma=0.45, size=1000) # most around 1.8 s
latency[rng.choice(1000, 15, replace=False)] *= 6 # a few very slow ones
ttft = rng.lognormal(mean=np.log(350), sigma=0.35, size=1000)
for name, data in (("end-to-end latency", latency), ("time to first token", ttft)):
p50, p95, p99 = (percentile(data, p) for p in (50, 95, 99))
print(f"{name:<20} p50 {p50:7.0f} ms p95 {p95:7.0f} ms p99 {p99:7.0f} ms "
f"mean {float(data.mean()):7.0f} ms")
print()
slo_ms = 5000
slow = int((latency > slo_ms).sum())
print(f"SLO 'p95 under {slo_ms} ms': {'met' if percentile(latency, 95) < slo_ms else 'BROKEN'}"
f" ({slow} of 1000 requests slower than {slo_ms} ms)")
errors = sum(1 for line in log.lines if json.loads(line)["level"] == "error")
print(f"error events in this log: {errors} of {len(log.lines)}")
leaked = [line for line in log.lines if "jane.doe" in line or "sk-live" in line or "abc.def" in line]
print(f"secrets or emails left in the log lines: {len(leaked)}")REDACTIONS: regular expressions for key-shaped strings, bearer tokens, emails, phone numbers and card numbers, each replaced by a label.SECRET_FIELDSandDROP_FIELDS: fields replaced wholesale (authorization), and fields whose content is dropped and replaced by its length (prompt,completion).redact(value): walks strings, dictionaries and lists recursively, so a secret nested in headers is caught too.JsonLogger.log(...): one JSON object per line with a timestamp, level, service and event name.sort_keyskeeps lines stable and easy to diff. The fixed clock is only for a reproducible demo.percentile(...): p50, p95 and p99 from 1,000 simulated latencies, including a few very slow requests.- The last lines check the service-level objective and verify that no secret or email survived in the log lines.
--- three request events ---
{"cost_usd":0.0,"event":"chat.completed","headers":{"authorization":"[REDACTED]","user-agent":"app/1.4"},"input_tokens":812,"latency_ms":3110,"level":"info","model":"local-8b-q4","output_tokens":231,"prompt_chars":57,"prompt_version":"support-v3","request_id":"req_0001","service":"chat-api","status":200,"ts":"2026-11-12T10:00:00Z","ttft_ms":420,"user":"u_42"}
{"event":"chat.rate_limited","level":"warn","note":"client sent key [REDACTED_KEY] in the body","request_id":"req_0002","retry_after_s":12,"service":"chat-api","status":429,"ts":"2026-11-12T10:00:01Z","user":"u_7"}
{"completion_chars":35,"error":"upstream did not answer within 30 s (user [EMAIL])","event":"provider.timeout","latency_ms":30000,"level":"error","model":"local-8b-q4","request_id":"req_0003","service":"chat-api","status":504,"ts":"2026-11-12T10:00:02Z","user":"u_42"}
--- latency percentiles from 1,000 simulated requests ---
end-to-end latency p50 1759 ms p95 3936 ms p99 7884 ms mean 2071 ms
time to first token p50 349 ms p95 625 ms p99 771 ms mean 372 ms
SLO 'p95 under 5000 ms': met (24 of 1000 requests slower than 5000 ms)
error events in this log: 1 of 3
secrets or emails left in the log lines: 0Look at the first event: the email address in the prompt and the bearer token in the headers are gone, but the event still says the prompt had 57 characters, which model and prompt version answered, and how long it took. The third shows an email inside an error message being caught too: errors are a classic leak, because they often echo user input.
Percentiles, SLOs and error budgets
Latency is never one number. In the output the mean latency is about 2.1 s, but 1% of requests take 7.9 s or more. If a user makes 20 requests in a session, there is roughly an 18% chance that at least one of them is in that slowest 1%. That is why services describe latency with percentiles: p50 (the median, the typical experience), p95 and p99 (the bad experiences that still happen every day).
A service-level objective (SLO) turns this into a target, for example "95% of chat requests get their first token within 1.5 s, measured over 28 days" or "99.5% of requests succeed". The gap to 100% is the error budget: with a 99.5% success objective and a million requests a month, 5,000 failures are within budget. Spending the budget slowly is fine; burning it fast (a third of the month's budget in an hour) is what should page someone. This keeps alerts tied to what users feel rather than to every CPU spike.
2,000 simulated request latencies (a fixed pseudo-random seed, so the picture is stable). Move the sliders and watch the mean barely move while p99 jumps.
What is different about monitoring LLMs
- Success is not correctness. A 200 response can contain a wrong answer, a refusal, invented citations or broken JSON. Track the proxies you can measure: stop reasons (a rising share of
max_tokensmeans truncated answers), refusal rate, structured-output validation failures, thumbs-up/down feedback, and conversations where users rephrase the same question. - Tokens drive cost and latency. Plot input and output tokens per request and per feature. A prompt change that adds 2,000 tokens of instructions shows up here before it shows up on the invoice.
- Models change. Pin model versions where possible and log them; when a provider or you switch models, compare quality metrics before and after. Run your evaluation set (lesson 10.8) on a schedule, not just once.
- For self-hosted models, add hardware metrics: GPU memory and utilisation, KV cache usage, queue length and the number of running sequences. Engines such as vLLM export these; queue length rising while GPU utilisation is flat usually means you are memory-bound on the KV cache.
- Agents need per-step traces: which tools were called with what arguments, how many iterations, which permission checks fired (lesson 9.8), and the total tokens of the whole run.
Histograms instead of averages, sampling, and privacy-preserving evaluation
You cannot average percentiles: the p95 of two servers is not the mean of their p95s. Metric systems therefore record latency in histogram buckets (for example counts of requests under 100 ms, 250 ms, 500 ms, 1 s, 2.5 s, …) which can be added across servers and time windows, and estimate percentiles from the combined buckets. Choose bucket edges around your SLO threshold so the estimate is accurate where it matters.
At high volume, logging every event in full gets expensive. Common practice is to keep every error and slow request, and a random sample of the rest, while still counting everything in metrics. Traces are usually sampled the same way, with "tail sampling" deciding after a request finishes whether it was interesting enough to keep Industry practice.
Evaluating answer quality in production without reading users' conversations is an active area. Options include asking for explicit consent to review, running automatic checks (validators, an LLM judge as in lesson 10.8) inside the trusted environment and storing only their scores, and replaying a fixed synthetic test set against production on a schedule. Whatever you choose, the privacy policy must describe it truthfully.
Common mistakes and debugging tips
Logging full prompts and responses by default
Logs fill with personal data, pasted passwords and confidential documents, are copied to third-party log services, and kept for a year.
Fix: log sizes and metadata, redact patterns, and store any conversation content separately with consent, access control and short retention.
Unstructured log messages
print(f"done for {user} in {t}s") cannot be searched by field or aggregated, and every developer phrases it differently.
Fix: one JSON event per request with agreed field names; build dashboards from fields, not from text matching.
Alerting on everything
Alerts fire for every CPU spike and single error; people start ignoring them and miss the real outage.
Fix: alert on symptoms users feel (SLO burn rate, error-rate spikes, spending anomalies) and send everything else to dashboards.
No request id end to end
A user reports a bad answer; the API log, the model server log and the provider dashboard cannot be connected.
Fix: generate the id at the edge, pass it to every downstream call (as a header and in spans), return it to the client and show it in error messages so users can quote it.
Key takeaways
- Logs explain one request, metrics show overall health, traces show where time went; the request id links them.
- Log one structured event per request with model, prompt version, tokens, TTFT, latency, status and cost; never keys, and not raw content by default.
- Use percentiles, SLOs and error budgets, and alert on user-visible symptoms.
- For LLMs, also watch stop reasons, refusals, format failures, feedback, token trends and model versions: a 200 is not a correct answer.
Exercise: a better log event and a cost alert
1) Extend log_events.py so the redaction also catches IPv4 addresses (for example 203.0.113.42) and add a test event that contains one. 2) Using the simulated latencies, compute what fraction of requests would break a stricter SLO of "p99 under 6 s". 3) Describe in two sentences an alert that would catch a prompt change that doubled the average input tokens.
Hint
A simple IPv4 pattern is \b(?:\d{1,3}\.){3}\d{1,3}\b; put it before the phone pattern so the digits are not taken as a phone number. For part 2 compare percentile(latency, 99) with 6,000 and count (latency > 6000).sum().
Show a solution
1) Add (re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"), "[IP]") as the first entry of REDACTIONS and log an event with client_ip="203.0.113.42"; the line shows [IP]. 2) p99 is about 7.9 s, so the SLO is broken; 16 of the 1,000 requests (1.6%) are slower than 6 s, mostly the planted very slow ones. 3) Track the average input tokens per request per feature over a rolling hour and alert when it exceeds, say, 1.5 times the previous week's value for that hour; include the prompt version in the alert so the cause is obvious.
Check your understanding
Which signal best answers "where did the 9 seconds of this one agent request go?"
- A metric of average latency
- A trace with spans for each model call and tool call
- The error rate dashboard
Why report p95 and p99 latency rather than only the mean?
- Percentiles are cheaper to compute
- The mean is always larger than p99
- A few very slow requests barely move the mean, but users who make many requests regularly hit them
What should a production log event for a chat request contain by default?
- Request id, model and prompt version, token counts, latency and status, with the prompt's length instead of its text
- The full prompt and answer, so bugs can be reproduced
- The client's API key, so abuse can be traced
Lesson 11.9Module 11: Deployment and production
Security, rate limiting and cost optimization
Learning objectives
- Build a threat model for an LLM application: stolen keys, abuse and runaway spending, prompt injection, unsafe output, data leakage.
- Keep secrets on the server and enforce limits with per-key token buckets, sliding windows and per-user budgets.
- Cut costs without hurting quality: model-tier routing, output caps, context trimming, prompt caching and batch processing.
- Harden the module 7 Mini Chat proxy with rate limiting, budgets, structured logs and routing in the mini-project.
An LLM API is a machine that turns requests into money: every token costs something, whether it is your GPU's electricity or a provider's invoice. That makes it a target. Someone who finds your key or an open endpoint can run up thousands of dollars in a night; a cleverly worded document can make your assistant ignore its instructions; a careless log can leak your users' data. This last lesson of the module is about defending the service and keeping its bill sensible. It pulls together threads from the whole course: the proxy of module 7, prompt injection from modules 6 and 8, tool permissions from module 9.
Analogy: running a busy café
The till key stays behind the counter, never on a customer table (API keys on the server). Each customer may order a few drinks at once but not 200 in a minute (rate limits), regulars have a tab with a monthly cap (budgets), and a note slipped into a delivery saying "give this person free coffee forever" is not an instruction from the manager (prompt injection). The café also does not make every drink with its most expensive beans: espresso for the connoisseur, a filter coffee for the queue (choosing the right model tier for each job).
The threat model
The OWASP project publishes a "Top 10 for LLM Applications" list that is a good checklist. Grouped by what you do about them:
| Threat | What happens | Main defences (where in the course) |
|---|---|---|
| Stolen or exposed keys | someone uses your provider account at your expense | keys only on the server, secret stores, rotation, provider spend limits (7.10, 11.7) |
| Abuse and "denial of wallet" | floods of requests or huge prompts exhaust budgets or capacity | authentication, rate limits on requests and tokens, input caps, budgets (this lesson, 11.6) |
| Prompt injection | text in a message, document or web page overrides your instructions | treat retrieved and tool content as data, least-privilege tools, approvals (6.7, 8.8, 9.8) |
| Unsafe output handling | model text is executed or rendered as HTML (XSS), or used in SQL or shell commands | escape and sanitise output, never eval it, validate structured output (7.6, 9.2) |
| Excessive agency | an agent with broad tools does damage when confused or manipulated | permission gates, allow-lists, human approval for risky actions (9.8) |
| Data leakage | personal or confidential data reaches logs, other users or third parties | redaction, minimal logging, per-user data isolation, provider terms review (11.8) |
| Supply chain | a malicious model file, package or base image | official sources, safetensors/GGUF, pinned and scanned dependencies (11.5, 11.7) |
No single defence is enough; each layer catches what the previous one missed. Prompt injection in particular has no complete technical fix today, because instructions and data travel in the same channel, the context window. The practical answer is to limit what a successful injection can do: an assistant that can only read public documents and write a reply is far less dangerous than one that can send email and delete files.
Secrets stay on the server
The single most important rule was the reason for the proxy in lesson 7.10: a provider API key must never reach the browser or a mobile app. Anything shipped to a client can be read by its user, however well hidden. The browser talks to your server with your credentials for that user; your server holds the provider key in an environment variable or secret store and makes the provider call. Beyond that:
- Use separate keys for development, staging and production, and for each service, so one leak does not expose everything and keys can be revoked independently.
- Load keys from the environment or a secret manager; never commit them. Add secret scanning to your repository, and rotate any key that has ever been pasted into a chat, a ticket or a log.
- Set spending limits and alerts in the provider's console as a last line of defence that works even when your own code is broken.
- Give your own clients their own keys (or user sessions), so you can rate-limit, bill and revoke them individually.
Rate limiting
A rate limiter answers one question for each request: is this caller allowed to spend more right now? Two algorithms cover most needs.
- A token bucket holds up to capacity tokens and refills at a steady rate. Each request takes one token (or more for expensive requests); if the bucket is empty, the answer is 429 with the time until enough tokens return. It allows short bursts (a user sending three quick messages) while capping the long-run rate.
- A sliding window keeps the timestamps and sizes of recent requests and refuses a new one if the total in the last N seconds would exceed the limit. It is exact, which suits limits on LLM tokens per minute.
Limit more than one thing: requests per minute per key, LLM tokens per minute per key (one request can carry 100,000 tokens), concurrent streams per user, and a global cap that protects your provider quota or GPU. The provider limits you as well: when it answers 429 or reports overload, back off with jitter (lesson 7.8) rather than retrying immediately.
# @run
# Two rate limiters for an LLM API, with an injected clock so tests are instant and repeatable.
# TokenBucket: allows short bursts, refills at a steady rate (good for "requests per minute").
# SlidingWindow: counts cost in the last N seconds exactly (good for "LLM tokens per minute").
import math
from collections import deque
class FakeClock:
"""A clock we move by hand. In production pass time.monotonic instead."""
def __init__(self, t=0.0):
self.t = t
def __call__(self):
return self.t
def advance(self, seconds):
self.t += seconds
class TokenBucket:
def __init__(self, capacity, refill_per_sec, clock):
self.capacity = capacity
self.rate = refill_per_sec
self.clock = clock
self.tokens = float(capacity) # start full: a new client may burst
self.last = clock()
def _refill(self):
now = self.clock()
self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
self.last = now
def allow(self, cost=1.0):
"""Return (allowed, retry_after_seconds)."""
self._refill()
if self.tokens >= cost:
self.tokens -= cost
return True, 0.0
return False, (cost - self.tokens) / self.rate
class SlidingWindow:
def __init__(self, limit, window_sec, clock):
self.limit = limit
self.window = window_sec
self.clock = clock
self.events = deque() # (timestamp, cost)
self.used = 0
def allow(self, cost=1):
now = self.clock()
while self.events and self.events[0][0] <= now - self.window:
self.used -= self.events.popleft()[1] # forget events older than the window
if self.used + cost > self.limit:
oldest = self.events[0][0] if self.events else now
return False, max(0.0, oldest + self.window - now)
self.events.append((now, cost))
self.used += cost
return True, 0.0
class PerKeyLimiter:
"""One limiter per API key, created on first use (a dict here; Redis in a multi-server setup)."""
def __init__(self, factory):
self.factory = factory
self.limiters = {}
def allow(self, key, cost=1):
if key not in self.limiters:
self.limiters[key] = self.factory()
return self.limiters[key].allow(cost)
def run_tests():
clock = FakeClock()
# 1. Token bucket: burst of 5, then 1 request per second
tb = TokenBucket(capacity=5, refill_per_sec=1.0, clock=clock)
results = [tb.allow()[0] for _ in range(7)]
assert results == [True] * 5 + [False] * 2, results
ok, retry = tb.allow()
assert not ok and math.isclose(retry, 1.0), retry
clock.advance(2.5) # 2.5 tokens come back
assert [tb.allow()[0] for _ in range(3)] == [True, True, False]
print("token bucket: burst of 5 allowed, 6th refused, refills at 1/s ok")
# 2. Sliding window over LLM tokens: 1,000 tokens per 60 s
clock = FakeClock()
sw = SlidingWindow(limit=1000, window_sec=60, clock=clock)
assert sw.allow(600)[0]
clock.advance(30)
assert sw.allow(300)[0]
ok, retry = sw.allow(200) # 1,100 > 1,000
assert not ok and math.isclose(retry, 30.0), retry # the 600 expires at t = 60
clock.advance(30)
assert sw.allow(200)[0] # now only 300 + 200 in the window
print("sliding window: 600 + 300 ok, +200 refused (retry in 30 s), ok after expiry ok")
# 3. Per-key isolation: one noisy client does not block another
clock = FakeClock()
per_key = PerKeyLimiter(lambda: TokenBucket(2, 0.5, clock))
assert [per_key.allow("key-a")[0] for _ in range(3)] == [True, True, False]
assert per_key.allow("key-b")[0]
print("per-key: key-a throttled, key-b unaffected ok")
# 4. Simulate a steady stream: 3 requests/s for 10 s against a 5-burst, 1/s bucket
clock = FakeClock()
tb = TokenBucket(5, 1.0, clock)
allowed = 0
for _ in range(30):
allowed += tb.allow()[0]
clock.advance(1 / 3)
print(f"simulation: 30 requests in 10 s -> {allowed} allowed, {30 - allowed} got HTTP 429")
assert allowed == 14 # 5 burst + 9 refilled (last request at t = 9.67 s)
if __name__ == "__main__":
run_tests()
print("all rate limiter tests passed")FakeClock: a clock moved by hand, so the tests run instantly and identically. In production you passtime.monotonic, which never jumps backwards when the system clock is adjusted.TokenBucket._refill(): addselapsed × ratetokens, never above capacity. Refilling lazily on each call means no background timer is needed.TokenBucket.allow(cost): takescosttokens if available; otherwise returns how many seconds until there will be enough, which becomes theRetry-Afterheader.SlidingWindow.allow(cost): drops events older than the window from the front of a deque, then checks whether this request still fits.PerKeyLimiter: one limiter per API key, created on first use, so a noisy client cannot use up everyone's capacity. With several servers, the state must live in a shared store such as Redis.run_tests(): assertions for burst, refill, window expiry and isolation, then a simulation of a client sending 3 requests per second into a bucket of 5 refilling at 1 per second.
token bucket: burst of 5 allowed, 6th refused, refills at 1/s ok
sliding window: 600 + 300 ok, +200 refused (retry in 30 s), ok after expiry ok
per-key: key-a throttled, key-b unaffected ok
simulation: 30 requests in 10 s -> 14 allowed, 16 got HTTP 429
all rate limiter tests passedSend requests and watch the bucket. Time only moves when you press "Wait 1 s", so you can see exactly how the refill works.
Cost optimisation
The cost of an LLM feature is roughly requests × (input tokens × input price + output tokens × output price), so every lever reduces one of those factors. In rough order of how much they usually save:
- Choose the right model tier for each job. Providers offer families of models at very different prices; Claude, for example, comes in larger and smaller tiers (Opus, Sonnet and Haiku models) Public. A task that has to change twenty files across a codebase benefits from the most capable model, because a mistake costs more than the tokens. Classifying a support ticket, writing a title or extracting a date is done well by a small, fast, much cheaper model. A local model can take jobs whose data must not leave your network. Routing each request to the cheapest tier that does it well is a real engineering skill: decide with your evaluation set, not by feel.
- Send fewer input tokens. Trim old turns, summarise long histories, retrieve the five most relevant chunks rather than whole documents (module 8), and remove instructions that do nothing.
- Reuse what repeats with prompt caching. If many requests start with the same long system prompt, tool definitions or document, providers can cache that prefix; cached input is billed at a fraction of the normal input price and starts faster (lesson 6.8). Keep the stable part first and identical byte for byte.
- Cap the output. Output tokens usually cost several times more than input tokens. Set
max_tokensto what the feature needs and ask for concise answers or structured output. - Batch what is not urgent. Nightly reports, bulk classification and evaluations can go through a provider's batch interface, which processes requests asynchronously at a discount (about half price for Claude's Message Batches API at the time of writing; check current docs).
- Do not call a model at all when you can avoid it: cache answers to identical requests, use plain code for things code does well (dates, arithmetic: lesson 9.5), and stop agents that loop without progress.
The script below puts numbers on these levers with a price table you configure. The prices in it are illustrative examples, not a current price list: copy real ones from your provider's pricing page before trusting the totals.
# @run
# Per-request token accounting and cost, with prices you configure.
# The prices below are EXAMPLE numbers in US dollars per million tokens, not real price lists:
# copy the current numbers from your provider's pricing page into PRICES before trusting the totals.
from collections import defaultdict
from dataclasses import dataclass
PRICES = { # $ per 1M tokens: input, output, cache write, cache read
"large": {"in": 5.00, "out": 25.00, "cache_write": 6.25, "cache_read": 0.50},
"medium": {"in": 3.00, "out": 15.00, "cache_write": 3.75, "cache_read": 0.30},
"small": {"in": 1.00, "out": 5.00, "cache_write": 1.25, "cache_read": 0.10},
"local": {"in": 0.00, "out": 0.00, "cache_write": 0.00, "cache_read": 0.00},
}
BATCH_DISCOUNT = 0.5 # e.g. a batch API that costs half for non-urgent work
@dataclass
class Usage:
input_tokens: int
output_tokens: int
cache_write_tokens: int = 0
cache_read_tokens: int = 0
def request_cost(tier, usage, batch=False):
p = PRICES[tier]
dollars = (usage.input_tokens * p["in"]
+ usage.output_tokens * p["out"]
+ usage.cache_write_tokens * p["cache_write"]
+ usage.cache_read_tokens * p["cache_read"]) / 1_000_000
return dollars * (BATCH_DISCOUNT if batch else 1.0)
class CostTracker:
def __init__(self, budget_per_user=None):
self.by_user = defaultdict(float)
self.by_feature = defaultdict(float)
self.tokens = defaultdict(int)
self.requests = 0
self.budget = budget_per_user
def record(self, user, feature, tier, usage, batch=False):
cost = request_cost(tier, usage, batch)
self.by_user[user] += cost
self.by_feature[feature] += cost
self.tokens["input"] += usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens
self.tokens["output"] += usage.output_tokens
self.requests += 1
return cost
def over_budget(self, user):
return self.budget is not None and self.by_user[user] >= self.budget
def route(task):
"""Pick the cheapest tier that is good enough for the job (rules you tune with your own evals)."""
if task.get("private"):
return "local" # data that must not leave the machine
if task["kind"] in ("classify", "extract", "summarise") and task["input_tokens"] < 50_000:
return "small" # short, well-defined jobs
if task["kind"] == "multi_file_change" or task.get("files", 0) >= 5:
return "large" # long, many-step work where mistakes are expensive
return "medium" # everyday chat and RAG answers
# 1. One request, priced three ways
u = Usage(input_tokens=2_000, output_tokens=500)
print("One request: 2,000 input + 500 output tokens")
for tier in ("large", "medium", "small"):
print(f" {tier:<6} ${request_cost(tier, u):.5f} (batch: ${request_cost(tier, u, batch=True):.5f})")
# 2. Prompt caching: a 10,000-token system prompt + documents reused on every turn
print()
print("10 turns that each resend a 10,000-token prefix (+300 new input, 400 output), tier 'medium':")
plain = sum(request_cost("medium", Usage(10_300, 400)) for _ in range(10))
cached = request_cost("medium", Usage(300, 400, cache_write_tokens=10_000))
cached += sum(request_cost("medium", Usage(300, 400, cache_read_tokens=10_000)) for _ in range(9))
print(f" without caching ${plain:.4f} with caching ${cached:.4f} saved {100 * (1 - cached / plain):.0f}%")
# 3. A day of traffic, aggregated per user and per feature
tracker = CostTracker(budget_per_user=0.05)
traffic = [
("alice", "chat", "medium", Usage(1_200, 350)),
("bob", "chat", "medium", Usage(900, 600)),
("alice", "summarise", "small", Usage(8_000, 300)),
("carol", "chat", "large", Usage(3_000, 1_500)),
("bob", "rag-answer", "medium", Usage(4_500, 400)),
("alice", "chat", "medium", Usage(1_500, 420)),
("dave", "nightly-report", "small", Usage(50_000, 2_000)),
("carol", "chat", "large", Usage(2_800, 1_700)),
]
print()
print("Request log:")
for user, feature, tier, usage in traffic:
batch = feature == "nightly-report"
cost = tracker.record(user, feature, tier, usage, batch=batch)
flag = " OVER BUDGET" if tracker.over_budget(user) else ""
print(f" {user:<6} {feature:<15} {tier:<6} in {usage.input_tokens:>6,} out {usage.output_tokens:>5,}"
f" ${cost:.5f}{' (batch)' if batch else ''}{flag}")
print()
print(f"requests {tracker.requests}, input tokens {tracker.tokens['input']:,}, output tokens {tracker.tokens['output']:,}")
total = sum(tracker.by_user.values())
print(f"total ${total:.4f}, average ${total / tracker.requests:.5f} per request")
print("by user: " + ", ".join(f"{k} ${v:.4f}" for k, v in sorted(tracker.by_user.items(), key=lambda kv: -kv[1])))
print("by feature: " + ", ".join(f"{k} ${v:.4f}" for k, v in sorted(tracker.by_feature.items(), key=lambda kv: -kv[1])))
print(f"projected monthly cost at 10,000 such requests/day: ${total / tracker.requests * 10_000 * 30:,.0f}")
# 4. Routing: the same workload, everything on "large" vs each job on the tier it needs
jobs = [
{"kind": "classify", "input_tokens": 400, "output_tokens": 5, "n": 20_000},
{"kind": "summarise", "input_tokens": 6_000, "output_tokens": 300, "n": 2_000},
{"kind": "chat", "input_tokens": 2_500, "output_tokens": 500, "n": 5_000},
{"kind": "multi_file_change", "input_tokens": 60_000, "output_tokens": 8_000, "n": 50, "files": 20},
{"kind": "chat", "input_tokens": 1_500, "output_tokens": 400, "n": 300, "private": True},
]
print()
print("Routing one day of jobs:")
all_large = routed = 0.0
for j in jobs:
tier = route(j)
u = Usage(j["input_tokens"], j["output_tokens"])
all_large += j["n"] * request_cost("large", u)
routed += j["n"] * request_cost(tier, u)
print(f" {j['n']:>6,} x {j['kind']:<18} -> {tier}")
print(f" everything on 'large': ${all_large:,.2f}/day routed: ${routed:,.2f}/day "
f"saved {100 * (1 - routed / all_large):.0f}%")PRICES: dollars per million tokens for each tier, including cache writes and reads;BATCH_DISCOUNTmodels a half-price batch interface. All example numbers.request_cost(tier, usage, batch): the cost formula above, with cached tokens priced separately.CostTracker: adds up cost per user and per feature, and flags users over a daily budget, the data you need for the "by feature" dashboard of lesson 11.8.route(task): a rule-based router. Private data goes local, short well-defined jobs go small, long multi-file work goes large, everything else medium. Real routers are tuned with evaluations and sometimes use a small classifier model.- The four printed sections: one request priced on three tiers, ten turns with and without caching a 10,000-token prefix, a day of traffic with budgets, and a day of jobs with and without routing.
One request: 2,000 input + 500 output tokens
large $0.02250 (batch: $0.01125)
medium $0.01350 (batch: $0.00675)
small $0.00450 (batch: $0.00225)
10 turns that each resend a 10,000-token prefix (+300 new input, 400 output), tier 'medium':
without caching $0.3690 with caching $0.1335 saved 64%
Request log:
alice chat medium in 1,200 out 350 $0.00885
bob chat medium in 900 out 600 $0.01170
alice summarise small in 8,000 out 300 $0.00950
carol chat large in 3,000 out 1,500 $0.05250 OVER BUDGET
bob rag-answer medium in 4,500 out 400 $0.01950
alice chat medium in 1,500 out 420 $0.01080
dave nightly-report small in 50,000 out 2,000 $0.03000 (batch)
carol chat large in 2,800 out 1,700 $0.05650 OVER BUDGET
requests 8, input tokens 71,900, output tokens 7,270
total $0.1993, average $0.02492 per request
by user: carol $0.1090, bob $0.0312, dave $0.0300, alice $0.0291
by feature: chat $0.1404, nightly-report $0.0300, rag-answer $0.0195, summarise $0.0095
projected monthly cost at 10,000 such requests/day: $7,476
Routing one day of jobs:
20,000 x classify -> small
2,000 x summarise -> small
5,000 x chat -> medium
50 x multi_file_change -> large
300 x chat -> local
everything on 'large': $272.75/day routed: $123.50/day saved 55%With these example prices the same request costs five times more on the large tier than on the small one, caching a repeated prefix saves about two thirds over ten turns, and routing a realistic mix of jobs saves more than half compared with sending everything to the largest model, while the twenty-file change still gets the most capable one. Notice also the "OVER BUDGET" flag: one heavy user on the large tier spends more than everyone else combined, the kind of pattern you only see if you track cost per user.
Type the current prices from your provider's pricing page (dollars per million tokens; the defaults are only examples) and describe your traffic. Nothing is sent anywhere.
Calling Claude with costs in mind
Here is a minimal, cost-aware call with the official Python SDK: the key comes from the environment, the output is capped, the answer streams, and the final usage numbers are printed so they can be logged and priced.
# Stream an answer from the Claude API with the official Python SDK.
# needs: pip install anthropic, and ANTHROPIC_API_KEY set in the environment (never in code).
# Not executed by the course tests (it needs a key and costs money). No temperature/top_p/top_k:
# on API version 2026-10-21 the Messages API rejects them with a 400.
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY; retries 429/529 errors itself
with client.messages.stream(
model="claude-haiku-5-5", # model ids change: check the models page
max_tokens=400, # always cap the output: it caps the cost too
system="You are a concise assistant.",
messages=[{"role": "user", "content": "Explain a KV cache in two sentences."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final = stream.get_final_message()
print(f"\ninput tokens {final.usage.input_tokens}, output tokens {final.usage.output_tokens}")This needs an API key and costs a little money per run, so our tests only check that it compiles; they did not execute it. Note what it does not send: no temperature or other sampling parameters, which the API version this course uses rejects. Model ids change over time, so check the current models page before copying one.
Defence in depth for injection, constant-time key checks, and the self-hosting break-even
Injection, in layers. Keep the operator's instructions in the system prompt and user or retrieved content in clearly delimited blocks; tell the model that content inside them is data; strip or neutralise markup that could be rendered (hidden links, images that leak data through URLs); give each tool the narrowest scope; require human approval for actions with side effects; and validate every tool input against its schema in your own code (lesson 9.8). Monitoring helps too: log which tools were called after reading untrusted content. Models are trained to resist injection, and providers publish guidance on it, but no vendor claims complete protection, so design as if some injections will succeed.
Checking keys. Compare secrets with a constant-time function (hmac.compare_digest in Python, crypto.timingSafeEqual in Node) or, better, store only a hash of each client key and compare hashes, so a database leak does not expose working keys. Give keys a recognisable prefix so secret scanners can find them, and an id you can log instead of the key itself.
When does self-hosting pay? A rented GPU costs the same per hour whether it is busy or idle. If it costs H dollars per hour and produces T tokens per hour at your real average load, its cost per million tokens is . Compare that with the API price of a model of similar quality for your task, and add the engineering time for operations, upgrades and on-call. At low or spiky volume the API wins almost always; at very high, steady volume on a task a small open model does well, self-hosting can win. Lesson 11.3's batching table shows why utilisation is everything: the same GPU produces dozens of times more tokens per hour when it is kept busy.
Common mistakes and debugging tips
A provider key in the frontend "just for the demo"
The demo is shared, someone opens the developer tools, and the key is used by strangers within hours. Automated scanners also search public repositories for keys continuously.
Fix: always go through a server-side proxy (module 7), revoke and rotate the exposed key immediately, and set provider spend limits.
Rate limiting by request count only
A client sends few requests, but each one carries a 150,000-token document; the request limit never triggers and the token bill explodes.
Fix: limit tokens per minute and input size as well, and charge expensive requests more bucket tokens.
In-memory limits with several servers
Each of four replicas allows 20 requests per minute, so the real limit is 80, and a restart resets everyone's budget.
Fix: keep limiter and budget state in a shared store (Redis with atomic operations), or route each key consistently to one instance.
Optimising cost per request instead of cost per task
Moving everything to the cheapest model cuts the price per call, but users now need three attempts, and agents loop longer; the total goes up and quality goes down.
Fix: measure cost per completed task and quality together on your evaluation set before switching tiers.
Key takeaways
- Threats: stolen keys, abuse and runaway spending, prompt injection, unsafe output, excessive agency, data leakage, supply chain. Defend in layers.
- Provider keys stay on the server; your clients get their own keys or sessions so they can be limited and revoked.
- Token buckets allow bursts and cap the rate; sliding windows count tokens exactly; limit requests, tokens and concurrency per key, with state shared across servers.
- The biggest cost levers: route each job to the cheapest tier that does it well, send fewer tokens, cache repeated prefixes, cap output, batch non-urgent work.
Exercise: a tokens-per-minute limit and a router test
1) Combine the two limiters from rate_limiter.py: a request is allowed only if the per-key token bucket (requests) and a per-key sliding window of 20,000 LLM tokens per 60 seconds both allow it. Write a test where a client sends three requests of 9,000 tokens within ten seconds. 2) Add a rule to route() in cost_tracker.py so that any task with more than 150,000 input tokens goes to the large tier, and print how the routed cost changes.
Hint
Check the sliding window first and only take from the bucket if it passes, or you will consume a request token for a refused request. In the test, the third request should be refused with a Retry-After of about 50 seconds.
Show a solution
class CombinedLimiter:
def __init__(self, clock):
self.requests = TokenBucket(capacity=10, refill_per_sec=0.5, clock=clock)
self.tokens = SlidingWindow(limit=20_000, window_sec=60, clock=clock)
def allow(self, llm_tokens):
ok, retry = self.tokens.allow(llm_tokens)
if not ok:
return False, retry
return self.requests.allow()With requests at t = 0, 5 and 10 s of 9,000 tokens each, the first two pass (18,000) and the third is refused, with a retry of 50 s (when the first event leaves the window). A more careful version would also give back the window's tokens if the bucket then refuses. For part 2, put the new rule before the "small" rule; with the example jobs nothing changes, since none is that long, which is itself a useful test result.
Mini-project: harden the Mini Chat proxy
The module 7 proxy (m07/server/proxy.js) already keeps the key on the server, validates bodies, caps max_tokens and applies a simple fixed-window limit per IP. Turn it into something you could put in front of real users. Use the tested helpers below as your starting point: they are pure functions with no dependencies, and hardening.check.js tests them (our test suite runs it).
- Token bucket per client. Replace
createRateLimiterwithcreateTokenBucket(capacity 5, refill 1 every 3 seconds). Charge 1 token per request plus 1 per 2,000 estimated input tokens (lesson 7.4's estimate), and sendRetry-Afterwith every 429. - Per-user daily budgets. Identify users (a session cookie or a per-user key instead of the IP). After each response, read the token usage from the final stream event, price it with
costOfand your own price table, andchargeit. Refuse new requests with 429 and a clear message whenallowedis false. - Structured logs. Write one
logLineper request to standard output: request id, user id, model, input and output tokens, cost, TTFT, total latency, status and stop reason. Confirm that no key and no message text appear. - Model-tier routing. Use
chooseModelso short requests and title generation go to the small tier and everything else to the medium tier, unless the user explicitly picks an allowed model. - Prove it. Add tests in the style of
m07/test/proxy.check.jsfor the 429 path, the budget path and the log format, then run the proxy and watch the logs while you chat.
// Mini-project helpers (lesson 11.9): pure functions to harden the module 7 Mini Chat proxy (m07/server/proxy.js).
// No npm packages, no network: plug them into handleClaude() and test them with `node hardening.check.js`.
// createTokenBucket per-key rate limit with bursts and a Retry-After value
// createBudgets per-user daily spending cap in US dollars (prices are YOUR config, not built in)
// chooseModel model-tier routing: the cheapest tier that fits the job
// costOf dollars for one response, from its usage numbers and your price table
// logLine one structured JSON log line, with secrets redacted and no prompt text
'use strict';
function createTokenBucket(opts) {
const capacity = opts.capacity, rate = opts.refillPerSec, now = opts.now || (() => Date.now() / 1000);
const buckets = new Map(); // key -> { tokens, last }
return function take(key, cost) {
const c = cost || 1, t = now();
const b = buckets.get(key) || { tokens: capacity, last: t };
b.tokens = Math.min(capacity, b.tokens + (t - b.last) * rate);
b.last = t;
buckets.set(key, b);
if (b.tokens >= c) { b.tokens -= c; return { ok: true, retryAfter: 0 }; }
return { ok: false, retryAfter: Math.ceil((c - b.tokens) / rate) };
};
}
function createBudgets(opts) {
const limit = opts.dailyUsd, now = opts.now || (() => Date.now());
const spent = new Map(); // user -> { day, usd }
const day = () => new Date(now()).toISOString().slice(0, 10); // resets at midnight UTC
const entry = (user) => {
const e = spent.get(user);
if (!e || e.day !== day()) { const fresh = { day: day(), usd: 0 }; spent.set(user, fresh); return fresh; }
return e;
};
return {
allowed: (user) => entry(user).usd < limit,
charge: (user, usd) => { entry(user).usd += usd; return entry(user).usd; },
remaining: (user) => Math.max(0, limit - entry(user).usd),
};
}
const TIERS = { small: 'claude-haiku-5-5', medium: 'claude-sonnet-5-5', large: 'claude-opus-5-5' };
function chooseModel(job, tiers) {
const t = tiers || TIERS;
if (job.userChoice && Object.values(t).includes(job.userChoice)) return job.userChoice; // an explicit, allowed choice wins
if (job.kind === 'code-change' || (job.files || 0) >= 5) return t.large; // long, many-step work
if (job.kind === 'classify' || job.kind === 'title' || (job.inputTokens || 0) < 300) return t.small;
return t.medium;
}
function costOf(usage, price) {
// price: dollars per million tokens, e.g. { in: 1, out: 5 } (example numbers: copy yours from the pricing page)
return ((usage.input_tokens || 0) * price.in + (usage.output_tokens || 0) * price.out) / 1e6;
}
const SECRET = /(sk-ant-[A-Za-z0-9_-]{8,}|Bearer\s+[A-Za-z0-9._-]+)/g;
function logLine(fields) {
const out = {};
for (const [k, v] of Object.entries(fields)) {
if (k === 'prompt' || k === 'messages' || k === 'completion') out[k + '_chars'] = JSON.stringify(v).length;
else if (/key|authorization|password/i.test(k)) out[k] = '[REDACTED]';
else out[k] = typeof v === 'string' ? v.replace(SECRET, '[REDACTED]') : v;
}
return JSON.stringify(out);
}
if (typeof module !== 'undefined') module.exports = { createTokenBucket, createBudgets, chooseModel, costOf, logLine, TIERS };Hints / reference solution
Wire the helpers into handleClaude in this order: same-origin check, user id, bucket (take(user, cost)), budget (budgets.allowed(user)), body validation (now including chooseModel to set body.model), then the upstream call. To charge the budget you need the usage numbers from the stream: Claude's streaming events report input tokens at the start of the message and the output token count in the final delta (lesson 7.5), so parse the events as you forward them, rather than buffering the whole response.
const take = createTokenBucket({ capacity: 5, refillPerSec: 1 / 3 });
const budgets = createBudgets({ dailyUsd: 0.50 });
// inside handleClaude, before calling upstream (estimateTokens: from m07/app/context.js):
const inTok = estimateTokens(JSON.stringify(input.messages));
const t = take(user, 1 + Math.floor(inTok / 2000));
if (!t.ok) { res.setHeader('retry-after', String(t.retryAfter)); return sendJson(res, 429, 'Too many requests'); }
if (!budgets.allowed(user)) return sendJson(res, 429, 'Daily budget used up; it resets at midnight UTC');
checked.body.model = chooseModel({ kind: input.kind, inputTokens: inTok, userChoice: input.model });
// after the stream ends:
const usd = costOf(usage, PRICES[checked.body.model]); // PRICES: your own table from the pricing page
budgets.charge(user, usd);
console.log(logLine({ event: 'chat', request_id: rid, user, model: checked.body.model, ...usage, usd, status: 200 }));For a multi-instance deployment, move the bucket and budget maps to Redis and keep the same function signatures. In the capstone (module 12) you will put this hardened proxy behind an assistant with configurable providers, including a local model through Ollama.
Check your understanding
A token bucket has capacity 5 and refills 1 token per second. A client sends 8 requests at once, waits 3 seconds, and sends 4 more. How many of the 12 are allowed?
- 5
- 8
- 12
Which job most clearly deserves the most capable (and most expensive) model tier?
- Generating a three-word title for a chat
- Classifying support emails into ten categories
- Planning and making a coordinated change across twenty files of a codebase
Why must the provider API key never be included in a web page's JavaScript, even in an obfuscated form?
- Everything sent to the browser can be read by the user, so the key can be extracted and used at your expense
- Browsers refuse to send API keys
- The key would make the page load more slowly