Sub topic 3
GGUF for local inference and quantized models
This chapter assumes you know how to load a PyTorch state dict, understand what a tensor is, and have read the earlier chapters on pickle. It covers the formats you are likely to meet when you run models on your own machine, and how to move older checkpoints into safer formats.
GGUF for local inference
GGUF is a binary format used by llama.cpp and tools built on it. A GGUF file holds a header, a key-value metadata section (architecture, tokenizer, context length), a table describing each tensor, and the raw tensor data. Weights are often stored quantized, for example as 4-bit integers with scale factors, which shrinks a model enough to run on a laptop. Loading a GGUF file reads fixed-layout fields. It never calls a Python function, so it does not carry the pickle risk.
ONNX
ONNX (Open Neural Network Exchange) stores a computation graph as a protocol buffer (protobuf) message. The file lists nodes, each naming an operator such as MatMul, plus the weights. ONNX is portable across runtimes, but custom operators can point to native code, so check the operator set before you trust a model.
TensorFlow and Keras formats
A TensorFlow SavedModel directory stores graphs and functions. Older Keras .h5 files use HDF5. Keras model files can also contain a Lambda layer, which stores serialized Python bytecode. Loading that layer executes code. Keras 3 defaults to safe_mode=True, which blocks this. Do not turn it off for a file you did not create.
Choosing a format
| Format | Executes code on load | Typical use |
|---|---|---|
| pickle (.pt, .pth, .bin) | Yes | Legacy PyTorch checkpoints |
| safetensors | No | Hugging Face weights, training |
| GGUF | No | Local inference with llama.cpp |
| ONNX | Only with custom ops | Cross-runtime deployment |
Converting checkpoints to safetensors
Load the old file with weights_only=True, then save the tensors with safetensors:
import torch
from safetensors.torch import save_file
state_dict = torch.load("model.pth", map_location="cpu", weights_only=True)
tensors = {k: v.contiguous() for k, v in state_dict.items()}
save_file(tensors, "model.safetensors")> Note: save_file rejects tensors that share memory. Untie shared weights before you save.
A layered approach to loading third-party models
Apply several defenses together:
- Pin the exact revision or commit hash, and verify a published checksum.
- Prefer safetensors or GGUF.
- Load pickle-based files only with
weights_only=True. - Never enable
trust_remote_codefor a model you have not reviewed. - Load the model in an unprivileged account or container.
Exercise
Why does GGUF loading avoid the pickle risk?
Show answer
GGUF stores a fixed binary layout of metadata and tensor data. A loader reads those fields and never calls arbitrary Python callables, so a crafted file cannot run code during loading.