TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Saving Models: pickle and joblib

Saving Models: pickle and joblib

A trained model lives in the memory of the Python process that trained it. The moment the notebook kernel restarts, it is gone. Before a model can be served, scored in a nightly job, compared with last month's model or rolled back to, it has to become a file: a sequence of bytes that another process, on another machine, maybe months later, turns back into the same model. That step is called serialisation, and in the Python ecosystem the default tools are the standard library's pickle and scikit-learn's companion library joblib.

Both are convenient, and both have sharp edges that cause real production incidents: a model that loads but predicts differently after a library upgrade, a file that cannot be loaded because a helper function was renamed, and a file that runs arbitrary code when it is opened. This lesson shows what is inside such a file, so that these failures stop being surprises.

The round trip

The running example of this course is a credit-risk classifier, "risk-model": eight numeric features of a loan application, a binary label (default or not), and a Pipeline of a StandardScaler and a LogisticRegression. Save it to bytes, load it back, and check that the copy predicts exactly what the original predicts.

python · try it yourself
import pickle
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr)

data = pickle.dumps(model)                 # model -> bytes (pickle.dump(model, f) writes a file)
copy = pickle.loads(data)                  # bytes -> a new, independent object
p1, p2 = model.predict_proba(X_te)[:, 1], copy.predict_proba(X_te)[:, 1]
print(f"pickle size: {len(data)} bytes")
print(f"same object? {copy is model}; identical probabilities? {np.array_equal(p1, p2)}")
print(f"test accuracy (n = {len(y_te)}): original {model.score(X_te, y_te):.3f}, copy {copy.score(X_te, y_te):.3f}")
pickle size: 1353 bytes
same object? False; identical probabilities? True
test accuracy (n = 500): original 0.864, copy 0.864

The whole fitted pipeline is 1353 bytes. The copy is a different object with identical behaviour (accuracy 0.864 on the 500-row test split, a quarter of the data, for both): not "close", bit-for-bit identical probabilities, because the floating-point weights were stored exactly. That is the property you want from a model file. The rest of the lesson is about when it breaks.

What a pickle stores, and what it does not

A pickle is a small program for a stack machine. Loading it executes instructions such as "import the class LogisticRegression from the module sklearn.linear_model._logistic, create an empty instance, and set its attributes to this dictionary". So a pickle stores:

  • the import path of every class (module name plus class name), as text;
  • the state of every object: its __dict__ (for a fitted estimator the hyperparameters, coef_, intercept_, classes_, …), with NumPy arrays as raw bytes;

and it does not store the code of the class. The code comes from whatever library version is installed where the file is loaded.

python · try it yourself
import pickle, pickletools
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression

X, y = make_classification(n_samples=200, n_features=4, random_state=0)
clf = LogisticRegression().fit(X, y)
data = pickle.dumps(clf, protocol=2)       # protocol 2 names each class in one GLOBAL opcode

imports = [arg.replace(" ", ".") for op, arg, pos in pickletools.genops(data) if op.name == "GLOBAL"]
print("classes the loader must import:")
for name in dict.fromkeys(imports):
    print("  ", name)
print("fitted attributes stored:", sorted(k for k in clf.__dict__ if k.endswith("_")))
print("contains source code?", b"def predict" in data)
classes the loader must import:
   sklearn.linear_model._logistic.LogisticRegression
   numpy._core.multiarray._reconstruct
   numpy.ndarray
   _codecs.encode
   numpy.dtype
fitted attributes stored: ['classes_', 'coef_', 'intercept_', 'n_features_in_', 'n_iter_']
contains source code? False

The file names the estimator class and the NumPy functions that rebuild its arrays (_codecs.encode turns the stored raw array bytes back into a bytes object); the fitted attributes coef_, intercept_, classes_ are just values. No line of predict is in it. Two consequences follow directly.

Your own classes must be importable at load time, under the same name. If the pipeline contains a custom transformer, say riskfeatures.AgeBucketer, the file names that path, and loading fails when the class is renamed or the package is missing (the example builds a module in memory to play the package):

python · try it yourself
import pickle, sys, types

# A custom preprocessing step, living in the training project's package "riskfeatures"
riskfeatures = types.ModuleType("riskfeatures")
sys.modules["riskfeatures"] = riskfeatures
class AgeBucketer:
    def __init__(self, edges):
        self.edges = edges
AgeBucketer.__module__ = "riskfeatures"
riskfeatures.AgeBucketer = AgeBucketer

data = pickle.dumps(AgeBucketer([25, 40, 60]))
print("stored path:", b"riskfeatures" in data and b"AgeBucketer" in data)

del riskfeatures.AgeBucketer               # a later release renamed the class ...
riskfeatures.AgeBinner = AgeBucketer
try:
    pickle.loads(data)
except AttributeError as e:
    print("AttributeError:", e)

del sys.modules["riskfeatures"]            # ... or the serving image lacks the package
try:
    pickle.loads(data)
except ModuleNotFoundError as e:
    print("ModuleNotFoundError:", e)
stored path: True
AttributeError: Can't get attribute 'AgeBucketer' on <module 'riskfeatures'>
ModuleNotFoundError: No module named 'riskfeatures'

The fix is organisational, not technical: put custom code in a versioned package (riskmodel.features.AgeBucketer), install the same package version in training and serving, and never pickle classes defined in a notebook.

The library version at load time decides the behaviour. scikit-learn writes its version into every estimator's state as _sklearn_version and warns when a file was written by a different version. The next example fakes an old file by editing that field in the state, which is exactly what the loader sees when a model trained with an older release is opened.

python · try it yourself
import pickle, warnings
import sklearn
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression

X, y = make_classification(n_samples=200, n_features=4, random_state=0)
state = LogisticRegression().fit(X, y).__getstate__()
print("version recorded in the state:", state["_sklearn_version"], "| installed:", sklearn.__version__)

state["_sklearn_version"] = "1.3.2"         # pretend the file was written by an older release
old = LogisticRegression.__new__(LogisticRegression)
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    old.__setstate__(state)                # what pickle.loads calls for each estimator
w = caught[0]
print(type(w.message).__name__ + ":", str(w.message).split(". ")[0] + ".")
version recorded in the state: 1.7.0 | installed: 1.7.0
InconsistentVersionWarning: Trying to unpickle estimator LogisticRegression from version 1.3.2 when using version 1.7.0.

The warning is not cosmetic. Between releases, internal attributes get renamed, defaults change and numerical routines are rewritten. Sometimes the old file fails loudly; sometimes it loads and predicts slightly differently, which is worse. The rule is to pin versions: record the exact versions of Python, NumPy, SciPy, scikit-learn and your own package next to the model (the next lessons build a metadata file and a signature for this), install exactly those in the serving image, and treat a library upgrade as a retraining or at least a re-validation event. Pickles are fine for "the same environment, later"; they are a poor format for long-term archives. For that, retrain from versioned data and code (reproducibility) or export to a format defined by a specification, such as ONNX.

Loading a pickle runs code

Because loading executes instructions, and one of those instructions is "call this function with these arguments", a pickle can run any code the author chose. An object controls how it is pickled through __reduce__, which returns a callable and its arguments; on load, pickle calls it. Here the callable is a harmless print, but it could just as well be os.system:

python · try it yourself
import pickle

class NotAModel:
    def __reduce__(self):
        # on load, pickle will call print("...") -- an attacker would return os.system and a command
        return (print, ("this line was executed by pickle.loads",))

payload = pickle.dumps(NotAModel())
print(f"payload is {len(payload)} bytes; loading it now:")
result = pickle.loads(payload)
print("the 'model' we got back:", result)
payload is 78 bytes; loading it now:
this line was executed by pickle.loads
the 'model' we got back: None

Nothing in the file looks like a model, and nothing warned. So: only load pickles you or your pipeline produced, from storage only your pipeline can write to, and verify the file's hash before loading (below). A model downloaded from a public hub, a file uploaded by a user, or an artifact bucket that many people can write to is untrusted input. The security lesson shows real attacks (malicious model files, scanners and their limits) and the safer formats (weights-only formats such as safetensors, ONNX, and restricted loaders).

joblib: the same thing, better at arrays and compression

joblib.dump and joblib.load use pickle underneath, so everything above applies, including code execution on load. Two practical differences: joblib writes large NumPy arrays efficiently (and can memory-map them on load with mmap_mode="r"), and it compresses with one argument. Compression matters for models whose state is large, such as tree ensembles, which store every split of every tree.

python · try it yourself
import io, pickle, joblib
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier

X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
forest = RandomForestClassifier(n_estimators=50, random_state=0).fit(X, y)

def joblib_bytes(obj, compress):
    buf = io.BytesIO()
    joblib.dump(obj, buf, compress=compress)
    return buf.getvalue()

print(f"pickle             {len(pickle.dumps(forest)) / 1e6:6.2f} MB")
for level in (0, 3, 9):
    print(f"joblib compress={level}  {len(joblib_bytes(forest, level)) / 1e6:6.2f} MB")
again = joblib.load(io.BytesIO(joblib_bytes(forest, 3)))
print("round trip identical predictions:", bool((again.predict(X) == forest.predict(X)).all()))
pickle               1.13 MB
joblib compress=0    1.14 MB
joblib compress=3    0.27 MB
joblib compress=9    0.24 MB
round trip identical predictions: True

The forest of 50 trees takes 1.13 MB as a plain pickle and 0.27 MB at level 3; level 9 squeezes out only another 0.03 MB. Compression is lossless, so predictions are unchanged; the cost is CPU time on save and load. Level 3 is a common default: most of the gain, little of the time. In a service, the model is loaded once at start-up (FastAPI for production), so load time adds to the cold start, not to each request.

A hash makes the file checkable

A model file should be content-addressed: record its SHA-256 hash when you save it, and check the hash before you load it. The hash detects a truncated upload, a file overwritten by another run, and a tampered artifact, and it gives every model version an identity that does not depend on a file name.

python · try it yourself
import hashlib, io, joblib
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression

X, y = make_classification(n_samples=500, n_features=8, random_state=0)
buf = io.BytesIO()
joblib.dump(LogisticRegression().fit(X, y), buf)
blob = buf.getvalue()
recorded = hashlib.sha256(blob).hexdigest()           # stored next to the model, e.g. in metadata.json

def safe_load(blob, expected):
    actual = hashlib.sha256(blob).hexdigest()
    if actual != expected:
        raise ValueError(f"hash mismatch: expected {expected[:12]}..., got {actual[:12]}...")
    return joblib.load(io.BytesIO(blob))

print("intact file loads:", type(safe_load(blob, recorded)).__name__)
tampered = blob[:-1] + bytes([blob[-1] ^ 1])          # flip one bit in the last byte
try:
    safe_load(tampered, recorded)
except ValueError as e:
    print("tampered file refused:", str(e).split(":")[0])
intact file loads: LogisticRegression
tampered file refused: hash mismatch

The hash only helps if the expected value comes from somewhere the attacker cannot also change: a registry entry, a signed manifest, a deployment config in Git. The same idea secures container images and dependencies (hash pinning).

Pitfalls

  • Pickling the estimator without its preprocessing. Save the whole Pipeline, not only the final classifier; a scaler fitted on training data is part of the model.
  • Classes from a notebook or a renamed module. The file stores import paths; keep custom code in an installed, versioned package.
  • Loading with different library versions. Pin them, store them with the model, and heed InconsistentVersionWarning.
  • Loading files from untrusted sources. pickle.load and joblib.load run code. Verify a hash from a trusted record first, or use a format without code.
  • Pickle as an archive. Years later, the library versions that can read it may not install any more. Keep the training code, data version and metrics so the model can be rebuilt, or export to a specified format.
  • Lambdas and local functions. The standard pickle cannot serialise them (FunctionTransformer(lambda x: ...) fails to save); use named functions in a module.

Practice

  1. A colleague trained a pipeline in a notebook that includes a FunctionTransformer(clip_outliers), where clip_outliers is defined in the notebook. The service cannot load the file. Why, and what is the fix?
  2. Your service runs scikit-learn 1.7.0. A model file from last year logs an InconsistentVersionWarning mentioning 1.3.2 and its accuracy on a fresh holdout dropped slightly. What do you do?
  3. Why does checking the SHA-256 of a model file not protect you if the expected hash is stored in the same bucket as the file?
Answers
  1. The pickle stores the function's import path, __main__.clip_outliers, not its code. The serving process has no such function in its __main__. Move clip_outliers into a package that both training and serving install (same version), retrain, and save again.
  2. Do not keep serving an unvalidated mix. Either rebuild the serving image with the versions the model was trained with (recorded in its metadata), or retrain the model with the current versions from the versioned data and code, validate it on the holdout, and release it as a new version.
  3. Anyone who can replace the file can also replace the hash next to it. The expected hash must come from a separate, more trusted place (registry, signed manifest, reviewed config).

Test yourself

What does a pickle of a fitted scikit-learn model contain?

  1. The source code of the estimator class
  2. The import path of each class and the state of each object (hyperparameters, fitted arrays)
  3. A compiled binary of the model
  4. Only the predictions on the training data

Why is pickle.loads on a file from an unknown source dangerous?

  1. It can be slow
  2. It may use a lot of memory
  3. The file can make the loader call any function with any arguments, so it can run arbitrary code
  4. It deletes the file after loading

What does joblib.dump(model, f, compress=3) change compared with no compression?

  1. The predictions become approximate
  2. The file is smaller and saving/loading takes more CPU; predictions are identical
  3. It removes the code-execution risk
  4. It makes the file readable by other languages

Which practice best prevents a model from silently behaving differently after deployment?

  1. Saving with a higher pickle protocol
  2. Recording and pinning the exact library versions used in training and installing them in the serving environment
  3. Renaming the file with the date
  4. Compressing the file