Sub topic 11
Loading once and reusing the model
This chapter assumes you can save a fitted Pipeline with joblib and load it back, as covered earlier. It deals with what happens after the file exists: a program that answers many prediction requests should read the file once and reuse the loaded object.
Why loading is the expensive step
Calling load does real work. It reads the file from disk, decompresses it if needed, and rebuilds every Python and NumPy object inside the estimator. For the iris pipeline this takes a few milliseconds. For a random forest with hundreds of trees it can take seconds. Calling predict on a loaded model is usually much cheaper than loading it.
A common mistake is to put load inside the function that handles each request. The model is then rebuilt for every call, and the cost of loading is paid again each time.
Comparing the two approaches
The script below creates the file, then times both patterns. It is self-contained, so you can run it as shown.
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)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
pipe.fit(X, y)
dump(pipe, "iris_model.joblib")
MODEL_PATH = "iris_model.joblib"
model = load(MODEL_PATH) # loaded once, when the module is imported
def predict_slow(rows):
return load(MODEL_PATH).predict(rows) # reloads on every call
def predict_fast(rows):
return model.predict(rows) # reuses the object in memory
def time_calls(func, n=200):
start = time.perf_counter()
for _ in range(n):
func(X[:1])
return time.perf_counter() - start
print(f"reload each call: {time_calls(predict_slow):.3f} s")
print(f"load once: {time_calls(predict_fast):.3f} s")Both functions return the same predictions. Only the timing differs, and the gap grows with model size.
Loading lazily with a cache
Loading at import time is simple, but it makes every import of the module pay the cost, including tests and tools that never predict. A lazy alternative loads on first use and keeps the result.
from functools import lru_cache
from joblib import load
@lru_cache(maxsize=1)
def get_model(path="iris_model.joblib"):
return load(path)
def predict(rows):
return get_model().predict(rows)The first call to get_model() reads the file. Later calls return the same object. With maxsize=1, the cache holds one model per distinct path argument, so always call it the same way. If you call get_model() in one place and get_model("iris_model.joblib") in another, the cache treats them as different keys and loads twice.
Things to watch in a long-running process
- Treat the loaded model as read-only. Do not call
fitorset_paramson the shared object while other requests use it. Callingpredictfrom several threads is normally safe for scikit-learn estimators, but changing the model is not. - Expect one copy per worker process. Web servers often start several worker processes. Each one loads its own copy, so memory use is the model size multiplied by the number of workers. Size your machine accordingly.
- Fail at startup, not on the first request. If the file is missing or was saved with an incompatible version, you want to learn that when the service starts. Load eagerly in production, then run one known prediction as a health check.
- Keep the input format fixed. A loaded pipeline expects the same number of features, in the same order, as during training. If you trained on a DataFrame, pass a DataFrame with the same column names.
- Reload deliberately. To deploy a new model, replace the file and restart the service, or load the new file into a new variable and swap the reference once it succeeds. Do not reload in the middle of handling a request.
Summary of the pattern
- Save the whole pipeline once, after training.
- Load it once when the process starts, or on first use through a cache.
- Call
predicton the shared object for every request. - Check at startup that the loaded model works, using a sample input with a known answer.
Exercise
A service calls joblib.load("model.joblib") at the top of its request-handling function, and responses are slow. What change fixes this, and what should you check about running several worker processes?
Show answer
Move the load call out of the handler so it runs once at startup, or wrap it in a function decorated with functools.lru_cache(maxsize=1) so the first request loads it and later requests reuse it. Each worker process keeps its own copy, so total memory is roughly the model size times the number of workers. Uncompressed files loaded with mmap_mode="r" can reduce that.