Sub topic 11
Loading Once and Reusing the Model
This chapter assumes you can save and load a fitted estimator or Pipeline with joblib, as covered earlier in this tutorial. It also assumes basic Python (modules, functions, global names) and a rough idea of how a web service or batch job calls a model many times. The chapter shows where the load belongs in a program that makes repeated predictions, and what to check before you depend on it.
Why loading per prediction is a mistake
Loading a model file does three things. It reads bytes from disk, rebuilds the Python objects (estimator, fitted arrays, pipeline steps), and allocates memory for them. Prediction on a few rows is usually much cheaper than that. If every request calls load, most of the request time goes to rebuilding a model that has not changed.
The fix is to load once when the process starts, keep the object in memory, and call predict on it for every request. A fitted estimator is an ordinary Python object, so holding a reference to it costs nothing.
The next script measures the difference. It trains a small Pipeline, saves it, and then predicts 150 single rows in two ways.
import time
from joblib import dump, load
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
model.fit(X, y)
dump(model, "iris_model.joblib")
rows = X.tolist()
def predict_reloading(row):
m = load("iris_model.joblib") # loads on every call
return m.predict([row])[0]
loaded = load("iris_model.joblib") # loads once
def predict_reused(row):
return loaded.predict([row])[0]
start = time.perf_counter()
reloaded_preds = [predict_reloading(r) for r in rows]
t_reload = time.perf_counter() - start
start = time.perf_counter()
reused_preds = [predict_reused(r) for r in rows]
t_reuse = time.perf_counter() - start
print(f"load every time: {t_reload:.3f} s")
print(f"load once: {t_reuse:.3f} s")
print("same predictions:", reloaded_preds == reused_preds)The exact times depend on your machine. The load-every-time version is typically several times slower even for this tiny model. The gap grows with model size, because a random forest with hundreds of trees can take seconds to load and milliseconds to predict.
Where the load belongs
The load should run in the startup path of your program, not in the request path. The sequence below shows the order of events in a long-running service.
Three common ways to arrange this:
- Module-level variable. Load at import time. This is the simplest option, but importing the module (for example in a test) also pays the load cost and fails if the file is missing.
- Application startup hook. Most web frameworks provide one, such as a lifespan or startup event. Load there and store the model in application state.
- Cached accessor. A function loads the model on first call and returns the same object afterwards. This gives lazy loading with one line of code.
The cached accessor needs only the standard library:
from functools import lru_cache
from pathlib import Path
import numpy as np
from joblib import load
MODEL_PATH = Path("iris_model.joblib")
FEATURES = [
"sepal length (cm)",
"sepal width (cm)",
"petal length (cm)",
"petal width (cm)",
]
@lru_cache(maxsize=1)
def get_model():
return load(MODEL_PATH)
def warm_up():
model = get_model()
model.predict(np.zeros((1, len(FEATURES))))
def predict_one(features: dict) -> dict:
model = get_model()
row = np.array([[features[name] for name in FEATURES]], dtype=float)
proba = model.predict_proba(row)[0]
best = int(np.argmax(proba))
return {
"class": int(model.classes_[best]),
"probability": float(proba[best]),
}
if __name__ == "__main__":
warm_up()
print(predict_one({
"sepal length (cm)": 5.1,
"sepal width (cm)": 3.5,
"petal length (cm)": 1.4,
"petal width (cm)": 0.2,
}))Run this after the previous script has written iris_model.joblib. lru_cache(maxsize=1) on a function with no arguments stores the first return value and returns it on every later call, so the file is read once.
The wrapper also does input handling. It builds the row in the order of FEATURES, not in the order a client happens to send keys. A Pipeline trained on a NumPy array has no column names, so the order is part of the model's contract. Keep that list next to the model and test it.
Why a warm-up call
warm_up runs one throwaway prediction at startup. The first prediction can be slower than later ones, because libraries may allocate buffers or start thread pools on first use. Doing it at startup moves that delay away from the first real user. It also acts as a smoke test: if the file is corrupt or the feature count is wrong, the service fails when it starts rather than on the first request.
Reuse is safe for prediction, not for training
Calling predict, predict_proba, or transform on a fitted estimator reads its learned attributes and does not change them. That is why many threads can share one loaded model. Two rules keep this true:
- Never call
fit,partial_fit, orset_paramson the shared object while requests are being served. Another thread could see a half-updated model. - Do not store per-request data on the model, for example by assigning your own attributes to it.
Some estimators, such as random forests, use n_jobs at prediction time to spread work over several threads. If you run many worker processes and each uses all CPU cores, they compete for the same cores and latency gets worse. For small requests, n_jobs=1 (set on the model before saving, or with set_params right after loading and before serving) is often the better choice. Measure with your own traffic before changing it.
Sharing large arrays between workers
For large models, joblib can memory-map the big NumPy arrays instead of copying them into each process. The operating system then keeps one copy in its page cache, and every worker reads from it.
from joblib import load
model = load("iris_model.joblib", mmap_mode="r")
print(type(model).__name__)mmap_mode="r" opens the arrays read-only, which is what you want for prediction. This only helps when the file was saved uncompressed. If you used compress=3 as in the compression chapter, joblib has to decompress into ordinary memory, so memory mapping gives no benefit. For a model that is served by many workers, an uncompressed file plus mmap_mode="r" is often a better trade than a smaller file. For a model that is small or downloaded rarely, compression is usually fine. The iris model is far too small to show a difference. The option matters for models with arrays of tens of megabytes or more.
Updating the model without restarting
At some point you will retrain and want the service to use the new file. There are two safe approaches.
The simplest is to restart the service so it loads the new file at startup. Rolling restarts behind a load balancer make this free of downtime.
If you need to swap in place, load the new model completely before you replace the reference. Python assignment of a name is atomic, so requests see either the old model or the new one, never a mix.
import threading
from joblib import load
_model = load("iris_model.joblib")
_lock = threading.Lock()
def current_model():
return _model
def reload_model(path):
global _model
new_model = load(path) # slow part, done outside the lock
new_model.predict([[0.0, 0.0, 0.0, 0.0]]) # smoke test before swapping
with _lock:
_model = new_modelRequest code should call current_model() once per request and use that object throughout, so one request never mixes two models. If the smoke test raises an exception, the old model stays in place.
On the writing side, save to a temporary name and then rename, so a reader never sees a half-written file:
import os
from joblib import dump
dump(model, "iris_model.joblib.tmp")
os.replace("iris_model.joblib.tmp", "iris_model.joblib")os.replace is atomic on the same filesystem on both Linux and Windows.
Checks to run at load time
Startup is the cheapest place to catch environment problems, so use the metadata file from the earlier chapter and compare it with the running environment.
- Read
iris_model.meta.jsonand compare the saved scikit-learn version withsklearn.__version__. Log a warning or refuse to start when they differ. A mismatch can produce warnings, wrong predictions, or errors. - Load from a fixed path in your configuration. Never build the path from request data, because loading a pickle-based file runs code. Only your own deployment should be able to put a file there.
- Run
warm_upand compare the result on a few stored example rows with outputs you saved when you trained the model. This is the round-trip check from earlier, repeated in the deployed environment. - Log the model file name and its modification time, or better, a hash of the file, so you can tell later which model produced a given prediction.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Every request takes hundreds of milliseconds | `load` is inside the request function | Move the load to startup or a cached accessor |
| Memory use is several times the model size | Several worker processes each loaded a copy | Reduce workers, or use an uncompressed file with `mmap_mode="r"` |
| `FileNotFoundError` on startup | Relative path resolved from a different working directory | Use an absolute path or a path from configuration |
| Predictions change right after a deploy | Different scikit-learn version, or a different feature order | Compare versions at startup and keep the feature list with the model |
| `ValueError: X has 3 features, but ... expecting 4` | Client sent the wrong number of values | Validate and order inputs before calling `predict` |
| Rare wrong results under load | Code calls `fit` or changes parameters on the shared model | Treat the loaded model as read-only |
Summary
Load the model file once, in the startup path, and keep the fitted Pipeline in memory. Treat it as read-only while serving. Run one warm-up prediction, and check library versions against your recorded metadata. For large models served by many workers, consider an uncompressed file with mmap_mode="r". When you update the model, either restart or swap the reference after the new model has loaded and passed a smoke test.
Exercise
A service has 4 worker processes. Each worker calls joblib.load on a 400 MB compressed model file at the start of every request. Name two changes that would reduce latency and one change that would reduce memory use, and say what limits the memory change.
Show answer
Latency: move the load out of the request function into worker startup (or a cached accessor such as lrucache), and add a warm-up prediction at startup so the first request is not slower. Memory: save the model uncompressed and load it with mmapmode="r", so the large NumPy arrays are memory-mapped and shared through the operating system page cache instead of copied into each worker. The limit is that memory mapping does not work with compressed files, and only the large arrays are shared. The rest of the Python objects are still loaded once per worker. Without the memory change, the service holds four copies, about 1.6 GB.
Exercise
Write the body of reload_model(path) so that a failed load or a failed smoke test leaves the currently served model unchanged. Why must the new model be fully loaded before the shared reference is replaced?
Show answer
Load into a local variable first, for example newmodel = load(path), then run a test prediction such as newmodel.predict(sample_rows). Only after both succeed, assign the global name (optionally under a lock). If load or predict raises an exception, the assignment never runs and the old model keeps serving. The new model must be fully loaded first because a reference to a partly built or untested object could be used by a request in the meantime, and because replacing the reference is atomic while loading is not.