Learning path: Serve a Model in Production: Docker, Latency and Scaling · Step 8 of 9
Making ML Inference Fast: ONNX, Micro-Batching and Quantisation, Measured
Speed up a scikit-learn model without a faster machine: ONNX skips the checks around the math (8.38 ms to 0.087 ms here), micro-batching pays when requests overlap, and quantisation does nothing for a small logistic model but a lot for a big network.
What you will learn
- Export a scikit-learn pipeline to ONNX with skl2onnx and check that no answer changed
- Find where one prediction's time really goes before optimising it
- Build an asyncio micro-batcher and know when batching helps
- Judge when dynamic int8 quantisation pays off and when it does nothing
Before you start
- A Production FastAPI for an ML Model
- Latency Math: p50, p95, p99
The rain model is trained, and we won't change what it learned. We only change how quickly it answers, without buying a faster machine. Three tools: ONNX, batching and quantisation, each checked on the same rows.
Every timing here is from one machine (an Intel Core Ultra 9 185H, one thread), measured while it was busy with other work. Yours will differ, so measure your own. The project prints every number below.
A suitcase, not a bigger car
Your luggage doesn't fit. You could buy a bigger car; for us that means more machines. Or you could pack the suitcase better:
- ONNX: pack only what the trip needs.
- Batching: one trip with all the bags.
- Quantisation: roll the clothes tighter. They crease a little.
Better packing doesn't always help, and we'll see plainly where it did nothing.
Shared helpers
All the scripts import a few names from common.py: the inputs, a sample day, a one-thread ONNX session, and functions that turn rows into the arrays ONNX expects.
import os
os.environ["OMP_NUM_THREADS"] = "1" # one thread: a fair race
import time
import numpy as np
import onnxruntime as ort
import pandas as pd
from sklearn.model_selection import train_test_split
NUMBERS = ["Rainfall", "Humidity3pm", "Cloud9am", "Cloud3pm"]
FEATURES = NUMBERS + ["RainToday"]
TODAY = {"Rainfall": 0.0, "Humidity3pm": 85, "Cloud9am": 7,
"Cloud3pm": 8, "RainToday": "No"}
def split():
df = pd.read_csv("rain.csv")
X, y = df[FEATURES], df["RainTomorrow"]
return train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
def session(path):
opts = ort.SessionOptions()
opts.intra_op_num_threads = 1
return ort.InferenceSession(
path, opts, providers=["CPUExecutionProvider"])
def table_feed(df):
feed = {c: df[[c]].to_numpy(dtype="float32") for c in NUMBERS}
rain = df[["RainToday"]].fillna("")
feed["RainToday"] = rain.to_numpy(dtype=object)
return feed
def days_feed(days):
feed = {c: np.array([[d[c]] for d in days], dtype="float32")
for c in NUMBERS}
rain = [[d["RainToday"]] for d in days]
feed["RainToday"] = np.array(rain, dtype=object)
return feed
The file also has a timed() helper that warms up, runs several rounds and returns the median and p95. An ONNX prediction for one day is then session("model.onnx").run(None, days_feed([TODAY])); the second output holds the probabilities.
ONNX: refused first, then it worked
ONNX is a file format that stores a trained model as a list of plain steps, and a separate engine, ONNX Runtime, runs them. skl2onnx walks through our pipeline and converts each step:
import os
import joblib
from skl2onnx import to_onnx
from skl2onnx.common.data_types import (
FloatTensorType, StringTensorType)
from common import NUMBERS
model = joblib.load("model.joblib")
cat = model[0].named_transformers_["cat"]
cat[0].missing_values = "" # ONNX strings have no NaN
types = [(c, FloatTensorType([None, 1])) for c in NUMBERS]
types += [("RainToday", StringTensorType([None, 1]))]
onx = to_onnx(model, initial_types=types,
options={"zipmap": False})
with open("model.onnx", "wb") as f:
f.write(onx.SerializeToString())
print("model.joblib", os.path.getsize("model.joblib"), "bytes")
print("model.onnx ", os.path.getsize("model.onnx"), "bytes")
print("steps:", len(onx.graph.node))
The first time, without the missing_values line, it failed:
NotImplementedError: The converter is implemented when the missing values are string not <class 'float'>.
Our text imputer looks for NaN in RainToday, and ONNX text has no NaN. So we add one line: the imputer now treats an empty string as missing. Now it runs:
model.joblib 4298 bytes
model.onnx 1693 bytes
steps: 14
The same fitted numbers, now runnable without Python.
Before any stopwatch: the same rows
Faster means nothing if the answers changed, so check first. check.py sends the same test rows (missing values included) through both files:
rows: 28439
joblib accuracy: 0.831
onnx accuracy: 0.831
answers that differ: 0
largest probability gap: 1.3996911052416294e-07
Two models can match on accuracy and still disagree, so we count the answers that differ: zero. The largest probability gap is about 0.0000001, which is just rounding.
One request, timed
One request is what our FastAPI route does: make a one-row table, then call predict_proba. Five rounds of 2,000 requests each:
one request, 5 rounds of 2000, on this machine
joblib median 8.381 ms p95 16.469 ms rounds 7.517 to 9.239
onnx median 0.087 ms p95 0.255 ms rounds 0.085 to 0.089
About 96 times faster at the median, here. Why? Look inside one joblib request, step by step (inside.py):
inside one request, median of 5 rounds of 500
make the table 0.2615 ms
prepare the row 7.0151 ms
score, with checks 0.1547 ms
just the math 0.0068 ms
Preparing the row, the column transformer and its checks, takes 7 ms. The math itself takes 0.007 ms. ONNX wins by skipping what's around the math.
The first row pays for everything
If most of the cost is per call, what if one call carries many rows? batch_sizes.py tries 1 row, then 8, up to 512:
cost per row by batch size, median, on this machine
rows joblib us/row onnx us/row
1 6345.9 49.40
8 778.0 6.97
32 206.3 1.60
128 57.3 0.77
512 14.4 0.42
With joblib, one row costs about 6,300 microseconds; with 512 rows in a call, each costs about 14. ONNX falls too, from 49 down to 0.42. Most of the cost is per call, not per row. But requests arrive one at a time, so how do we get them into one call?
A micro-batcher
import asyncio
class MicroBatcher:
def __init__(self, score, max_size=32, wait_ms=0):
self.score = score
self.max_size = max_size
self.wait = wait_ms / 1000
self.queue = asyncio.Queue()
self.sizes = []
async def submit(self, day):
done = asyncio.get_running_loop().create_future()
await self.queue.put((day, done))
return await done
async def run(self):
while True:
batch = [await self.queue.get()]
if self.wait:
await asyncio.sleep(self.wait)
while (not self.queue.empty()
and len(batch) < self.max_size):
batch.append(self.queue.get_nowait())
self.sizes.append(len(batch))
days = [day for day, _ in batch]
for (_, done), answer in zip(batch, self.score(days)):
done.set_result(answer)
submitcreates a future, a ticket for an answer that doesn't exist yet. The day and the ticket go in a queue, and the caller waits on the ticket.runtakes the first request, then the innerwhileloop takes everything else already waiting, up tomax_size.- All those days go into one call to
score, and each answer goes back to its own ticket. - With
wait_ms=0it never waits for more. It takes what's there. On a quiet day, that's a batch of one.
Batching pays when requests overlap
load.py runs three plans: one by one, batch with no wait, and batch with a 5 ms wait, at 1 caller and at 32 callers:
median, p95 in ms, requests a second, 5 rounds, this machine
joblib 1 callers one by one 6.59 10.01 142
joblib 1 callers batch, no wait 6.25 11.48 151
joblib 1 callers batch, wait 5 ms 16.56 29.25 55
joblib 32 callers one by one 202.28 314.01 155
joblib 32 callers batch, no wait 6.57 10.14 4518
joblib 32 callers batch, wait 5 ms 16.73 25.63 1890
onnx 1 callers one by one 0.05 0.16 12342
onnx 1 callers batch, no wait 0.06 0.18 11642
onnx 1 callers batch, wait 5 ms 15.59 17.72 64
onnx 32 callers one by one 2.27 4.17 13191
onnx 32 callers batch, no wait 0.25 0.59 122619
onnx 32 callers batch, wait 5 ms 15.60 16.92 2052
- joblib, 32 callers: one by one, the median is 202 ms and p95 is 314. Batching with no wait gives 6.57 ms, p95 10.1, and throughput goes from 155 to about 4,500 requests a second.
- joblib, 1 caller: 6.59 ms one by one, 6.25 batched. There's nothing to batch. The 5 ms wait costs about 16 ms here, so don't assume a timer is exact.
- ONNX, 32 callers: from 2.27 ms to 0.25 ms.
Put behind FastAPI (app_fast.py: ONNX plus the batcher, a demo app with plain fields and no input limits), one caller over HTTP gets the same answer much faster:
200 {'rain_tomorrow': 'Yes', 'probability': 0.63}
over HTTP: median 13.07 ms p95 18.77 ms
200 {'rain_tomorrow': 'Yes', 'probability': 0.63}
over HTTP: median 1.41 ms p95 2.26 ms
The first is the old app, the second app_fast. Batching pays when requests overlap. On a quiet service it does nothing, and a wait only hurts.
Quantisation: no help for our model
Our weights are stored as 32-bit floats. Quantisation maps each weight to a small whole number: one byte instead of four, with a little rounding. Here are the six weights of the logistic model, scaled so the largest, 1.00, becomes 127:
| Input | Weight | int8 |
|---|---|---|
| Rainfall | 0.148 | 19 |
| Humidity3pm | 1.004 | 127 |
| Cloud9am | 0.108 | 14 |
| Cloud3pm | 0.423 | 54 |
| RainToday No | -0.811 | -103 |
| RainToday Yes | -0.215 | -27 |
That table is a picture of the idea. Now the real tool on our model:
from onnxruntime.quantization import QuantType, quantize_dynamic
quantize_dynamic("model.onnx", "model_q.onnx",
weight_type=QuantType.QInt8)
model.onnx 1693 bytes accuracy 0.8310 median 25 us p95 57 us
model_q.onnx 2089 bytes accuracy 0.8310 median 26 us p95 70 us
The file got bigger, and it isn't faster. Plainly: quantisation doesn't help this model. This tool only rewrites matrix steps, and our logistic model has none. Leave it alone.
Where it does help: big weight matrices
net.py trains four small neural networks on the same inputs, exports each to ONNX and quantises it (size in KB, accuracy, median and p95 in ms, for one row and for a batch of 256):
(16,) answers that differ: 125 of 28439
float 2.8 0.8331 one 0.037 0.183 batch256 0.163 0.253
quant 4.4 0.8330 one 0.063 0.138 batch256 0.118 0.451
(64, 64) answers that differ: 179 of 28439
float 20.8 0.8333 one 0.037 0.148 batch256 0.289 1.246
quant 10.2 0.8327 one 0.037 0.107 batch256 0.144 0.774
(256, 256) answers that differ: 115 of 28439
float 267.6 0.8331 one 0.056 0.175 batch256 1.810 7.213
quant 73.0 0.8333 one 0.056 0.145 batch256 0.278 0.637
(1024, 1024) answers that differ: 112 of 28439
float 4134.6 0.8332 one 0.278 2.529 batch256 46.404 91.181
quant 1044.2 0.8329 one 0.068 0.215 batch256 2.395 4.840
(64, 64) over 10 seeds, accuracy change after quantising: -0.0004 to +0.0009
- 16 neurons: the file goes from 2.8 KB to 4.4 KB. Bigger.
- Two layers of 64: the file halves, and one row takes the same time.
- Two layers of 256: 268 KB to 73 KB, and a batch goes from 1.81 ms to 0.28 ms.
- Two layers of 1,024: about 4,100 KB to 1,040 KB; one row from 0.28 ms to 0.07 ms, a batch from 46 ms to 2.4 ms.
Answers do change a little: 112 of them for the biggest network, and accuracy went from 0.8332 to 0.8329. Over ten seeds of the 64-64 network, the accuracy change was between -0.0004 and +0.0009. A small crease, but check it. The bigger the matrices, the more quantisation gives.
Common mistakes
- Timing before checking answers. Count the answers that differ, not just accuracy.
- Optimising the math. Here the math was 0.007 ms of an 8 ms request. Measure inside first.
- Adding a batching wait "just in case". With one caller, a 5 ms wait made each request about 16 ms.
- Quantising every model. A model with no big weight matrices got a bigger file and no speed-up.
- Quoting one run. Report the median and the p95, over several rounds, with the machine.
Quick recap
| Tool | What it did here | When it helps |
|---|---|---|
| ONNX | 8.381 ms to 0.087 ms median, 0 answers changed | When the cost is the checks around the math |
| Micro-batching | 32 callers, joblib: 202 ms to 6.57 ms median | When requests overlap |
| Quantisation | Logistic model: no gain. 1,024-wide network: batch 46 ms to 2.4 ms | Big weight matrices |
Try it yourself
In load.py, change the max size from 32 to 4 in PLANS. What happens to 32 callers with joblib? The project and the rain data are in the community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Measuring Latency of an ML API: Timing Inside with OpenTelemetry, Outside with a Load Test and Locust
Next →Sizing and Autoscaling an Inference Service: From One Replica to a Replica Count
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
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 (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.