Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 08 · 60 minutes

Load a model file safely

After this lesson you can
  • Show that a pickle file runs code while it loads, and read what is in one without loading it
  • Store a model in formats that hold numbers only, and prove that it predicts the same
  • Write a loader that refuses a wrong hash, a wrong format, unexpected content and a file that is too large
Lab files of this lesson (13)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A colleague sends Northgate Parcels a model file with the words "load it, it works". Your lead asks: "What happens on our server when someone loads it, and how do we accept a model file without trusting the sender?" You show what a model file can do when it is loaded, and you build a loader that opens only numbers.

Recall

Lesson 7: what did the watermark prove, and what did it not prove?

It proves the copy of a file or of weights, since only the owner's model answers the secret inputs. It does not prove theft through queries.

Lesson 1: which stage of the model's life does a booby-trapped file touch?

The step between training and service, when the file moves to the place that uses it.

The idea

Python saves objects in the pickle format. "How AI works" (lesson 12) saves a model with joblib, which uses it. A pickle is not a table of numbers: it is a list of steps that Python carries out. A step may be "call this function with these arguments", and the function can be any that Python can reach. So loading a pickle can run code of the author's choice, with all your rights. The Python documentation warns against loading a pickle that you do not trust.

A safe format holds data only. For a linear model that is three arrays: the class names, the weights and the intercepts. A loader for it does arithmetic, never code. The loader of this lesson opens three such formats: JSON, .npz (the file of arrays of NumPy) and safetensors, a format for tensors (arrays of numbers) that is widely used for the weights of neural networks (lesson 9 takes it apart). Three layers make a file acceptable.

What a safe loader demands
Format.json, .npz or .safetensors, never a pickleHashthe file is the one that was announcedContentexactly three arrays of finite numbersFormat.json, .npz or .safetensors, never a pickleHashthe file is the one that was announcedContentexactly three arrays of finite numbers

A hash (SHA-256) is a fingerprint of the bytes of a file: change one byte and it changes completely. It proves that the file is the one whose hash you got from a place that you trust. A signature adds who made it (Field notes).

Worked example

1. Make a pickle that runs a function

The next script writes a pickle whose steps say "call harmless()", a function that only prints one line. __reduce__ is the method that tells pickle how to rebuild an object. pickle.dumps makes the bytes (protocol=4 fixes the format, so that every Python from 3.12 writes the same bytes) and pickle.loads reads them back.

pickledemo.py

"""pickledemo.py: a pickle file that runs a function while it is loaded. The function only prints a line."""
import pickle
from pathlib import Path


def harmless():
    print("this line was printed by code inside the file, during pickle.load")
    return "a model"


class Prank:
    def __reduce__(self):
        """Tell pickle how to rebuild this object: call harmless() with no arguments."""
        return (harmless, ())


Path("prank.pkl").write_bytes(pickle.dumps(Prank(), protocol=4))
print("file written, nothing loaded yet")
loaded = pickle.loads(Path("prank.pkl").read_bytes())
print("loaded:", loaded)
python3 pickledemo.py
file written, nothing loaded yet
this line was printed by code inside the file, during pickle.load
loaded: a model

The code in the file printed that line during loads, before your program touched the result.

2. Read a pickle without loading it

python3 -m pickletools file prints the steps of a pickle and runs none of them.

python3 -m pickletools prank.pkl
    0: \x80 PROTO      4
    2: \x95 FRAME      28
   11: \x8c SHORT_BINUNICODE '__main__'
   21: \x94 MEMOIZE    (as 0)
   22: \x8c SHORT_BINUNICODE 'harmless'
   32: \x94 MEMOIZE    (as 1)
   33: \x93 STACK_GLOBAL
   34: \x94 MEMOIZE    (as 2)
   35: )    EMPTY_TUPLE
   36: R    REDUCE
   37: \x94 MEMOIZE    (as 3)
   38: .    STOP
highest protocol among opcodes = 4

One line of that list, taken apart:

One step of a pickle
22:byte offset in the file\x8copcode byteSHORT_BINUNICODEopcode: push a short string'harmless'its argument22:byte offset in the file\x8copcode byteSHORT_BINUNICODEopcode: push a short string'harmless'its argument

STACK_GLOBAL takes a module name and a function name, here __main__ and harmless. REDUCE calls it. A function that a model has no reason to use (os, subprocess, builtins) is a reason to refuse the file. Do not load pickles from other people.

3. Write the safe format and the loader

New words in the code of safeload.py:

  • class Name: defines a new kind of object. __init__ runs when you make one, and self is the object itself, so self.coef_ = coef keeps a value inside it. a, b = x, y sets two names in one line.
  • class Refused(Exception) makes a new kind of error that the loader raises when it says no. raise Refused(...) from None hides the earlier error, so the caller sees only Refused.
  • hashlib.sha256 makes the fingerprint, and hmac.compare_digest compares two fingerprints in a time that does not depend on where they differ.
  • np.load(path, allow_pickle=False) opens an .npz file and refuses any array that needs a pickle to rebuild. An .npz file is a zip file of arrays, and zipfile.ZipFile(path).infolist() lists its members with the size that each has after unpacking. A compressed file can be small and unpack to a huge array, so the loader adds up those sizes before np.load reads anything.
  • load_file(path) from safetensors.numpy opens a .safetensors file. SafetensorError is its error.
  • LinearModel holds the three arrays and has the methods that the rest of the course calls (predict, predict_proba, score), so it can stand in for the scikit-learn model. @ is the matrix product, and np.exp turns scores into probabilities that add up to 1. all(test for a in items) is true when the test holds for every item.
  • RecursionError (JSON nested too deep) and MemoryError (an array header that claims a huge shape) are errors that a lying file can cause. The loader turns them into Refused too.
  • {**d, "k": v} makes a new dictionary from d with one item added or changed.
  • np.savez saves several arrays in one .npz file, and np.savez_compressed also shrinks them.
  • convert_pickle loads a pickle: use it only on a file that you made yourself.

load_model(path, sha256) raises Refused unless all of these hold, in this order: the suffix is .json, .npz or .safetensors; the file is under 10 MB (for .npz, also after unpacking); its SHA-256 is the one that the caller gives; it reads as numbers only; its names are exactly classes, coef and intercept; the arrays are finite numbers of the right shapes. Save the whole file as safeload.py. Its last part is the test run of step 4.

safeload.py

"""safeload.py: a model format that holds numbers only, and a loader that refuses everything else."""
import hashlib
import hmac
import json
import zipfile
from pathlib import Path

import numpy as np
from safetensors import SafetensorError
from safetensors.numpy import load_file

MAX_BYTES = 10_000_000          # a model of this kind is far smaller: refuse anything bigger, packed or unpacked


class Refused(Exception):
    """The loader will not open this file."""


class LinearModel:
    """A linear classifier made of three arrays. It has the methods of the scikit-learn model that it replaces."""

    def __init__(self, classes, coef, intercept):
        self.classes_, self.coef_, self.intercept_ = classes, coef, intercept

    def predict_proba(self, X):
        z = X @ self.coef_.T + self.intercept_
        e = np.exp(z - z.max(axis=1, keepdims=True))
        return e / e.sum(axis=1, keepdims=True)

    def predict(self, X):
        return self.classes_[(X @ self.coef_.T + self.intercept_).argmax(axis=1)]

    def score(self, X, y):
        return (self.predict(X) == y).mean()


def export_json(model, path):
    """Write a fitted scikit-learn logistic regression as JSON: lists of numbers, nothing else."""
    data = {"classes": model.classes_.tolist(), "coef": model.coef_.tolist(), "intercept": model.intercept_.tolist()}
    Path(path).write_text(json.dumps(data))


def export_npz(model, path):
    np.savez(path, classes=model.classes_, coef=model.coef_, intercept=model.intercept_)


def convert_pickle(source, target):
    """Turn a pickled logistic regression into JSON. This LOADS the pickle: use it only on a file that you made."""
    import joblib
    export_json(joblib.load(source), target)


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


def load_model(path, sha256):
    """Open a model file, or raise Refused. The caller must supply the expected hash from a trusted place."""
    path = Path(path)
    if path.suffix not in (".json", ".npz", ".safetensors"):
        raise Refused(f"format {path.suffix or 'none'} is not allowed")
    if path.stat().st_size > MAX_BYTES:
        raise Refused("file is too large")
    if not isinstance(sha256, str) or not hmac.compare_digest(sha256_of(path).encode(), sha256.encode()):
        raise Refused("hash does not match")
    try:
        if path.suffix == ".json":
            data = json.loads(path.read_text())
        elif path.suffix == ".npz":
            with zipfile.ZipFile(path) as archive:                  # a small .npz can unpack to a huge array
                if sum(item.file_size for item in archive.infolist()) > MAX_BYTES:
                    raise Refused("file is too large once unpacked")
            with np.load(path, allow_pickle=False) as npz:          # refuses any array that needs pickle
                data = {name: npz[name] for name in npz.files}
        else:
            data = load_file(path)                                  # numbers and a JSON header, checked by the library
    except (ValueError, RecursionError, MemoryError, SafetensorError, zipfile.BadZipFile) as error:
        raise Refused(f"unreadable: {error}") from None
    if set(data) != {"classes", "coef", "intercept"}:
        raise Refused("unexpected content: " + ", ".join(sorted(data)))
    try:
        classes, coef, intercept = (np.array(data[k], dtype=float) for k in ("classes", "coef", "intercept"))
    except (TypeError, ValueError):
        raise Refused("values are not numbers") from None
    shapes_ok = (classes.ndim == 1 and len(classes) > 1 and coef.ndim == 2 and coef.shape[0] == len(classes)
                 and intercept.shape == (len(classes),))
    if not shapes_ok or not all(np.isfinite(a).all() for a in (classes, coef, intercept)):
        raise Refused("wrong shapes or values")
    if len(set(classes.tolist())) != len(classes) or (classes != classes.round()).any():
        raise Refused("class names must be different whole numbers")
    return LinearModel(classes.astype(int), coef, intercept)


if __name__ == "__main__":
    from common import digits, train

    X_train, X_test, y_train, y_test = digits()
    original = train(X_train, y_train)
    Path("models").mkdir(exist_ok=True)
    export_json(original, "models/target.json")
    export_npz(original, "models/target.npz")
    copy = load_model("models/target.json", sha256_of("models/target.json"))
    print("same labels as the scikit-learn model:", bool((copy.predict(X_test) == original.predict(X_test)).all()))
    print("probabilities agree to 1e-9:", bool(np.abs(copy.predict_proba(X_test) - original.predict_proba(X_test)).max() < 1e-9))
    print("accuracy of the loaded model:", round(copy.score(X_test, y_test), 4))

    good = sha256_of("models/target.json")
    Path("models/tampered.json").write_text(Path("models/target.json").read_text().replace("0.", "0.9", 1))
    Path("models/evil.pkl").write_bytes(Path("prank.pkl").read_bytes())
    np.savez("models/objects.npz", classes=np.array([object()], dtype=object), coef=np.zeros((1, 64)), intercept=np.zeros(1))
    Path("models/extra.json").write_text(json.dumps({**json.loads(Path("models/target.json").read_text()), "run": "import os"}))
    big = np.zeros((2000, 2000))                                  # 32 MB of zeros: it compresses to a few kilobytes
    np.savez_compressed("models/bomb.npz", classes=np.arange(10), coef=big, intercept=np.zeros(10))
    print("file             verdict")
    accepted = 0
    for name in ("target.json", "target.npz", "tampered.json", "evil.pkl", "objects.npz", "extra.json", "bomb.npz"):
        # tampered.json gets the hash of the good file. The others get their own hash, so the content checks must catch them.
        trusted = good if name == "tampered.json" else sha256_of(f"models/{name}")
        try:
            load_model(f"models/{name}", trusted)
            verdict = "accepted"
            accepted += 1
        except Refused as reason:
            verdict = f"refused: {reason}"
        print(f"{name:<17}{verdict}")
    print("accepted", accepted, "of 7")

4. Run it

The script exports the course model, loads the JSON copy to prove that nothing changed, and offers the loader seven files. Five are bad.

python3 safeload.py
same labels as the scikit-learn model: True
probabilities agree to 1e-9: True
accuracy of the loaded model: 0.9533
file             verdict
target.json      accepted
target.npz       accepted
tampered.json    refused: hash does not match
evil.pkl         refused: format .pkl is not allowed
objects.npz      refused: unreadable: Object arrays cannot be loaded when allow_pickle=False
extra.json       refused: unexpected content: classes, coef, intercept, run
bomb.npz         refused: file is too large once unpacked
accepted 2 of 7

The loaded model gives the same labels and probabilities to nine decimal places. tampered.json has one changed number, so the hash does not match. evil.pkl is refused by its format before anything is read. objects.npz holds Python objects, and allow_pickle=False stops it. extra.json has the right hash and is still refused, because a fourth entry is not part of the format. bomb.npz is about 30 kilobytes on disk and unpacks to 32 MB: the check of the unpacked size refuses it before NumPy allocates anything. A false array size or a deep nesting also ends as Refused.

5. Hash a file

sha256_of gives the hash of a file. The command prints the first 16 digits for target.json, and whether the hash of tampered.json from step 4 is the same.

python3 -c "from safeload import *; p = 'models/target.json'; print(sha256_of(p)[:16], sha256_of(p) == sha256_of('models/tampered.json'))"
5147ace33493d7c8 False

Your first value will differ from this one: another processor changes the last digits of the weights and so the hash. The same file always gives the same value.

Your turn

A sender has written inbox/ with six files and hashes.txt: the name and the hash that the sender announced for each file. Save sender.py and run it. Then write inbox_check.py that reads hashes.txt, offers every file to load_model with its announced hash, and prints the verdict. Do not edit safeload.py.

sender.py

"""sender.py: a sender writes inbox/ with six model files and hashes.txt, the hashes that the sender announced."""
import json
import pickle
from pathlib import Path

import numpy as np

from safeload import sha256_of

inbox = Path("inbox")
inbox.mkdir(exist_ok=True)
good = {"classes": [0, 1, 2], "intercept": [0.1, 0.0, -0.1],
        "coef": [[0.5, -0.5, 0.1, 0.0], [0.0, 0.5, -0.5, 0.1], [-0.5, 0.0, 0.5, -0.1]]}

(inbox / "ok.json").write_text(json.dumps(good))
np.savez(inbox / "ok.npz", **{name: np.array(value) for name, value in good.items()})
(inbox / "swapped.json").write_text(json.dumps({**good, "intercept": [0.2, 0.0, -0.1]}))
(inbox / "model.pkl").write_bytes(pickle.dumps(good))
(inbox / "nan.json").write_text(json.dumps({**good, "intercept": [float("nan"), 0.0, -0.1]}))
(inbox / "notes.json").write_text(json.dumps({**good, "note": "from Dana"}))

lines = []
for name in ("ok.json", "ok.npz", "swapped.json", "model.pkl", "nan.json", "notes.json"):
    announced = "ok.json" if name == "swapped.json" else name      # the sender announced another file's hash
    lines.append(f"{name} {sha256_of(inbox / announced)}")
(inbox / "hashes.txt").write_text("\n".join(lines) + "\n")
print("wrote", len(lines), "files and hashes.txt")

Last, say in two sentences what a loader still cannot know about the two accepted files, even though they are safe to open.

Check yourself

You checked the hash. Why does the loader still check the content?

The hash proves that this is the file that was announced. If the announcer is hostile, the hash is right and the file is bad. The content checks stop a bad file that is well formed: extra.json shows it.

Where must the expected hash come from?

From a channel that the sender cannot change: a signed release note, your own record of what you built, a second person. A hash in the same folder as the file proves nothing: whoever swaps the file swaps the hash.

bomb.npz is 30 kilobytes and the limit is 10 MB. Why does the loader refuse it?

The limit applies to the bytes after unpacking too. A compressed file of zeros is small on disk and large in memory, and a few megabytes can ask for gigabytes. The loader reads the sizes from the zip directory and refuses before NumPy allocates the array.

Field notes

  • A hash shows that a file is the announced one; a signature also shows who made it. Inside one team an HMAC (hmac.new(key, data, "sha256").hexdigest()) can serve: only a holder of the key can make a matching one, but the verifier holds the key too and can forge one. Between companies, use a public-key signature (OpenSSF Model Signing, Sigstore).
  • The OWASP Machine Learning Security Top Ten lists the swap or booby trap of a model, a library or data as ML06 AI Supply Chain Attacks, and the change of an answer on its way to the user as ML09 Output Integrity Attack.
  • Pin and verify the libraries too. A requirements file with --hash=sha256:... after each line works with pip install --require-hashes -r requirements.txt, which refuses any package whose hash is not listed.
  • The loader reads each file twice, once for the hash and once to parse it. In a folder that other people can write to, read the bytes once, hash them and parse them from memory.
  • Scanners for model files read the steps of a pickle as pickletools does. They reduce risk, but the list of dangerous functions is never complete: an allow-list is stronger.