Sub topic 9
Recording Versions Next to the Model
This chapter assumes you can fit a scikit-learn estimator, save it with joblib, and load it back. It also assumes you know that a saved file depends on the library versions that wrote it. Here you will learn what to record beside a model file, how to write that record, and how to use it when you load the model later.
Why a model file is not enough
A .joblib or .pkl file stores the fitted state of an object. It also stores references to the classes that define that object, such as sklearn.linear_model._logistic.LogisticRegression. The file does not contain the code of those classes. When you load it, Python imports the classes from whatever scikit-learn is installed and rebuilds the object from the stored attributes.
If the installed version differs from the one that saved the file, several things can happen:
- The load fails with an
ImportErrororAttributeErrorbecause a class or module moved. - The load succeeds but the object lacks an attribute that the newer code expects. The failure appears later, at
predict. - The load succeeds and predictions differ slightly, because an algorithm default or internal computation changed.
The third case is the most dangerous because nothing raises an error. A small text file next to the model lets you detect the mismatch before you trust the output.
scikit-learn also emits an InconsistentVersionWarning when it unpickles an estimator saved by a different version. That warning is useful, but it only appears at load time and only for scikit-learn. It says nothing about NumPy, SciPy, joblib, or Python.
What to record
A useful record has two parts: the environment and the model's identity.
| Item | Why it matters |
|---|---|
| scikit-learn version | Defines the estimator classes and their internal attributes |
| NumPy and SciPy versions | Fitted arrays and sparse matrices are stored in their formats |
| joblib version | The file format of the container |
| Python version | Pickle protocol and class layout can depend on it |
| Save timestamp | Tells you how old the model is |
| Model file name and hash | Detects a file that was swapped or corrupted |
| Feature names and order | The loaded model expects columns in the training order |
| Training data description | Tells you what population the model was fitted on |
You do not need every item for every project. The first four are the minimum for reproducibility, and the hash and feature names are cheap additions that prevent real mistakes.
Writing the metadata file
The Topic Spine example records three versions. The next example extends it with NumPy, SciPy, a timestamp, and a checksum. It fits and saves the model first, so the script runs on its own.
import hashlib
import json
import sys
from datetime import datetime, timezone
import joblib
import numpy as np
import scipy
import sklearn
from joblib import dump
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
iris = load_iris()
X, y = iris.data, iris.target
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
model.fit(X, y)
model_path = "iris_model.joblib"
dump(model, model_path)
def sha256_of(path):
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
meta = {
"model_file": model_path,
"sha256": sha256_of(model_path),
"saved_at": datetime.now(timezone.utc).isoformat(),
"python": sys.version.split()[0],
"scikit_learn": sklearn.__version__,
"numpy": np.__version__,
"scipy": scipy.__version__,
"joblib": joblib.__version__,
"feature_names": list(iris.feature_names),
}
with open("iris_model.meta.json", "w") as f:
json.dump(meta, f, indent=2)
print(json.dumps(meta, indent=2))Some choices in this script are deliberate:
- The hash is computed after
dumpfinishes, so it describes the bytes on disk. - The file is read in 1 MiB chunks. Model files can reach hundreds of megabytes, and chunking keeps memory use flat.
- The timestamp uses UTC, which avoids confusion when the model moves between machines in different time zones.
- The metadata is JSON, not pickle. A reader can open it in any editor, and loading it carries no code execution risk.
The output has this shape. Your values for the hash, time, and versions will differ.
{
"model_file": "iris_model.joblib",
"sha256": "9f2c...",
"saved_at": "2026-11-28T11:30:12.482913+00:00",
"python": "3.12.4",
"scikit_learn": "1.5.2",
"numpy": "2.1.1",
"scipy": "1.14.1",
"joblib": "1.4.2",
"feature_names": [
"sepal length (cm)",
"sepal width (cm)",
"petal length (cm)",
"petal width (cm)"
]
}Reading the metadata before loading
Recording versions has value only if something reads them. The loader below compares the stored record with the current environment and verifies the hash before it unpickles anything. The hash check matters for security as well as for integrity: you detect a modified file before any pickle code runs.
import hashlib
import json
import warnings
import joblib
import sklearn
def sha256_of(path):
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def load_checked(model_path, meta_path, strict=False):
with open(meta_path) as f:
meta = json.load(f)
if sha256_of(model_path) != meta["sha256"]:
raise ValueError("Model file does not match the recorded checksum.")
current = {
"scikit_learn": sklearn.__version__,
"joblib": joblib.__version__,
}
problems = [
f"{name}: saved with {meta[name]}, running {version}"
for name, version in current.items()
if meta[name] != version
]
if problems:
message = "Version mismatch: " + "; ".join(problems)
if strict:
raise RuntimeError(message)
warnings.warn(message)
return joblib.load(model_path), meta
model, meta = load_checked("iris_model.joblib", "iris_model.meta.json", strict=True)
print(model.predict([[5.1, 3.5, 1.4, 0.2]]))The strict flag expresses a policy decision:
- In a notebook, a warning is usually enough. You can decide to continue.
- In a production service, raise an error. A service that quietly runs a mismatched model is harder to debug than one that refuses to start.
Note that the version comparison uses exact string equality. That is conservative. Two patch releases, such as 1.5.1 and 1.5.2, are usually compatible, but scikit-learn only promises compatibility for the same version. Treating any difference as a flag, then deciding by hand, is the safe default.
Checking feature names
The metadata also guards against a column-order mistake. A pipeline fitted on a NumPy array has no column names, and it will accept any four numbers in any order. If the metadata stores the training order, the calling code can assert it.
import pandas as pd
expected = meta["feature_names"]
new_rows = pd.DataFrame(
[[5.1, 3.5, 1.4, 0.2]],
columns=expected,
)
assert list(new_rows.columns) == expected
print(model.predict(new_rows.to_numpy()))If you fit the pipeline on a pandas DataFrame, scikit-learn stores feature_names_in_ on the fitted estimator and checks names at predict time. Recording names in the metadata is still useful, because it lets you inspect a model's contract without loading it.
Recreating the environment
The record also lets someone rebuild a compatible environment. From the JSON above, you can write a pinned requirements file.
import json
with open("iris_model.meta.json") as f:
meta = json.load(f)
pins = [
f"scikit-learn=={meta['scikit_learn']}",
f"numpy=={meta['numpy']}",
f"scipy=={meta['scipy']}",
f"joblib=={meta['joblib']}",
]
with open("requirements-model.txt", "w") as f:
f.write("\n".join(pins) + "\n")
print("\n".join(pins))Install that file in a fresh virtual environment, then run the loader. The Python version cannot be installed by pip, so use it to choose the interpreter when you create the environment.
Common mistakes
- Recording versions from a different environment than the one that saved the model. Run the metadata code in the same process, or at least the same environment, that calls
dump. Readingpip freezefrom another shell can record the wrong versions. - Storing the metadata inside the pickle. If you must read it before loading, it cannot live in the pickled object. Keep it in a separate plain file.
- Updating the model without updating the metadata. Write both in one function, so one cannot change without the other. The checksum will catch a mismatch.
- Trusting the checksum as proof of safety. A hash shows the file is the one you recorded. It does not show that the file was safe in the first place. If an attacker can edit the model file, they can usually edit the metadata too. Protect both with file permissions or a signed storage location.
- Ignoring non-scikit-learn dependencies. A custom transformer or a function inside
FunctionTransformeris stored by reference. The loading environment must be able to import your module, so record your own package version or commit hash too.
Edge cases
- Models that train on many nodes. If training and serving run on different machines, record the training environment, not the serving one. The training environment is what the file depends on.
- Rebuilding after an upgrade. When you upgrade scikit-learn, the safest path is to retrain from the original data and save a new file with a new record. Loading an old file in a new version is an unsupported path, even when it appears to work.
- Version strings with local tags. Some builds report versions like
1.5.2+cpuor a development tag. Compare the strings exactly, and expect to pin to the same build. - Many models in one service. Keep one metadata file per model. A single shared file drifts out of date when only one model is replaced.
Exercise
A teammate sends you fraud_model.joblib and fraud_model.meta.json. The metadata says scikit-learn 1.3.2, and your environment has 1.5.2. List the steps you take before using the model, and say which step must come before the call to joblib.load.
Show answer
First verify the SHA-256 of fraud_model.joblib against the sha256 field in the metadata. This must come before joblib.load, because loading a pickle-based file can execute code. Then compare versions and see the mismatch (1.3.2 against 1.5.2). Either create a new virtual environment pinned to the recorded versions and load the model there, or ask the teammate to retrain with your version. Load the model only after one of these is done, then check its predictions against a few known inputs. Also confirm that you trust the source of the file, since the checksum only shows the file matches the record.
Exercise
Why is the metadata stored as JSON and not inside the pickled object?
Show answer
You need to read the versions before you load the model. Unpickling can fail or run code when versions differ, so the metadata must be readable without it. JSON is plain text, safe to parse, and can be read in any editor or tool.