Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 2

What Exactly Are You Shipping? Model Artifacts and Formats

What a model artifact must contain to be served safely: preprocessing and model saved as one scikit-learn pipeline, metadata with versions and reference predictions, why pickle and joblib files can run code when loaded, how skops refuses unknown types, how safetensors stores weights without code, and how to export to ONNX and prove that ONNX Runtime gives the same predictions.

Contentsand lesson path

What you will learn

  • Serialize a model together with its preprocessing and metadata in a portable, safe format (for example skops or joblib with pinned versions, safetensors, ONNX) and verify that predictions match the training environment.

Prerequisites: Containerization

01. Why it matters

Training ends with a model in the memory of one Python process. Serving starts in a different process, often on a different machine, months later. Everything that crosses that gap must be written to files, and those files are the model artifact: what you actually ship. If the artifact is incomplete, the server has to rebuild the missing parts, and a rebuilt part that differs even slightly gives wrong predictions without any error. If the format is unsafe, loading the file can run code that someone hid in it.

This lesson builds a small churn model and saves it in four ways, so you can see what each format stores and what it costs. You need Python 3.12 with scikit-learn, skops, skl2onnx, ONNX Runtime and safetensors; every script runs in a few seconds.

Terminal
mkdir -p artifacts && cd artifacts
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "scikit-learn==1.9.*" "pandas==3.1.*" "skops==0.16.*" \
    "skl2onnx==1.20.*" "onnxruntime==1.32.*" "safetensors==0.8.*"

02. Preprocessing, model and metadata travel together

A model rarely sees raw data. A scaler subtracts the training mean and divides by the training standard deviation; an encoder turns plan into three columns of zeros and ones in a fixed order. Those means, standard deviations and category lists are learnt from the training data, exactly like the model weights. If you save only the classifier and rebuild the scaler at serving time, the rebuilt one will learn different numbers from different data, and every prediction shifts. The fix is to make the preprocessing part of the model: a scikit-learn Pipeline holds both, fit trains both, and saving the pipeline saves both.

An artifact also needs metadata, a small file that answers the questions you will have later: which columns and types it expects, which library versions produced it, a hash of the file, and a set of reference predictions computed at training time. The reference predictions are the most useful part. Any environment that loads the artifact can score the same rows and compare, which turns "it seems to work" into a check.

Python · data.py
"""Seeded churn data: three numeric and two categorical columns."""
import numpy as np
import pandas as pd

NUMERIC = ["tenure_months", "monthly_fee", "support_calls"]
CATEGORICAL = ["plan", "channel"]


def make(n=4000, seed=0):
    rng = np.random.default_rng(seed)
    df = pd.DataFrame({
        "tenure_months": rng.integers(0, 72, n),
        "monthly_fee": rng.normal(45, 15, n).clip(5, 120).round(2),
        "support_calls": rng.poisson(1.5, n),
        "plan": rng.choice(["basic", "standard", "premium"], n, p=[0.5, 0.3, 0.2]),
        "channel": rng.choice(["online", "store"], n, p=[0.7, 0.3]),
    })
    logit = (-1.0 - 0.04 * df.tenure_months + 0.03 * (df.monthly_fee - 45)
             + 0.45 * df.support_calls + 0.6 * (df.plan == "basic"))
    df["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    return df
Python · train.py
"""Train preprocessing + model as ONE pipeline, save it with its metadata."""
import hashlib
import json
import platform

import joblib
import numpy as np
import sklearn
import skops.io as sio
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

from data import CATEGORICAL, NUMERIC, make

df = make()
train, check = df.iloc[:3000], df.iloc[3000:]
model = Pipeline([
    ("prep", ColumnTransformer([
        ("num", StandardScaler(), NUMERIC),
        ("cat", OneHotEncoder(handle_unknown="ignore"), CATEGORICAL),
    ])),
    ("clf", LogisticRegression(max_iter=1000)),
])
model.fit(train[NUMERIC + CATEGORICAL], train["churned"])

joblib.dump(model, "model.joblib")        # pickle-based: fast, but can run code on load
sio.dump(model, "model.skops")            # skops: loads only types you allow

# Reference predictions: the serving side must reproduce these exactly.
X_check = check[NUMERIC + CATEGORICAL]
proba = model.predict_proba(X_check)[:, 1]
np.save("reference_proba.npy", proba)
X_check.to_csv("reference_rows.csv", index=False)

metadata = {
    "features": {c: str(df[c].dtype) for c in NUMERIC + CATEGORICAL},
    "versions": {"python": platform.python_version(),
                 "scikit-learn": sklearn.__version__, "numpy": np.__version__},
    "sha256": {f: hashlib.sha256(open(f, "rb").read()).hexdigest()[:16]
               for f in ["model.joblib", "model.skops"]},
    "check_rows": len(X_check),
    "check_mean_proba": round(float(proba.mean()), 6),
}
json.dump(metadata, open("metadata.json", "w"), indent=2)
print(json.dumps({k: metadata[k] for k in ["features", "versions"]}, indent=2))
Terminal
python train.py
Expected output
{
  "features": {
    "tenure_months": "int64",
    "monthly_fee": "float64",
    "support_calls": "int64",
    "plan": "str",
    "channel": "str"
  },
  "versions": {
    "python": "3.12.13",
    "scikit-learn": "1.9.1",
    "numpy": "2.5.5"
  }
}

The versions matter because a pickled scikit-learn object is only guaranteed to load correctly with the same scikit-learn version that saved it. Loading it with another version raises an InconsistentVersionWarning and may change results, so the serving environment pins the versions recorded here. Your Python patch version may differ from the one shown; the scikit-learn and NumPy lines should match the pins in the setup.

03. Pickle runs code; skops asks first

joblib.dump uses Python's pickle format. A pickle is not just data: it is a small program that tells Python how to rebuild objects, and it may call any importable function while doing so. That is what makes it convenient, and also why the Python documentation warns never to unpickle data from an untrusted source. A model file downloaded from a shared drive, a bucket or a model hub is exactly such a source unless you control where it came from.

skops is a format for scikit-learn models that stores objects as data and rebuilds only types on an allow-list. Its loader first reports any type outside the default list, and refuses to load until you pass the ones you have reviewed. The script shows both behaviours. The Surprise class is harmless here: it prints a line. A malicious file would call something like os.system instead.

Python · features.py
def per_year(monthly):
    """Turn a monthly value into a yearly one (stands in for your own feature code)."""
    return monthly * 12
Python · load_safely.py
"""Why a pickle can run code, and how skops asks before it loads anything."""
import pickle

import skops.io as sio
from sklearn.preprocessing import FunctionTransformer

import features


class Surprise:
    def __reduce__(self):               # pickle calls this to learn how to rebuild it
        return (print, ("this ran while the file was loading",))


print("loading a pickle ...")
pickle.loads(pickle.dumps(Surprise()))  # the call stored in the bytes runs here

print("untrusted types in model.skops:", sio.get_untrusted_types(file="model.skops"))
model = sio.load("model.skops")         # only scikit-learn and NumPy types inside
print("loaded:", type(model).__name__, "with steps", list(model.named_steps))

# A file that refers to your own code is not trusted until you say so.
sio.dump(FunctionTransformer(features.per_year), "custom.skops")
found = sio.get_untrusted_types(file="custom.skops")
print("untrusted types in custom.skops:", found)
try:
    sio.load("custom.skops")
except Exception as error:
    print("refused:", type(error).__name__)
step = sio.load("custom.skops", trusted=found)   # after you have reviewed the list
print("loaded after review:", step.func.__name__)
Terminal
python load_safely.py
Expected output
loading a pickle ...
this ran while the file was loading
untrusted types in model.skops: []
loaded: Pipeline with steps ['prep', 'clf']
untrusted types in custom.skops: ['features.per_year']
refused: UntrustedTypesFoundException
loaded after review: per_year

The pickle printed its line during pickle.loads, before your code could inspect anything. The skops file of the pipeline holds only scikit-learn and NumPy types, so it loads directly. The file with a custom function is refused until you name features.per_year as trusted, and that function must be importable on the server, so your own feature code ships as a package next to the artifact. skops reduces the risk; it does not make an unknown file safe, because any type you trust can still be misused. Keep artifacts in storage you control and check their hashes.

For neural networks the common safe format is safetensors. It stores named arrays (tensors) after a JSON header, and nothing else, so loading cannot execute code. Most models on the Hugging Face Hub are distributed this way. When a PyTorch checkpoint is still a pickle, torch.load(..., weights_only=True), the default since PyTorch 2.6, restricts what it may rebuild.

Python · weights_only.py
"""safetensors stores named arrays and a JSON header: no code, nothing to execute."""
import json
import struct

import numpy as np
from safetensors.numpy import load_file, save_file

rng = np.random.default_rng(0)
weights = {"layer1.weight": rng.normal(size=(16, 5)).astype(np.float32),
           "layer1.bias": np.zeros(16, dtype=np.float32)}
save_file(weights, "tiny.safetensors", metadata={"trained_with": "numpy 2.5"})

with open("tiny.safetensors", "rb") as f:
    header_size = struct.unpack("<Q", f.read(8))[0]   # first 8 bytes: header length
    header = json.loads(f.read(header_size))
for name, info in header.items():
    print(name, info)
loaded = load_file("tiny.safetensors")
print("round trip equal:", all(np.array_equal(weights[k], loaded[k]) for k in weights))
Terminal
python weights_only.py
Expected output
__metadata__ {'trained_with': 'numpy 2.5'}
layer1.bias {'dtype': 'F32', 'shape': [16], 'data_offsets': [0, 64]}
layer1.weight {'dtype': 'F32', 'shape': [16, 5], 'data_offsets': [64, 384]}
round trip equal: True

04. ONNX: one graph for many runtimes

ONNX (Open Neural Network Exchange) describes a model as a graph of standard operators, such as matrix multiply, scaling and one-hot encoding, with named inputs and outputs. Any ONNX runtime can execute that graph: ONNX Runtime on servers, browsers and phones, and others. You no longer need Python or scikit-learn at serving time, and the runtime is often faster for small requests. The converter for scikit-learn is skl2onnx. It needs to know the type and shape of each input; here each column becomes its own input of shape (batch, 1).

A conversion is a translation, and translations can be wrong: an operator may be unsupported, a default may differ, or numbers may be computed in a different precision. So the script does not stop when the export succeeds. It runs the ONNX model on the 1,000 reference rows that train.py saved and compares its probabilities with the ones scikit-learn produced at training time.

Python · export_onnx.py
"""Export the whole pipeline to ONNX, then check it against scikit-learn."""
import numpy as np
import onnxruntime as ort
import pandas as pd
import skops.io as sio
from skl2onnx import to_onnx
from skl2onnx.common.data_types import (FloatTensorType, Int64TensorType,
                                        StringTensorType)

model = sio.load("model.skops")
rows = pd.read_csv("reference_rows.csv")
expected = np.load("reference_proba.npy")       # saved by train.py

# One named input per column, each of shape (batch, 1).
types = [("tenure_months", Int64TensorType([None, 1])),
         ("monthly_fee", FloatTensorType([None, 1])),
         ("support_calls", Int64TensorType([None, 1])),
         ("plan", StringTensorType([None, 1])),
         ("channel", StringTensorType([None, 1]))]
onx = to_onnx(model, initial_types=types, options={"zipmap": False},
              target_opset=18)
open("model.onnx", "wb").write(onx.SerializeToString())

session = ort.InferenceSession("model.onnx", providers=["CPUExecutionProvider"])
feeds = {name: rows[[name]].to_numpy() for name, _ in types}
feeds["monthly_fee"] = feeds["monthly_fee"].astype(np.float32)
feeds["plan"] = feeds["plan"].astype(object)
feeds["channel"] = feeds["channel"].astype(object)
labels, proba = session.run(None, feeds)

print(f"rows compared: {len(rows)}")
print("within 1e-5:", bool(np.allclose(proba[:, 1], expected, atol=1e-5)))
print("same labels:", bool((labels == (expected >= 0.5)).all()))
Terminal
python export_onnx.py
Expected output
rows compared: 1000
within 1e-5: True
same labels: True

The probabilities agree within 1e-5 and every label is the same. They are not bit-for-bit identical: the ONNX graph computes in 32-bit floats, scikit-learn in 64-bit, so tiny differences are expected. The tolerance you accept should be decided in advance and small enough that no decision near the 0.5 threshold could flip. Comparing on many rows, one by one, matters: two models can have the same accuracy while disagreeing on individual customers.

Which format should you ship? A common choice for scikit-learn models is skops for the Python service, with pinned versions, plus ONNX when another runtime or language must serve the model. Neural networks ship as safetensors weights with their code and config, or as ONNX. Whatever you choose, ship the reference rows and predictions with the artifact, and make "load it and reproduce the reference predictions" the first test of every deployment.

05. Check your understanding

Practice check · 3 questions

Model artifacts

Use the scripts and outputs of this lesson.

Q1. `metadata.json` records scikit-learn 1.9.1. A teammate loads `model.joblib` on a server with an older scikit-learn release. What should you expect?
Q2. For `custom.skops`, `get_untrusted_types` lists `features.per_year`. What is the right next step before you load the file in production?
Q3. In `export_onnx.py`, ONNX Runtime and scikit-learn agree within 1e-5 but are not exactly equal. What is the most likely cause?
Practice only: not graded, not saved, not evidence.

06. Apply it

For your project, take the model from an earlier project and package it properly. Put all preprocessing into one pipeline with the model, save it with skops, and write a metadata.json with the expected columns and types, pinned library versions, file hashes and 1,000 reference rows with their predictions. Export it to ONNX as well and write the parity check as a test that fails if any probability differs by more than your chosen tolerance. You will load this artifact in the API of the next lab.

07. Review prompt

Without looking back, answer in your own words:

  1. Why must preprocessing be saved together with the model, and how does a scikit-learn pipeline do that?
  2. What belongs in the metadata of an artifact, and why are reference predictions the most useful part?
  3. Why can loading a pickle run code, and what does skops do differently?
  4. What does safetensors store, and why is that safer for neural network weights?
  5. How do you check that an ONNX export behaves like the original model, and why is a tolerance needed?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check