Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 15 of 16
Ticket Routing, Part 3: Quantise to int8, Host Behind FastAPI and Measure the Server
Shrink the ticket encoder to int8 (3 of 537 validation tickets change, 90.9 MB becomes 58.6 MB), serve it with FastAPI and measure the server: on this CPU, int8 is slower (p95 24.9 ms vs 14.3 ms) and the process uses more memory (762 MB vs 556 MB).
What you will learn
- Quantise an encoder's Linear layers to int8 with one PyTorch call and check quality did not drop
- Explain why the file shrank from 90.9 MB to 58.6 MB and not to a quarter
- Serve the model with FastAPI: load once, input limits, a busy limit and a log line without the ticket text
- Measure cold start, memory and p95 on the running server
Before you start
- Ticket Routing, Part 2: Fine-Tuning a Small Encoder on a CPU, With a Run Log and Honest Ranges
- A Production FastAPI for an ML Model: Input Limits, /health, /ready and a Model Version
- Latency Math: p50, p95, p99 and Why the Tail Reaches Your Users
Our small encoder routes tickets well (Part 2). Now we want to serve it. First we shrink it, storing its weights in 8 bits instead of 32. Then we check it can still do its job. Then we put it behind FastAPI with limits and logging. And then we measure three things on the server: cold start, memory and p95. One of them will surprise you.
This part uses a bigger batch of the same synthetic tickets, 8,000 instead of 2,400, so the numbers are steadier: 3,154 for training, 537 for validation and 527 for test. The encoder is retrained on that data (losses 0.5392, 0.189, 0.1701), and everything here is chosen on validation; the test group isn't touched. All timings come from one CPU limited to 2 threads, with simulated traffic.
Poster to postcard
Think about a big poster you want to shrink to a postcard. Most of it survives: the headline, the picture. But you don't just assume that. You hold the postcard up and try to read it. Shrink too far and the small print turns to mush. That's quantising: keep fewer digits per weight, then check you can still read it.
One call to shrink it: quantise.py
def to_int8(model):
"""Real int8: Linear weights stored as 8-bit."""
return torch.ao.quantization.quantize_dynamic(
copy.deepcopy(model), {torch.nn.Linear},
dtype=torch.qint8)
- A deep copy first, because we still want the original for comparing.
quantize_dynamicis told which layers (torch.nn.Linear) and which type (qint8). So only the Linear layers get touched. Remember that.- Each weight snaps to one of about 250 steps, so it moves a tiny bit, and it takes 1 byte instead of 4.
- The numbers flowing through are converted while the ticket runs. That's the "dynamic" part.
Can we still read it?
python run.py quantise on the 537 validation tickets:
fp32 size= 90.9 MB val acc=0.873 p50= 7.6 ms p95= 13.1 ms
int8 size= 58.6 MB val acc=0.875 p50= 10.7 ms p95= 16.8 ms
int8 differs from fp32 on 3 of 537
Quality: 0.873 to 0.875, and the two models disagree on just 3 tickets of 537. No regression.
Size: 90.9 MB down to 58.6. But 8 bits is a quarter of 32, so why not a quarter of the size? python run.py where answers it:
embeddings=47.7 MB linear=43.1 MB other=0.1 MB
The embeddings are 47.7 MB, and we only asked for Linear layers. The Linear part, 43.1 MB, drops to about 10.8. Add it back up and you get 58.6.
run.py where and run.py quantise; the 10.8 MB is the rest of the 58.6 MB. Bars to scale.Speed: p50 goes from 7.6 ms to 10.7 ms. On this CPU, it got smaller and slower. That's why we measure. (Making ML Inference Fast shows quantisation on other models, and Model Size and Memory has the parameters-times-bytes rule.)
How small is too small?
To see how far we could push it, fake_bits rounds the Linear weights to fewer levels. The name is honest: it's simulated rounding. Values change, the file doesn't shrink, so this only tells us about quality.
def fake_bits(model, bits):
"""SIMULATED: round Linear weights to 2**bits levels.
Values change, the file does not get smaller."""
small = copy.deepcopy(model)
levels = 2 ** (bits - 1) - 1
for mod in small.modules():
if isinstance(mod, torch.nn.Linear):
w = mod.weight.data
step = w.abs().max() / levels
mod.weight.data = torch.round(w / step) * step
return small
8 bit (simulated) val acc=0.872
6 bit (simulated) val acc=0.812
4 bit (simulated) val acc=0.767
3 bit (simulated) val acc=0.628
2 bit (simulated) val acc=0.192
At 2 bits it scores 0.192. With four queues, plain guessing gets about 0.25, so this is worse than guessing. That's the small print turning to mush. So 8 bits it is, and we keep the 2-bit model around as a bad candidate for Part 4.
Behind FastAPI: serve.py
"""FastAPI host for the ticket router, with limits."""
import logging
import os
import threading
import time
import torch
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from transformers import AutoTokenizer
from data import QUEUES
from encoder import NAME
from quantise import to_int8
torch.set_num_threads(2)
KIND = os.environ.get("MODEL_KIND", "int8")
MAX_BUSY = 4
logging.basicConfig(level=logging.INFO,
format="%(message)s")
log = logging.getLogger("router")
tok = AutoTokenizer.from_pretrained(NAME)
model = torch.load("work/fp32.pt", weights_only=False)
model = model.eval()
if KIND == "int8":
model = to_int8(model)
slots = threading.BoundedSemaphore(MAX_BUSY)
app = FastAPI()
class Ticket(BaseModel):
text: str = Field(min_length=1, max_length=500)
@app.get("/health")
def health():
return {"model": KIND}
@app.post("/route")
def route(ticket: Ticket):
if not slots.acquire(blocking=False):
raise HTTPException(503, "busy, try again")
try:
t0 = time.perf_counter()
enc = tok(ticket.text, return_tensors="pt",
truncation=True, max_length=48)
with torch.no_grad():
i = model(**enc).logits.argmax(1).item()
ms = (time.perf_counter() - t0) * 1000
finally:
slots.release()
log.info("queue=%s chars=%d ms=%.1f", QUEUES[i],
len(ticket.text), ms)
return {"queue": QUEUES[i], "model": KIND}
- The model and tokenizer load once, at the top, when the server starts, not per request. Notice the int8 path: it loads the full fp32 model, then
to_int8makes a converted copy. Keep that in mind for the memory number. - A
Ticketis a small pydantic class: text between 1 and 500 characters. POST /routetokenizes (truncated to 48 tokens), runs the model, and the biggest output picks the queue.- At most
MAX_BUSY= 4 tickets run at once. If no slot is free, the answer is 503 straight away instead of a growing queue. - One log line per ticket with the queue, the length and the milliseconds. The length, not the text, because tickets can hold customers' private details.
Limits, tested: measure.py
measure.py starts the server with uvicorn and sends it simulated traffic from the validation tickets. The limit checks on int8:
too long -> 422
empty -> 422
burst 32 -> 9 ok, 23 busy
log line: queue=technical chars=29 ms=42.3
A 501-character ticket and an empty one both come back 422: FastAPI rejects them before the model runs. Then 32 tickets at once: 9 come back OK and 23 are told "busy, try again". The server stays standing, and the caller knows to retry. (Limits like these are covered in A Production FastAPI for an ML Model.)
Cold start, memory, p95
Now the three numbers, for both models behind the same server. One machine, one run, 200 tickets each. Cold start is the median of three starts, with fp32 measured first, and memory is read once right after startup.
fp32 cold=11.7 s mem= 556 MB first= 43.5 ms p50= 9.5 ms p95= 14.3 ms hits=178/200
int8 cold= 8.7 s mem= 762 MB first= 55.7 ms p50= 11.8 ms p95= 24.9 ms hits=181/200
| Measured on the server | fp32 | int8 |
|---|---|---|
| Cold start (median of 3) | 11.7 s | 8.7 s |
| Process memory after startup | 556 MB | 762 MB |
| First ticket | 43.5 ms | 55.7 ms |
| p50 over 200 tickets | 9.5 ms | 11.8 ms |
| p95 over 200 tickets | 14.3 ms | 24.9 ms |
hits is the number of the 200 tickets routed to the right queue. These are server round trips, so they're higher than the in-process numbers from run.py quantise (7.6 and 10.7 ms p50). Keep the two tables apart.
- Cold start. fp32 went first, so don't read the gap between 11.7 and 8.7. Call it around ten seconds when the server can't answer. And the first ticket after that took 43.5 and 55.7 ms against a typical 10 or so, so warm it up before it takes traffic.
- Memory went up. 556 MB for fp32, 762 MB for int8. My best reading is what we saw in
serve.py: it loads the full model, copies it, then converts it, and the process doesn't hand that memory back. The run shows it's higher, not why. - p95: 14.3 ms against 24.9 ms. That's only the slowest ten of 200, so it's noisy. (Why the tail matters is in Latency Math.)
So on this machine, int8 saved 32 MB on disk and cost us memory and speed. You only know that because you measured the server.
Common mistakes
- Assuming 8 bits means a quarter of the size. Only the layers you quantise shrink.
- Assuming smaller means faster. Here p50 went from 7.6 to 10.7 ms in process.
- Measuring the model and not the server. Memory and cold start only show up in the running process.
- Loading the model per request. Load once at startup.
- Logging the ticket text. Log the length and the queue; the text may hold private details.
Recap
| Step | Result |
|---|---|
| Quantise to int8 | 3 of 537 changed, val 0.873 to 0.875 |
| File size | 90.9 MB to 58.6 MB (embeddings stay 32-bit) |
| Simulated 2 bit | 0.192, worse than guessing |
| Limits | 422 for too long and empty, burst of 32: 9 ok, 23 busy |
| Server, int8 vs fp32 | more memory (762 vs 556 MB), worse p95 (24.9 vs 14.3 ms) |
Try it yourself: in serve.py, set MAX_BUSY to 1 and run python measure.py again. Guess the burst line first. The project files are in the community, free to join.
In Part 4, int8 takes over from fp32 in stages, and the 2-bit model gets caught.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)Related posts
Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
The whole ML workflow on 205 cars: clean the brand out of CarName, split first, audition five regressors on the same folds, tune the random forest, test once (RMSE 2,195, R2 0.939), save it and serve prices with FastAPI.
Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
Before training a fraud model, write down what good means. On 6,000 synthetic validation transactions, a rule that never flags is 96.13% accurate and costs 23,200, flagging everyone costs 28,840, and a small contract.py fixes the rules first.
Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
Train the fraud model against its contract: a time split of 30,000 synthetic transactions, a card_n_1h feature that never looks ahead, XGBoost that pays 23,200 at 0.5, and a cost-picked threshold of 0.045 that brings validation to 14,955 and test to 16,765.
Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
A payment is waiting on the fraud score. Time each stage (the model takes 0.43 ms of a 3.3 ms request), then load test: p99 is 6.1 ms with one client and 163.3 ms with 32, against an example 50 ms budget. Then a Dockerfile, built and run once.