GyaanStack. Blog

Articles / mlopspython

How to save ML models for production: scikit-learn and PyTorch, done safely

Save scikit-learn and PyTorch models so they load anywhere: full pipelines, pinned versions, skops, ONNX, state_dict, safetensors, hashes and a load-time test.

By Raghunath · · 19 min read

pickle.dump(model, open("model.pkl", "wb")) is how most models leave a notebook. The file then fails in three ways once it reaches a server. The serving box has a different scikit-learn and the predictions shift or the load breaks. The preprocessing lived in notebook cells, so the service feeds raw rupees into a model trained on scaled values. And anyone who can swap that .pkl file can run code on your server the moment it loads.

This post builds a model bundle that avoids all three. It covers scikit-learn (joblib, skops, ONNX) and PyTorch (state_dict, the weights_only default, safetensors), then adds a metadata file with hashes and versions and a loader that refuses a bundle that fails any check. Every script here ran on Python 3.13.12 with scikit-learn 1.9.1, skops 0.16.0, skl2onnx 1.20.0, onnxruntime 1.32.0, torch 2.15.0 and safetensors 0.8.0. The output shown is the real output.

What a production model bundle contains#

A model you can ship is a folder with a version number in its path. One serialized file is not enough.

bundle/churn-model/1.0.0/
  pipeline.skops        fitted preprocessing + model, safe format (sklearn)
  pipeline.onnx         same pipeline for ONNX Runtime (no sklearn needed)
  pipeline.joblib       optional, only if every loader is trusted
  golden_inputs.json    5 fixed input rows
  metadata.json         versions, schema, metrics, golden outputs, sha256 of each file
  requirements.txt      exact pins of the training environment

        save time                                load time
  fit pipeline ──> write files ──> hash      read metadata.json
                                     │             │
                                     v             v
                              metadata.json   1. hashes match?
                                              2. library versions match?
                                              3. only trusted types inside?
                                              4. golden rows give the same output?
                                                   │
                                          all yes  v   any no -> refuse to start
                                              serve requests

The rest of the post fills in each box.

Pickle runs code when it loads#

The Python docs put it in one line: "The pickle module is not secure. Only unpickle data you trust." A pickle stores instructions for rebuilding an object, and those instructions can call any importable function. This file looks like a model and writes to disk when it loads:

import os, pickle

class NotAModel:
    # pickle calls __reduce__ when saving; on load it runs whatever it returns
    def __reduce__(self):
        return (os.system, ("echo 'this ran during pickle.load' > pwned.txt",))

with open("model.pkl", "wb") as f:
    pickle.dump(NotAModel(), f)

obj = pickle.load(open("model.pkl", "rb"))   # the "load the model" step
print("load returned:", obj)
print("pwned.txt exists:", os.path.exists("pwned.txt"))
print(open("pwned.txt").read().strip())
load returned: 0
pwned.txt exists: True
this ran during pickle.load

load returned: 0 is the exit code of the shell command. The caller gets no model back and no error, and the command has already run. Swap echo for a reverse shell and that is the attack. joblib files and PyTorch's old default loader use pickle underneath, so the same applies to them. The scikit-learn persistence guide gives the warning "Loading can execute arbitrary code" for pickle, joblib and cloudpickle alike.

Pickle is fine when you made the file and nobody else could have touched it between save and load. It is not fine for models downloaded from the internet, models uploaded by users, or artifacts that pass through a shared bucket with loose write permissions. For those cases the rest of this post uses formats that cannot run code, plus a hash check.

Save the whole pipeline, not the estimator#

The second failure is preprocessing drift. If the scaler, the encoder and the imputer live in notebook cells, the serving code has to re-implement them, and sooner or later it gets one wrong. Put every transform that touches raw data into one Pipeline and save that object.

The example is a churn classifier on synthetic data with three numeric columns, two categorical ones and 5% missing values in monthly_spend:

import numpy as np, pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

def make_data(n=2000, seed=0):
    rng = np.random.default_rng(seed)
    df = pd.DataFrame({
        "age": rng.integers(18, 70, n).astype(float),
        "monthly_spend": rng.gamma(2.0, 1500.0, n),
        "tenure_months": rng.integers(0, 60, n).astype(float),
        "plan": rng.choice(["basic", "pro", "family"], n, p=[0.5, 0.3, 0.2]),
        "city": rng.choice(["Bangalore", "Pune", "Delhi", "Chennai"], n),
    })
    logit = -1.2 + 0.00025 * df.monthly_spend - 0.04 * df.tenure_months + (df.plan == "basic") * 0.9
    df["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    df.loc[rng.random(n) < 0.05, "monthly_spend"] = np.nan   # real data has holes
    return df

NUM = ["age", "monthly_spend", "tenure_months"]
CAT = ["plan", "city"]

df = make_data()
X, y = df[NUM + CAT], df["churned"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)

pre = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), NUM),
    ("cat", OneHotEncoder(handle_unknown="ignore"), CAT),
])
pipe = Pipeline([("pre", pre), ("clf", LogisticRegression(max_iter=1000))])
pipe.fit(X_tr, y_tr)
print("test accuracy:", round(pipe.score(X_te, y_te), 4))
test accuracy: 0.746

The median used by the imputer, the scaler's means and the encoder's categories are now fitted state inside pipe. Serving code calls pipe.predict_proba(raw_dataframe) and nothing else. handle_unknown="ignore" matters in production: a city the model never saw ("Mysore" in the test below) becomes all zeros instead of an exception.

Three ways to save the scikit-learn pipeline#

The save script writes the same fitted pipeline three ways, stores five golden rows with their predicted probabilities, and records a SHA-256 for every file:

import hashlib, json, platform
from datetime import datetime, timezone
from pathlib import Path
import joblib, numpy as np, sklearn, skops, skops.io as sio
from train import pipe, X_tr, X_te, y_te, NUM, CAT

def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()

out = Path("bundle/churn-model/1.0.0"); out.mkdir(parents=True, exist_ok=True)

# 1. three formats of the same fitted pipeline
joblib.dump(pipe, out / "pipeline.joblib")
sio.dump(pipe, out / "pipeline.skops")

from skl2onnx import to_onnx
from skl2onnx.common.data_types import FloatTensorType, StringTensorType
initial_types = [(c, FloatTensorType([None, 1])) for c in NUM] + \
                [(c, StringTensorType([None, 1])) for c in CAT]
onx = to_onnx(pipe, initial_types=initial_types, target_opset=18,
              options={"zipmap": False})
(out / "pipeline.onnx").write_bytes(onx.SerializeToString())

# 2. golden rows: fixed inputs plus the probabilities this exact model gives
golden = X_te.head(5)
golden.to_json(out / "golden_inputs.json", orient="records")
golden_proba = pipe.predict_proba(golden)[:, 1].round(6).tolist()

# 3. metadata / model card
meta = {
    "name": "churn-model", "version": "1.0.0",
    "created_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
    "python": platform.python_version(),
    "libraries": {"scikit-learn": sklearn.__version__, "numpy": np.__version__,
                  "joblib": joblib.__version__, "skops": skops.__version__},
    "input_schema": {**{c: "float" for c in NUM}, **{c: "string" for c in CAT}},
    "output": "probability of churn (class 1)",
    "train_rows": len(X_tr),
    "metrics": {"test_accuracy": round(pipe.score(X_te, y_te), 4)},
    "golden_proba": golden_proba,
    "files": {p.name: sha256(p) for p in sorted(out.iterdir())
              if p.suffix in {".joblib", ".skops", ".onnx", ".json"} and p.name != "metadata.json"},
}
(out / "metadata.json").write_text(json.dumps(meta, indent=2))
for p in sorted(out.iterdir()):
    print(f"{p.name:22s} {p.stat().st_size:>8,d} bytes")
test accuracy: 0.746
golden_inputs.json          478 bytes
metadata.json               974 bytes
pipeline.joblib           3,994 bytes
pipeline.onnx             1,376 bytes
pipeline.skops          132,239 bytes

The three formats suit different situations.

joblib is pickle with efficient handling of large NumPy arrays. It is the smallest and fastest here, and it has the same code-execution risk. Keep it for internal artifacts that never leave a pipeline you control.

skops (skops.io docs) stores the object as a zip of a JSON schema plus arrays and rebuilds only types it knows. Anything else must be approved by name before it loads. The file is 132 KB because skops 0.16 defaults to ZIP_STORED, which means no compression. Passing compression=zipfile.ZIP_DEFLATED to sio.dump brought the same pipeline down to 8,193 bytes.

ONNX turns the pipeline into a graph of standard operators that ONNX Runtime executes from C++, C#, Java, JavaScript or Python, with no scikit-learn installed. The converter is sklearn-onnx. Each DataFrame column becomes a named input, so float columns get FloatTensorType and string columns get StringTensorType. zipmap: False returns probabilities as a plain array instead of a list of dicts. ONNX does not support every estimator or custom transformer, and float64 numbers become float32, so check its output against the original before you trust it (done below).

The scikit-learn guide offers a simple rule. Use ONNX when you need to serve without Python or the original object. Use skops when you need the Python object and the file might not be trusted. Use joblib or pickle only when you trust the source.

The metadata file is your model card#

{
  "name": "churn-model",
  "version": "1.0.0",
  "created_utc": "2026-11-23T16:10:50+00:00",
  "python": "3.13.12",
  "libraries": {
    "scikit-learn": "1.9.1",
    "numpy": "2.5.5",
    "joblib": "1.6.0",
    "skops": "0.16.0"
  },
  "input_schema": {
    "age": "float",
    "monthly_spend": "float",
    "tenure_months": "float",
    "plan": "string",
    "city": "string"
  },
  "output": "probability of churn (class 1)",
  "train_rows": 1500,
  "metrics": {
    "test_accuracy": 0.746
  },
  "golden_proba": [0.133173, 0.673365, 0.187421, 0.353007, 0.703012],
  "files": {
    "golden_inputs.json": "67bc828cf3ff772ec0ed1f4126391b6540cfad2e16b551421dfc6feaeb290ddc",
    "pipeline.joblib": "55d982c6effb6e708033c3a6443a197ec165f826fda1c04b42838029f6fcb177",
    "pipeline.onnx": "0f15eff601a013121eb76ed69875032315165eca53f0f6c385a83548ff9e0ef3",
    "pipeline.skops": "a4a5d42b4fe250c5869700b1934acd3d41ed8f556f5474d6bbb9cadeb68cc4ab"
  }
}

The scikit-learn guide lists what to keep next to a pickled model: the training data or a reference to it, the Python source that produced the model, the library versions and the cross-validation score. The file above covers versions, schema, metric and hashes. For a real model, add the git commit of the training code and a hash or URI of the training data snapshot. Hugging Face model cards are a good template for the human-readable side: intended use, limits, evaluation data.

Pin the environment next to it. A loose scikit-learn line in requirements.txt will install whatever is newest the day the container builds. This is the relevant slice of uv pip freeze from the training venv:

joblib==1.6.0
numpy==2.5.5
onnxruntime==1.32.0
pandas==3.1.1
scikit-learn==1.9.1
scipy==1.18.1
skops==0.16.0

With a uv project, uv.lock plus uv sync --locked (uv docs) gives the same guarantee for the whole dependency tree. The dockerize an AI agent post shows that lockfile inside a multi-stage Docker build.

The version pin has teeth. When scikit-learn unpickles an estimator saved by a different scikit-learn version, it raises InconsistentVersionWarning, and the guide warns that a model trained with older versions cannot always be loaded in an updated environment. A warning in a log is easy to miss, so the loader below turns it into a hard failure.

A loader that refuses bad bundles#

The loader runs four checks before the service accepts traffic:

import hashlib, json
from pathlib import Path
import numpy as np, pandas as pd, sklearn, skops.io as sio

class BundleError(RuntimeError):
    pass

def sha256(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()

def load_bundle(folder, allowed_types=()):
    folder = Path(folder)
    meta = json.loads((folder / "metadata.json").read_text())

    # 1. integrity: every file must match the hash written at save time
    for name, expected in meta["files"].items():
        if sha256(folder / name) != expected:
            raise BundleError(f"hash mismatch for {name}")

    # 2. environment: refuse a different scikit-learn than the one that trained it
    want = meta["libraries"]["scikit-learn"]
    if sklearn.__version__ != want:
        raise BundleError(f"trained on scikit-learn {want}, running {sklearn.__version__}")

    # 3. safe load: skops lists every type it does not trust by default
    path = folder / "pipeline.skops"
    unknown = sio.get_untrusted_types(file=path)
    extra = [t for t in unknown if t not in allowed_types]
    if extra:
        raise BundleError(f"untrusted types in bundle: {extra}")
    model = sio.load(path, trusted=list(allowed_types))

    # 4. behaviour: the golden rows must give the same probabilities as at save time
    golden = pd.read_json(folder / "golden_inputs.json", orient="records")
    got = model.predict_proba(golden)[:, 1]
    if not np.allclose(got, meta["golden_proba"], atol=1e-6):
        raise BundleError(f"golden mismatch: {got.round(6)} vs {meta['golden_proba']}")
    return model, meta

if __name__ == "__main__":
    folder = "bundle/churn-model/1.0.0"
    print("untrusted types reported:", sio.get_untrusted_types(file=f"{folder}/pipeline.skops"))
    model, meta = load_bundle(folder, allowed_types=("numpy.dtype",))
    print("loaded", meta["name"], meta["version"], "- checks passed")
    row = pd.DataFrame([{"age": 34.0, "monthly_spend": 5200.0, "tenure_months": 3.0,
                         "plan": "basic", "city": "Mysore"}])   # unseen city
    print("p(churn) for new row:", round(float(model.predict_proba(row)[0, 1]), 4))

The first run used load_bundle(folder) with an empty allow-list, and it failed:

BundleError: untrusted types in bundle: ['numpy.dtype']

This plain scikit-learn pipeline contained one type that skops 0.16 does not trust by default. The fix is to read the list, decide that numpy.dtype is harmless, and pass it by name. Do not pass the output of get_untrusted_types straight into trusted, because that approves whatever an attacker put in the file. Since skops 0.10, trusted=True raises an error for that reason. With the allow-list in place:

untrusted types reported: ['numpy.dtype']
loaded churn-model 1.0.0 - checks passed
p(churn) for new row: 0.735

The unseen city went through without an error. Then two more checks: does the ONNX file match scikit-learn, and does a one-byte change get caught?

import json, shutil
import numpy as np, onnxruntime as ort, pandas as pd
from load_verified import load_bundle, BundleError

folder = "bundle/churn-model/1.0.0"
meta = json.load(open(f"{folder}/metadata.json"))
golden = pd.read_json(f"{folder}/golden_inputs.json", orient="records")

# ONNX Runtime: no scikit-learn needed at serving time
sess = ort.InferenceSession(f"{folder}/pipeline.onnx", providers=["CPUExecutionProvider"])
feeds = {}
for inp in sess.get_inputs():
    col = golden[inp.name].to_numpy().reshape(-1, 1)
    feeds[inp.name] = col.astype(np.float32) if "float" in inp.type else col.astype(object)
print("onnx inputs:", [(i.name, i.type) for i in sess.get_inputs()])
print("onnx outputs:", [o.name for o in sess.get_outputs()])
label, proba = sess.run(None, feeds)
diff = np.abs(proba[:, 1] - np.array(meta["golden_proba"])).max()
print("max |onnx - sklearn| on golden rows:", f"{diff:.2e}")

# tamper test: flip one byte in a copy of the bundle
shutil.copytree(folder, "tampered", dirs_exist_ok=True)
p = "tampered/pipeline.skops"
b = bytearray(open(p, "rb").read()); b[-100] ^= 0xFF; open(p, "wb").write(b)
try:
    load_bundle("tampered", allowed_types=("numpy.dtype",))
except BundleError as e:
    print("tampered bundle rejected:", e)
onnx inputs: [('age', 'tensor(float)'), ('monthly_spend', 'tensor(float)'), ('tenure_months', 'tensor(float)'), ('plan', 'tensor(string)'), ('city', 'tensor(string)')]
onnx outputs: ['label', 'probabilities']
max |onnx - sklearn| on golden rows: 4.11e-07
tampered bundle rejected: hash mismatch for pipeline.skops

The ONNX graph agrees with scikit-learn to within 4.11e-07, which is float32 rounding. On a tree ensemble or a model near a decision threshold, check that gap against what your use case can tolerate. A probability of 0.5000003 and 0.4999998 give different labels.

A hash stored next to the file only protects against accidents (a truncated upload, a corrupted disk, the wrong file copied). Someone who can rewrite the bundle can rewrite metadata.json too. Against that threat, keep the expected hash somewhere the attacker cannot write, such as the deploy config or the MLflow model registry entry, and compare against that.

Run the same load_bundle call as a unit test in CI and as the first step of service startup. A service that cannot load its model should crash at boot, where the deploy rolls back. Discovering it on the first user request is worse. The production LLM API with FastAPI post shows where startup hooks and health checks go in a FastAPI service; loading the model there means /health only reports ready after these checks pass.

PyTorch: state_dict, weights_only and safetensors#

PyTorch has its own version of the same problem. torch.save uses pickle. Since PyTorch 2.6, torch.load defaults to weights_only=True, which restricts unpickling to tensors, primitive types, dictionaries and types you add with torch.serialization.add_safe_globals. Older tutorials that save the whole model object now fail to load with the default settings. This script compares three options on a small network:

import torch, torch.nn as nn
from safetensors.torch import save_file, load_file

class ChurnNet(nn.Module):
    def __init__(self, n_in=10, hidden=32):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(n_in, hidden), nn.ReLU(), nn.Linear(hidden, 1))
    def forward(self, x):
        return torch.sigmoid(self.net(x))

torch.manual_seed(0)
model = ChurnNet().eval()
x = torch.randn(4, 10)
ref = model(x)
print("torch", torch.__version__)

# A. whole object: pickles the class reference too
torch.save(model, "full_model.pt")
try:
    torch.load("full_model.pt")              # weights_only=True is the default since 2.6
except Exception as e:
    print("full model, default load ->", type(e).__name__, str(e).splitlines()[0][:90])
m_full = torch.load("full_model.pt", weights_only=False)   # only for files you made yourself
print("full model, weights_only=False -> same output:", torch.allclose(m_full(x), ref))

# B. state_dict: tensors only, loads under the safe default
torch.save(model.state_dict(), "weights.pt")
m2 = ChurnNet(); m2.load_state_dict(torch.load("weights.pt")); m2.eval()
print("state_dict + default load -> same output:", torch.allclose(m2(x), ref))

# C. safetensors: no pickle at all, plus string metadata in the header
save_file(model.state_dict(), "weights.safetensors",
          metadata={"arch": "ChurnNet", "n_in": "10", "hidden": "32"})
m3 = ChurnNet(); m3.load_state_dict(load_file("weights.safetensors")); m3.eval()
print("safetensors -> same output:", torch.allclose(m3(x), ref))

from safetensors import safe_open
with safe_open("weights.safetensors", framework="pt") as f:
    print("header metadata:", f.metadata(), "| keys:", list(f.keys()))

# D. load-time check that catches the classic mistake: wrong architecture
try:
    ChurnNet(hidden=64).load_state_dict(load_file("weights.safetensors"))
except RuntimeError as e:
    print("wrong hidden size ->", str(e).splitlines()[0][:80])
torch 2.15.0
full model, default load -> UnpicklingError Weights only load failed. This file can still be loaded, to do so you have two options, [
full model, weights_only=False -> same output: True
state_dict + default load -> same output: True
safetensors -> same output: True
header metadata: {'hidden': '32', 'n_in': '10', 'arch': 'ChurnNet'} | keys: ['net.0.bias', 'net.0.weight', 'net.2.bias', 'net.2.weight']
wrong hidden size -> Error(s) in loading state_dict for ChurnNet:

The file sizes were 5,307 bytes for the full model, 3,869 for the state_dict and 1,892 for safetensors.

Saving the full model pickles a reference to ChurnNet by module path. Loading it later requires the same class at the same import path, so renaming a file or moving the class breaks old checkpoints. It also needs weights_only=False, which turns code execution back on. The PyTorch saving and loading tutorial recommends the state_dict approach for inference.

A state_dict is an ordered dict of tensors. It loads under the safe default, and the architecture comes from your code, which is versioned in git. Call model.eval() after loading so dropout and batch norm behave as they do at inference.

safetensors stores the raw tensors after a JSON header. Loading cannot run code, and the header holds string metadata, which is a good place for the architecture arguments. For PyTorch inference weights it is the format to pick.

The last line of output is the check every PyTorch loader should keep. load_state_dict with the default strict=True raises an error when key names or shapes do not match, so a checkpoint for a 32-unit network cannot silently load into a 64-unit one. Passing strict=False to make an error go away hides exactly this bug. The golden-row test from the scikit-learn loader applies here too: store four input tensors and their outputs in the bundle, and compare at startup.

Failure modes this setup catches#

Failure What catches it
Serving container installs a newer scikit-learn pinned requirements; version check in load_bundle
Preprocessing re-implemented by hand at serving time single Pipeline saved as one object
Truncated or wrong file copied to the server SHA-256 check against metadata
Malicious model file from an outside source skops or safetensors; allow-list reviewed by a person
ONNX conversion changes predictions golden rows compared with a tolerance
Checkpoint loaded into the wrong architecture load_state_dict(strict=True)
New category value at inference OneHotEncoder(handle_unknown="ignore")
Behaviour silently changes after a library upgrade golden-row test in CI and at startup

Two things this setup does not catch. The golden rows test five points, so a change that only affects rare inputs can slip through; use a larger held-out set with a metric threshold in CI if that matters. And none of this covers data drift after deployment, which is a monitoring problem covered in the auto-retrain on drift post. The MLOps vs LLMOps post covers how that part of the work is split.

Once you retrain, write 1.0.1 or 1.1.0 next to 1.0.0 instead of overwriting it, and register each version in a model registry such as MLflow so the deploy can point at a version and roll back to the previous one.

Sources#

Found this useful? You can buy me a coffee or support with any amount. It pays for hosting and keeps new articles coming.