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 09 · 30 minutes

Store the weights as safetensors and test the file

After this lesson you can
  • Save a model as a safetensors file and rebuild its predictions from the file alone
  • Read the header of a safetensors file and say what each part holds
  • Offer damaged safetensors files to the loader and say what stops each one
Lab files of this lesson (16)

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

Northgate Parcels wants to buy a larger model from a supplier, and the supplier ships its weights as a .safetensors file. Your lead asks: "Everybody says that this format is safe. Why, and what does it not cover?" You write a small model into the format, take the file apart byte by byte, and offer damaged files to the loader of lesson 8.

Recall

Lesson 8: which three formats does the loader open, and what does it check before it parses a file?

JSON, .npz and .safetensors. It checks the suffix, the size (on disk and after unpacking) and the hash that the caller gives. Only then does it read the file.

Lesson 3: can a file that opens safely still hold a backdoor?

Yes. A safe format removes the risk of running code. The weights can still be trained to give a wrong answer for a trigger, and only a scan of the model finds that.

The idea

A pickle is a program, and a safetensors file is a data file. It has three parts: eight bytes that give the length of a header, the header (JSON text), and the raw numbers. The header names each tensor and says its type, its shape and where its numbers lie. A reader copies numbers. It has no step to carry out, so it has no way to run code.

A safetensors file
8 bytesthe length N of the headerN bytes of JSONname, type, shape, place of each tensorthe restthe raw numbers8 bytesthe length N of the headerN bytes of JSONname, type, shape, place of each tensorthe restthe raw numbers

The format is common for the weights of neural networks, and many model hubs use it. It solves one problem, the code in a file. It leaves the others open: who made the file, whether the values make sense, and whether the model is a backdoor.

Worked example

The scripts use common.py (lesson 1) and safeload.py (lesson 8). stbad.py also needs prank.pkl, which pickledemo.py of lesson 8 wrote.

1. Save the weights and load them back

safetensors.numpy.save_file(tensors, path) writes a dictionary of names and NumPy arrays to a file, and load_file(path) reads it back. np.ascontiguousarray copies an array so that its numbers lie row by row in memory. The format has no strides, so every tensor must be packed like that, and coef_ of this model is not. In a test without the call, 388 of 450 predictions changed.

stfile.py

"""stfile.py: save the weights as safetensors, load them, and rebuild the predictions from the file alone."""
from pathlib import Path

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

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)
good = {"classes": original.classes_, "coef": np.ascontiguousarray(original.coef_), "intercept": original.intercept_}
save_file(good, "models/target.safetensors")

loaded = load_file("models/target.safetensors")
print("tensors in the file:", sorted(loaded))
scores = X_test @ loaded["coef"].T + loaded["intercept"]
rebuilt = loaded["classes"][scores.argmax(axis=1)]
print("predictions that differ from the original:", int((rebuilt != original.predict(X_test)).sum()), "of", len(X_test))
python3 stfile.py
tensors in the file: ['classes', 'coef', 'intercept']
predictions that differ from the original: 0 of 450

The arrays rebuild all 450 predictions, so the file holds the model.

2. Read the header

struct.unpack("<Q", data) turns 8 bytes into one whole number (< little-endian, Q unsigned 64 bits), the type of the length field. .rstrip() removes spaces from the end of a text: the library pads the header with spaces, which the format allows.

sthead.py

"""sthead.py: take a safetensors file apart: the length field, the JSON header and the number area."""
import struct
from pathlib import Path

raw = Path("models/target.safetensors").read_bytes()
(size,) = struct.unpack("<Q", raw[:8])
print("header:", size, "bytes; the numbers after it:", len(raw) - 8 - size, "bytes")
print(raw[8:8 + size].decode().rstrip())
python3 sthead.py
header: 200 bytes; the numbers after it: 5280 bytes
{"classes":{"dtype":"I64","shape":[10],"data_offsets":[0,80]},"coef":{"dtype":"F64","shape":[10,64],"data_offsets":[80,5200]},"intercept":{"dtype":"F64","shape":[10],"data_offsets":[5200,5280]}}

The header is text: for each tensor a type (I64 and F64: 64-bit integers and decimals), a shape and a place in the number area. The places end at 5,280, the size of the number area. There is no step in the file to carry out.

3. Offer damaged files to the loader

stbad.py makes three bad files and gives each to the loader with its own hash, so that only the format and the content can stop them: the pickle of lesson 8 under the suffix .safetensors, the good file with its length field set to 20, and a valid file with a fourth tensor. except SafetensorError as error catches the error of the library and keeps it in error. {**d, "k": v} makes a new dictionary with the items of d and one more (lesson 8).

stbad.py

"""stbad.py: offer damaged safetensors files to load_file and to the safe loader."""
import struct
from pathlib import Path

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

from common import digits
from safeload import Refused, load_model, sha256_of

_, X_test, _, y_test = digits()
raw = Path("models/target.safetensors").read_bytes()
Path("models/pickle.safetensors").write_bytes(Path("prank.pkl").read_bytes())
Path("models/length.safetensors").write_bytes(struct.pack("<Q", 20) + raw[8:])
save_file({**load_file("models/target.safetensors"), "run": np.zeros(1)}, "models/extra.safetensors")
try:
    load_file("models/pickle.safetensors")
except SafetensorError as error:
    print("load_file on the pickle:", type(error).__name__, "-", error)
for name in ("target", "pickle", "length", "extra"):
    path = f"models/{name}.safetensors"
    try:
        model = load_model(path, sha256_of(path))
        print(f"{name:<8}accepted, accuracy {model.score(X_test, y_test):.4f}")
    except Refused as reason:
        print(f"{name:<8}refused: {reason}")
python3 stbad.py
load_file on the pickle: SafetensorError - Error while deserializing header: header too large
target  accepted, accuracy 0.9533
pickle  refused: unreadable: Error while deserializing header: header too large
length  refused: unreadable: Error while deserializing header: invalid JSON in header: EOF while parsing a value at line 1 column 20
extra   refused: unexpected content: classes, coef, intercept, run

The library reads the first 8 bytes of the pickle as a header length, finds a number far too large, and stops before it reads on. The cut header is not valid JSON. extra.safetensors is a good file of the format, and load_model still refuses it, as it refused extra.json in lesson 8: a fourth tensor is not part of our model.

What the format does not give you (the project's documentation): it does not check the values, since NaN and infinity can be in a file, so the loader's check for finite numbers stays. It has no field for a signature, and its __metadata__ entry is free text that anyone can write, so the file does not say who made it. And the weights may still hide a backdoor (lesson 3). The hash, the provenance record and the gates of lessons 8 and 10 still apply. Those gates and the scorecard open a model through load_model, so a record that names model.safetensors is accepted. ship.py of lesson 10 still writes JSON.

Your turn

The supplier now sends a smaller model, trained on the images whose label is below 5 (the digits 0 to 4) of the course training set, with the usual train. Write mysafe.py. It saves that model as models/small.safetensors (pack coef_ first), loads the file again, and rebuilds the predictions for the test images of the digits 0 to 4 by hand, as stfile.py does. It reads the header length and the size of the number area from the file. Then it makes a second file, models/nan.safetensors, in which the first value of the intercept is np.nan, and offers both files to load_model, each with its own hash.

Last, say which of the three open points of this lesson (who made it, sane values, a backdoor) the loader covers for nan.safetensors, and which it does not.

Check yourself

Why can a safetensors file not run code when it is opened?

It holds a length, a JSON header and raw numbers. The reader parses the JSON, checks that the places and shapes agree, and copies the numbers. Nothing in the file names a function to call, and the reader has no opcode that could. A pickle is the opposite: its steps are the program.

A model arrives as a .safetensors file. What can you now be sure of, and what not?

Opening it runs no code from the file: it is a JSON header and numbers, and a wrong header is refused. You cannot be sure who made it (use a hash from a trusted channel, and a signature), that the values are sane (check them), or that the model is no backdoor (lesson 3). The safe loader removes the code risk. The scan and the gates of lessons 3 and 10 are for the model risk. You need both.

Why did the loader refuse extra.safetensors, a file that the library opens without a fault?

The library checks the format, and the format allows any tensor names. Our model has exactly three arrays, and the loader enforces that. A file that is well formed and does not match the model that you expect is still a wrong file.

Field notes

  • Large models are often split over several .safetensors files with an index file next to them. Hash every file, and apply the format rule to the index too: it is JSON that names the other files.
  • The header is limited in size by the library, which is why the pickle was refused so early. A reader that you write yourself needs the same limit, or a hostile length makes it allocate memory.
  • __metadata__ is free text. Do not use it to decide anything, such as which code to run or which file to open.
  • A format that cannot run code is the first layer. Pin the source, check the hash from a trusted channel, and sign what you release (the OpenSSF Model Signing project and Sigstore define signatures for models).