Sub topic 16
A layered approach to loading third-party models
This chapter assumes you know how pickle's __reduce__ leads to code execution, what torch.load(weights_only=True) restricts, and how safetensors differs from pickle-based checkpoints. It combines those pieces into one workflow. No single control makes an untrusted model safe, so you stack several. Each layer covers a gap in the others.
Why one control is not enough
Every control from the earlier chapters has a known limit:
weights_only=Trueis an allowlist inside a large, complex unpickler. Bugs in it have been found. In 2025, CVE-2025-32434 showed thattorch.loadcould be made to execute code even withweights_only=Truein PyTorch versions before 2.6.0.- safetensors cannot run code on load. It also cannot tell you whether the numbers in the tensors are trustworthy.
- A file scanner is a heuristic. It finds known-bad patterns, not all bad patterns.
- A hash proves the file is the one you expected. It says nothing about whether that file is safe.
Defense in depth means that when one layer fails, another still limits the damage.
Layer 1: provenance and pinning
Start by asking where the file came from. A model from a vendor's verified organization is a different risk from a fork uploaded last week by an unknown account.
Pin the exact revision. On the Hugging Face Hub, a branch name such as main can change after you reviewed it. A commit hash cannot. Also download only the file types you intend to load, so a pickle file in the same repository never reaches your disk.
from huggingface_hub import snapshot_download
local_dir = snapshot_download(
repo_id="example-org/example-model",
revision="0123456789abcdef0123456789abcdef01234567", # a full commit hash, not "main"
allow_patterns=["*.safetensors", "*.json", "*.txt"],
)
print(local_dir)Next, record a checksum the first time you approve a file. Later loads compare against it, so a swapped file is detected.
import hashlib
def sha256_of(path: str, chunk_size: int = 1 << 20) -> str:
digest = hashlib.sha256()
with open(path, "rb") as f:
while block := f.read(chunk_size):
digest.update(block)
return digest.hexdigest()
def verify(path: str, expected: str) -> None:
actual = sha256_of(path)
if actual != expected:
raise RuntimeError(f"hash mismatch for {path}: {actual}")Layer 2: prefer data-only formats
Choose the format before you choose the loader. The table summarizes what each choice leaves you exposed to.
| Format | Code runs on load by design? | Remaining risks |
|---|---|---|
| `.pt` / `.pth` / `.bin` (pickle) | Yes, unless restricted | Arbitrary code, bypass bugs in restricted loaders |
| safetensors | No | Malicious weights, parser bugs, which are rare |
| GGUF | No | Parser bugs, untrusted metadata and chat templates |
| ONNX | No | Parser bugs, external-data file paths, custom operators |
| Keras / HDF5 / SavedModel | Depends on contents | Lambda layers, custom objects, graph ops with side effects |
With transformers, you can make the preference explicit so that a repository offering only pickle files fails instead of silently falling back:
from transformers import AutoModel
model = AutoModel.from_pretrained(
"example-org/example-model",
revision="0123456789abcdef0123456789abcdef01234567",
use_safetensors=True, # raise an error rather than load a pickle file
trust_remote_code=False, # never run Python files shipped with the repo
)trust_remote_code=True is a separate hole. It downloads and executes Python from the repository, which gives an attacker the same power as a malicious pickle without any serialization trick. Leave it off unless you have read the code.
Layer 3: scan pickle files before loading
If a pickle checkpoint is unavoidable, inspect it without loading it. A modern torch.save file is a zip archive containing a data.pkl entry. The pickletools.genops function walks its opcodes without executing them. The function below collects the globals the pickle imports.
import pickletools
import zipfile
def list_globals(pickle_bytes: bytes) -> set[str]:
found = set()
strings = []
for op, arg, _pos in pickletools.genops(pickle_bytes):
if op.name in ("SHORT_BINUNICODE", "BINUNICODE", "BINUNICODE8", "UNICODE"):
strings.append(arg)
elif op.name == "GLOBAL":
found.add(arg.replace(" ", ".")) # arg is "module name"
elif op.name == "STACK_GLOBAL":
if len(strings) >= 2:
found.add(f"{strings[-2]}.{strings[-1]}")
else:
found.add("<unresolved>")
return found
def scan_checkpoint(path: str) -> dict[str, set[str]]:
if not zipfile.is_zipfile(path):
raise ValueError("not a zip-based checkpoint; refuse or convert in a sandbox")
results = {}
with zipfile.ZipFile(path) as zf:
for name in zf.namelist():
if name.endswith(".pkl"):
results[name] = list_globals(zf.read(name))
return results
if __name__ == "__main__":
for entry, names in scan_checkpoint("model.pth").items():
print(entry)
for n in sorted(names):
print(" ", n)A normal state dict imports only a few names, such as collections.OrderedDict and torch._utils._rebuild_tensor_v2, plus storage types such as torch.FloatStorage. Anything like os.system, builtins.eval, subprocess.Popen or posix.system is a reason to delete the file.
Layer 4: restricted loading
Load with the narrowest loader that works. For PyTorch pickle files, that means weights_only=True, on a current PyTorch release so known bypasses are patched.
import torch
state_dict = torch.load("model.pth", map_location="cpu", weights_only=True)
model.load_state_dict(state_dict)Two details matter here. map_location="cpu" keeps tensors off the GPU until you decide to move them, which avoids touching GPU drivers with unvetted data. load_state_dict also checks keys and shapes, so a file that does not match your architecture fails early. Do not "fix" a weights_only failure by setting it to False. The error means the file contains something beyond plain tensors, which is the signal you wanted.
Layer 5: convert once, in quarantine
The safest long-term pattern is to load each pickle checkpoint once, in a throwaway environment, then store and distribute only the safetensors version.
import torch
from safetensors.torch import save_file
state_dict = torch.load("model.pth", map_location="cpu", weights_only=True)
# safetensors rejects tensors that share memory, so copy them into contiguous tensors.
clean = {k: v.contiguous().clone() for k, v in state_dict.items()}
save_file(clean, "model.safetensors", metadata={"format": "pt"})Run this step with no network access and no credentials in the environment:
docker run --rm --network none --read-only \
--tmpfs /tmp --cap-drop ALL --security-opt no-new-privileges \
-v "$PWD/quarantine:/work:rw" \
my-convert-image python /work/convert.pyIf the file contains a payload that gets past the first four layers, it runs in a container that cannot reach your network, your secrets or your host file system. The conversion output is plain tensor data. Everything downstream, including your training and serving systems, consumes only that.
Layer 6: verify behavior
Safe loading does not make a model good. A tensor file cannot execute code, but its weights can encode a backdoor, such as a trigger phrase that changes outputs. Before production use:
- Run your standard evaluation set and compare the results to the publisher's claims.
- Test known adversarial inputs for your use case.
- Check the model's license and its training-data statement, if one exists.
- Roll out behind a canary, with monitoring for unexpected outputs.
These checks will not catch a well-hidden backdoor. They do catch the common failures: a wrong file, a corrupted conversion, or a model that behaves differently from its description.
Common errors
- Trusting the file extension. A
.binor.safetensorsname proves nothing. Check magic bytes or use the real parser, which rejects wrong content. - Scanning, then loading a different file. Hash the file you scanned and load that exact path, or you create a time-of-check to time-of-use gap.
- Pinning the loader but not the dependencies. Keep PyTorch, safetensors and transformers patched. The restricted-loader bypass above was fixed by upgrading.
- Letting the sandbox hold secrets. A container with your cloud credentials in its environment variables defeats the isolation.
- Skipping the adjacent formats. Keras models with
Lambdalayers and unsafe deserialization settings can run code. Apply the same layered process to every format that is not strictly data.
Exercise
A teammate downloads classifier.pth from a personal account on a model hub, runs your scanner and sees only collections.OrderedDict and torch._utils._rebuild_tensor_v2. They want to call torch.load("classifier.pth") on the production server because the scan is clean. Name the layers you would still apply, in order, and say why a clean scan is not sufficient.
Show answer
First, check provenance and pin the revision (or record the file's SHA-256) so you know exactly which file you reviewed. Then load it with weights_only=True on a patched PyTorch version, not with the default, because the scanner is only a heuristic and can miss bypasses. Do the load and the conversion to .safetensors in a sandbox with no network and no secrets, and deploy only the safetensors file. Finally, run an evaluation on your own data, because the weights themselves could be tampered with and no loading control detects that. A clean scan is insufficient because scanners can be fooled and because code execution is only one of the risks.
Exercise
Why does the chapter recommend use_safetensors=True and trust_remote_code=False together when calling from_pretrained?
Show answer
use_safetensors=True makes loading fail instead of falling back to a pickle file, which removes the pickle code-execution path. trust_remote_code=False stops the library from downloading and running Python files from the repository, which is a separate code-execution path that safetensors does not affect. Both must be closed, or the attacker simply uses the open one.