Sub topic 6
Compressing model files
This chapter shows how to shrink a saved scikit-learn model with joblib's compress argument. It also covers how to measure the trade-off and when compression is the wrong tool. It assumes you can save and load a model with joblib.dump and joblib.load, and that you know how a fitted estimator or Pipeline is built.
Why model files get large
A saved model contains the full fitted state of the estimator. The size depends on the algorithm.
- A linear model such as
LogisticRegressionstores one coefficient per feature and class. Its file is a few kilobytes. - A tree ensemble such as
RandomForestClassifierstores every node of every tree. Its file can reach tens or hundreds of megabytes. - A nearest-neighbor model such as
KNeighborsClassifierstores a copy of the training data, so the file grows with the dataset.
Large files cost you in three places: disk or object-storage space, transfer time to a server or container, and load time at startup. Compression addresses the first two. It often makes the third worse, because the file must be decompressed on load.
Compressing with joblib
joblib.dump takes a compress argument. The default is 0, which writes the file uncompressed. The simplest way to enable compression is an integer from 1 to 9.
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_compressed.joblib", compress=3)
loaded = load("iris_model_compressed.joblib")
print(loaded.predict(X[:3]))An integer selects the zlib method at that level. Higher levels try harder to find redundancy, so the file gets smaller and saving gets slower. Level 3 is a common default, and the joblib documentation suggests it as a good balance between size and speed.
Notice that load takes no compression argument. joblib recognizes the compression format from the file's header, so the same call loads compressed and uncompressed files.
Choosing a compression method
The compress argument accepts several forms.
| Value | Meaning |
|---|---|
| `0` or `False` | No compression (the default). |
| `True` | zlib at level 3. |
| `1` to `9` | zlib at that level. |
| `"gzip"`, `"bz2"`, `"lzma"`, `"xz"` | That method at its default level. |
| `("lzma", 6)` | A tuple of method and level. |
Two further details matter in practice.
- If the file name ends in
.z,.gz,.bz2,.xz, or.lzmaand you ask for a nonzero compression level, joblib uses the method that matches the extension. A name likemodel.joblib.xztherefore signals the format to anyone reading the directory. Passing the method explicitly in a tuple avoids relying on this rule. - The
"lz4"method is also supported, but only when the separatelz4package is installed. It is very fast and compresses less than the others. A model saved this way cannot be loaded in an environment that lackslz4.
Measuring the trade-off
Do not guess which setting suits your model. Compression ratios depend on the contents of the file, and the speed cost depends on your hardware. The script below fits a random forest, a model type with large files, and saves it with several settings. It prints the size, save time, and load time for each.
import os
import tempfile
import time
from joblib import dump, load
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
X, y = make_classification(n_samples=5000, n_features=20, random_state=0)
model = RandomForestClassifier(n_estimators=100, random_state=0).fit(X, y)
settings = [
("none", 0),
("zlib level 3", 3),
("zlib level 9", 9),
("gzip level 3", ("gzip", 3)),
("lzma level 3", ("lzma", 3)),
]
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "model.joblib")
print(f"{'setting':<14}{'size MB':>9}{'save s':>9}{'load s':>9}")
for label, compress in settings:
start = time.perf_counter()
dump(model, path, compress=compress)
save_seconds = time.perf_counter() - start
size_mb = os.path.getsize(path) / 1e6
start = time.perf_counter()
load(path)
load_seconds = time.perf_counter() - start
print(f"{label:<14}{size_mb:>9.2f}{save_seconds:>9.2f}{load_seconds:>9.2f}")The exact numbers vary between machines, so run it yourself. The pattern you should expect looks like this:
- The uncompressed file is the largest, and it saves and loads fastest.
- Level 3 gives most of the size reduction at a modest time cost.
- Level 9 usually shrinks the file only a little more than level 3, and saving takes noticeably longer.
lzmausually produces the smallest file and takes the longest to write.
Saving happens once per trained model, so slow saves are rarely a problem. Loading happens every time a service starts. A method that is slow to decompress has a recurring cost, so compare load times as well as sizes.
Compressing with the standard library
joblib is not the only route. Because pickle writes to any binary file object, you can wrap the file in the standard library's gzip module. Use this when you must stay with plain pickle, for example when a tool in your workflow only reads .pkl.gz files.
import gzip
import pickle
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
model = LogisticRegression(max_iter=200).fit(X, y)
with gzip.open("model.pkl.gz", "wb") as f:
pickle.dump(model, f)
with gzip.open("model.pkl.gz", "rb") as f:
loaded = pickle.load(f)
print(loaded.predict(X[:3]))For models that hold large NumPy arrays, joblib is usually the better choice. It stores arrays in an efficient layout, and it handles the compression for you.
What compression does not change
Compression changes how the bytes are stored. It does not change what the file means, so every caveat from earlier chapters still applies.
- Security. A compressed pickle-based file can still run arbitrary code when loaded. Compression gives no protection, and a compressed file from an untrusted source is as dangerous as an uncompressed one.
- Version compatibility. Decompression yields the same pickle stream, which still depends on the scikit-learn and Python versions that wrote it. Keep recording those versions next to the file.
- Predictions. Compression is lossless. A loaded model gives the same predictions as the saved one, and you can confirm this with the round-trip check you already know.
The check below applies the round-trip test to a compressed file. It reuses model and X from the benchmark script.
import numpy as np
from joblib import dump, load
dump(model, "forest.joblib", compress=("zlib", 3))
loaded = load("forest.joblib")
assert np.array_equal(loaded.predict(X), model.predict(X))
assert np.allclose(loaded.predict_proba(X), model.predict_proba(X))
print("round trip OK")Compression and memory mapping
joblib can load the large NumPy arrays inside a model with memory mapping, using load(path, mmap_mode="r"). The operating system then reads array data from disk on demand. Several worker processes on one machine can share the same pages instead of each holding its own copy. This helps when you serve a large model from multiple processes.
Memory mapping needs the data on disk to be stored as it appears in memory. A compressed file cannot be mapped that way, so joblib ignores mmap_mode for compressed files and emits a warning. If you rely on memory mapping, save the model with compress=0.
The choice is a trade-off between disk space and memory sharing. For a single process that loads the model once, compression costs nothing at prediction time. For many processes on one machine, an uncompressed file with memory mapping can use less memory overall.
Reducing size before compressing
Compression squeezes redundancy out of bytes you already have. If the model is larger than it needs to be, shrinking the model often saves more than any compression setting.
- Limit tree growth. A forest with fewer trees, a
max_depth, or a largermin_samples_leafstores fewer nodes. Check that validation scores stay acceptable. - Remove what you do not need. If you put a large object on the estimator or inside a pipeline step, such as a stored copy of the training data, it is saved with the model. Keep only what prediction requires.
- Prefer a simpler model when it performs as well. A linear model with a small file may match a forest on your data.
Reduce the model first, then compress what remains, and measure after each step.
Common mistakes
- Choosing a level without measuring. The best setting depends on the model type. Run the benchmark on your own model.
- Using the highest level by default. Level 9 and
lzmacost much more save time for a small extra gain on many models. - Ignoring load time. A smaller file that takes twice as long to load can slow every service restart.
- Expecting
mmap_modeto work on a compressed file. It is ignored with a warning. - Saving with
lz4and loading elsewhere. The loading environment needs thelz4package. - Treating compression as a safety measure. It changes size only.
Exercise
You save a random forest with dump(model, "m.joblib", compress=3). A colleague loads it with load("m.joblib", mmap_mode="r") in four worker processes and hopes the workers will share the model's arrays in memory. What happens, and how do you fix it?
Show answer
joblib cannot memory-map a compressed file, so it ignores mmap_mode and warns. Each worker decompresses and holds its own copy of the arrays. To share memory between workers, save the model uncompressed with dump(model, "m.joblib", compress=0) and load it with mmap_mode="r". The cost is a larger file on disk.
Exercise
Your service restarts often, and a profile shows that loading a 400 MB compressed model dominates startup time. The file is stored with ("lzma", 9). Name two changes you could try, and say how you would decide between them.
Show answer
First, switch to a faster-decompressing setting such as zlib level 3, or lz4 if the lz4 package is available everywhere the model is loaded. Second, shrink the model itself, for example with fewer trees or a larger min_samples_leaf, then re-check validation scores. To decide, run the benchmark script on each candidate and compare file size, load time, and validation score. Pick the option that meets your startup-time target with an acceptable score and file size.