Model files that run code: pickle and safetensors
Some model file formats can run code the moment you load them. Learn why, and how to load models safely.
In 60 seconds
Model files that run code: pickle and safetensors
Some model file formats can run code the moment you load them. Learn why, and how to load models safely.
Safer formats
| Format | Can run code on load? | Notes |
|---|---|---|
| Python pickle (and formats built on it) | Yes | Only load from sources you fully trust |
| safetensors | No, it stores tensors only | Designed to be safe and fast to load; widely supported |
| ONNX | Not designed to run arbitrary Python on load | Still check custom operators and the runtime you use |
| GGUF and similar weight formats | Not designed to run arbitrary code on load | Loader bugs are still possible; keep tools updated |
import hashlib
from safetensors.torch import load_file
EXPECTED_SHA256 = "paste-the-published-hash-here"
path = "model.safetensors"
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
if h.hexdigest() != EXPECTED_SHA256:
raise SystemExit("Hash mismatch: do not load this file")
state_dict = load_file(path) # reads tensors only
print(len(state_dict), "tensors loaded")
# model.load_state_dict(state_dict) # into a model class you trustOther ways model loading runs code
- Some libraries have an option, often named like
trust_remote_code, that downloads and runs Python code shipped with a model repository. Turning it on means running that author's code on your machine. - Custom layers or operators may need extra code you install.
- Notebooks, setup scripts and example code in a model repository are ordinary code too.
- Some frameworks offer safer loading modes, such as PyTorch's
weights_onlyoption fortorch.load. Check what your version supports and make it the default.
A safe loading policy
- 1
Prefer safe formats
Ask for or convert to safetensors. Refuse pickle from unknown sources. - 2
Verify
Check the hash (and signature, where available) against what the publisher states. - 3
Scan
Run a model scanner that looks for dangerous code in pickle-based files. Scanners help but can miss things. - 4
Isolate
Load any untrusted model in a sandbox: a throwaway container or VM with no secrets, no cloud credentials and no network. - 5
Review remote code
If remote code is truly needed, read it, pin the exact revision, and store a reviewed copy.
pickle.load, torch.load, joblib.load and remote-code options. For each, write down where the file comes from.Watch and read more
Lab
A script that verifies a model file's hash and loads it with safetensors, plus an inventory of risky loads in your code.
The problem
Download a small, well-known open model that is published in safetensors format, from its official page, along with its published hash (many hubs show the SHA-256 of each file).
- Adapt the lesson's code sample: compute the SHA-256 and compare it with the published value.
- Change one byte of a copy of the file and show the script refuses it.
- Load the original with
safetensorsand print the tensor names and shapes. - Search one of your own repositories for
pickle.load,torch.load,joblib.loadand remote-code options. List each with the file's source.
Do not write or run any pickle file designed to execute code.
You are done when
Hard questions
Try to answer before you reveal. If you can answer these, you understood the lesson.
Q1A hash matches the one on the model page. What does that prove, and what does it not prove?Reveal
It proves the file you have is the same as the one the page describes, so it was not corrupted or swapped on the way. It does not prove the file is safe or that the publisher is trustworthy. If an attacker controls the page, they can publish a bad file with a matching hash. Signatures tied to a known identity, and trust in the source, cover that gap.
Q2Why is a sandbox without network access important even if the model file is safetensors?Reveal
The weights may be safe, but other parts might not be: remote code, custom operators, tokenizer files, or bugs in the loader. Without network access, any code that does run cannot send data out or download more tools. It is cheap insurance.
Questions people ask
Is every pickle file dangerous?
A pickle file you created yourself and stored safely is fine to load. The danger is loading one that someone else could have made or changed. The format cannot tell you which it is.
Can we convert an untrusted pickle model to safetensors safely?
Converting usually means loading the pickle first, which is the risky step. Do it only inside an isolated sandbox with no secrets and no network, then verify and use the safetensors output.
Do model hubs scan uploads?
Some platforms scan uploaded files and show warnings. This is helpful, but do not rely on it alone. Scanners can miss new tricks, and files can come from many other places, such as shared drives and chat attachments.
What about scikit-learn models saved with joblib?
joblib uses pickle underneath, so the same rules apply. Load only files you trust, or use a format meant for safe exchange where your tools support it.
Lesson test
5 questions. Get 3 right (60%) to pass and complete this lesson.