Sub topic 14
Choosing a format: safety, portability and speed
This chapter assumes you know how pickle loads data and why __reduce__ allows code execution. It also assumes you have seen torch.load(..., weights_only=True) and the safetensors layout from earlier chapters. Here you compare the formats and pick one for a given job.
Four questions to ask of any format
No format wins on every axis, so ask four questions about each candidate.
- Does loading run code or only parse data? A data-only format limits what a hostile file can do. It does not make the model's behavior trustworthy.
- What does the file carry? It may hold only tensors. It may also hold a computation graph, an architecture, tokenizer data or chat templates.
- Who can read it? A format that only one framework understands limits where the model can run.
- How fast and how large is it? Load time, memory use and quantization support matter most for large models and for serving many replicas.
Format by format
PyTorch `.pt` and `.pth`
These are a zip archive that contains a pickle plus raw tensor storage. They can hold any Python object, including optimizer state and whole nn.Module instances. They also run code on load unless you restrict the unpickler. weights_only=True narrows the risk but does not remove it. It has had bypass bugs in past releases, so keep PyTorch updated.
safetensors
The file is an 8-byte header length, a JSON header and a block of raw tensor bytes. Loading parses JSON and reads bytes, so there is no code path from file contents to function calls. The format is a good fit for one specific job:
- It supports lazy loading, so you can read one tensor without reading the whole file.
- It can be memory-mapped, which avoids copies.
- It supports dtypes such as
bfloat16.
Its limits follow from its simplicity. It stores tensors and string metadata only, so you need the model code and config from somewhere else. It cannot store optimizer objects or arbitrary Python values. Tensors that share storage must be handled explicitly when saving.
from safetensors import safe_open
with safe_open("model.safetensors", framework="pt", device="cpu") as f:
print(list(f.keys()))
weight = f.get_tensor("weight") # reads only this tensor
print(weight.shape)GGUF
GGUF is the single-file format used by llama.cpp and related runtimes. It starts with the magic bytes GGUF, then key-value metadata, then tensor data. Its strengths are quantized tensor types (4-bit and 5-bit block formats), memory mapping, and bundling the tokenizer and hyperparameters into one file. The format is data-only, but the risk moves to the parser and the metadata. Memory-safety bugs have been reported in GGUF parsers. Embedded chat templates are code-like text, and some runtimes have had template-handling vulnerabilities. Use a current runtime build and treat metadata strings as untrusted input.
ONNX
ONNX stores a computation graph in protobuf, with weights as initializers inside the file or in external data files. It is the most portable option for inference, because many runtimes can run it and you can export from several frameworks. Protobuf does not execute code. The risks are different:
- Custom operators that load native libraries.
- External-data paths that point outside the model directory. Several path-traversal bugs have been reported for these.
- Parser bugs.
Validate with onnx.checker and load with a runtime that has custom-op loading disabled.
TensorFlow SavedModel, HDF5 and Keras
A SavedModel is protobuf plus checkpoint files. TensorFlow's own security guidance says models are programs. A graph can contain operations that read or write files, and a graph can call into Python. HDF5 (.h5) and .keras files can embed Keras Lambda layers, which store Python code. Keras 3 loads with safe_mode=True by default, which blocks that deserialization. Do not turn it off for a model you did not build. Both formats tie you to the TensorFlow or Keras ecosystem, and conversion tooling varies in quality.
Side-by-side comparison
| Format | Runs code on load? | Carries architecture or graph? | Portability | Load speed and size notes |
|---|---|---|---|---|
| PyTorch pickle (`.pt`) | Yes, unless restricted | Possible (full pickled objects) | PyTorch only in practice | Full unpickle and copy |
| safetensors | No | No, tensors only | Many frameworks and hubs | Lazy, mmap-friendly, no copy on CPU |
| GGUF | No, but parser and template risk | Hyperparameters and tokenizer, not a graph | llama.cpp ecosystem | Mmap-friendly, strong quantization |
| ONNX | No, but custom ops and external data risk | Yes, a graph | Many runtimes and languages | Good for inference, extra files possible |
| SavedModel / HDF5 / Keras | Possible (graph ops, Lambda code) | Yes | TensorFlow and Keras | Varies, `safe_mode` helps |
Speed claims depend on hardware, file system caching and model size. Measure your own load path before using speed as the deciding factor. Safety should usually decide first.
A decision path
Triage with a format sniffer
File extensions can be wrong or forged, so check the first bytes before you decide how to load. The script below classifies a file and prints a policy hint. It is a triage aid and not a malware scanner, because a hostile file can mimic any header.
import struct
import sys
from pathlib import Path
RISK = {
"safetensors": "data-only; load with safetensors",
"gguf": "data-only, but keep the runtime updated and distrust metadata",
"onnx": "graph; run onnx.checker, disable custom ops, check external data",
"zip": "may hold pickle (PyTorch) or Keras code; treat as code",
"hdf5": "may embed Keras Lambda code; keep safe_mode on",
"pickle": "executes code on load; do not load untrusted",
"unknown": "unrecognized; do not load until identified",
}
def sniff(path):
p = Path(path)
size = p.stat().st_size
with p.open("rb") as f:
head = f.read(16)
if head[:4] == b"GGUF":
return "gguf"
# Check safetensors before pickle: a header length of 128+ can start with 0x80.
if len(head) >= 9:
(n,) = struct.unpack("<Q", head[:8])
if head[8:9] == b"{" and 0 < n <= size - 8:
return "safetensors"
if head[:4] == b"PK\x03\x04":
return "zip"
if head[:8] == b"\x89HDF\r\n\x1a\n":
return "hdf5"
if head[:1] == b"\x80":
return "pickle"
if p.suffix == ".onnx":
return "onnx"
return "unknown"
if __name__ == "__main__":
for arg in sys.argv[1:]:
kind = sniff(arg)
print(f"{arg}: {kind} - {RISK[kind]}")ONNX has no magic bytes, so the script falls back to the extension. That is the weakest check in the script.
Gotchas and failure modes
- Safe format, unsafe model. A safetensors file can hold poisoned or backdoored weights. The format removes code execution on load. It says nothing about what the model does.
- Safe weights, unsafe companion files. Many repositories ship a
modeling_*.pyfile or a tokenizer pickle next to the weights. Options that allow remote code (such astrust_remote_code=Truein Hugging Face Transformers) run that Python code regardless of the weight format. - Zip is not one format. A
.kerasfile and a PyTorch checkpoint are both zip archives. The magic bytes tell you the container, not whether it holds code. - Conversion can load the pickle. Converting a
.ptfile to safetensors usually means loading the pickle first. Do that step in an isolated environment, as covered in the conversion chapter. - Metadata is input. JSON headers, GGUF key-value pairs and ONNX attributes come from the file author. Your tooling should validate sizes and paths instead of trusting them.
Practical recommendations
- Publish new models as safetensors for weights, with config and code in separate, reviewed files.
- Use GGUF when you target llama.cpp-style local inference and need quantization.
- Use ONNX when the consumer is a different framework or a non-Python runtime.
- Accept pickle-based or Keras files only from sources you control, and load them in a sandbox.
- Pin and verify checksums for every artifact you deploy.
Exercise
A teammate wants to download a .bin file of a fine-tuned model from a public repository and load it with torch.load in your production service because "it loads fastest". Which format would you ask for instead, what risk does it remove, and what risk remains?
Show answer
Ask for a safetensors version (or convert it in an isolated sandbox first). Safetensors removes code execution during deserialization, because loading only parses a JSON header and reads raw tensor bytes. It also loads lazily and can be memory-mapped, so it is usually not slower. The remaining risks are poisoned or backdoored weights, companion files such as custom modeling code or tokenizer pickles, and a tampered download. Verify the checksum, review any companion code, and run the model's evaluation checks before deployment.
Exercise
Why does the sniffer above test for safetensors before testing for a leading 0x80 byte?
Show answer
A safetensors file begins with an 8-byte little-endian header length. If that length is 128 or more and its low byte happens to be 0x80, the first byte of the file looks like a pickle protocol opcode. Checking the safetensors structure first (a { at byte 8 and a header length that fits in the file) avoids misclassifying it as pickle.