A teammate wants to load a 40GB pickle checkpoint and wonders why Hugging Face pushed safetensors instead. Separately, how does a 2TB dataset fit in 64GB of RAM?

The Problem: A teammate on a 64 GB training box wants to torch.load a 40 GB pickle checkpoint pulled from someone else’s repo, and asks why Hugging Face moved the Hub to safetensors. The same box must also train on a 2 TB tokenized corpus, which is about 31 times larger than its RAM.
Answer
A pickle checkpoint is a program, not a data file. Python’s unpickler executes opcodes that can import any callable and call it, so loading an untrusted .bin is arbitrary code execution. Safetensors replaces it with a passive layout of an 8-byte length, a JSON header that maps each tensor name to dtype, shape and byte offsets, and one contiguous byte buffer. Because nothing needs decoding, a loader can mmap the file and hand out zero-copy tensor views, so only the pages a process actually touches are read from disk. That removes the unpickling pass and the second copy of the weights, which is why CPU loading is often more than an order of magnitude faster and peak RAM halves. The 2 TB dataset fits the same way, because Hugging Face datasets keeps it as memory-mapped Apache Arrow (or streams it) and the OS page cache holds only the working set.
(1) Pickle Is A Program: The GLOBAL opcode imports any module attribute and REDUCE calls it with arguments, so a __reduce__ returning os.system runs at load time. Sharing a pickle checkpoint means sharing whatever payload it carries.
(2) weights_only Is A Mitigation, Not A Format: torch.load(weights_only=True) restricts the unpickler to an allowlist of types, but it still parses an executable opcode stream and has needed security patches.
(3) Header Then Bytes: The first 8 bytes are a little-endian unsigned 64-bit length N, the next N bytes are JSON, and the rest is tensor data in C order with no gaps or overlaps, so validation is just bounds checking.
(4) Zero-Copy mmap: Tensors are views into the mapped file, so there is no deserialization pass and no intermediate copy, and every process on the host shares the same page cache.
(5) Lazy And Sliced Loads: safe_open with get_tensor or get_slice reads one tensor or one slice of it, which is how a tensor-parallel rank loads only its own columns.
(6) Meta-Device Skeleton: from_pretrained builds the model with no storage on the meta device and fills it shard by shard, so the random-init copy never exists.
(7) Datasets Never Load Into RAM: Arrow files are memory-mapped and row lookup is offset arithmetic, while streaming=True reads remote shards incrementally, so RAM holds the working set, not the corpus.
The danger on the pickle side is concrete. torch.save writes a zip archive whose data.pkl entry is a pickle program, with tensor storages kept as separate raw entries. On load, the unpickler walks that program: GLOBAL pushes a callable named by module and attribute, and REDUCE applies it to a tuple. A crafted object whose __reduce__ returns os.system with a shell command therefore executes the moment the file is opened, before a single tensor is touched. Safetensors has no such code path. A typical header entry reads “model.embed_tokens.weight”: {“dtype”: “F16”, “shape”: [32000, 4096], “data_offsets”: [0, 262144000]}, the library rejects headers above 100 MB, duplicate names, and offsets that disagree with dtype times shape, and the worst a malicious file can do is fail validation.

Figure 1: A safetensors file is an 8-byte length, a JSON index, and one contiguous tensor buffer. After a single mmap call, asking for layers.0.q_proj faults in only the pages under its byte range (plus the partial edge pages), while every other tensor stays on disk until touched.
Mathematical Formulation:
Where:
is the absolute file byte where tensor
begins,
is the JSON header length stored in the first 8 bytes, and
is the begin value of its data_offsets, which is relative to the end of the header.
is the end offset,
the bytes per element of dtype
(2 for F16 and BF16, 4 for F32), and
the shape dimensions; a header where this product disagrees with the byte range is rejected.
is the parameter count and
the bytes per parameter of the stored dtype;
counts a random-initialized model plus the unpickled state dict held at the same time.
counts a single copy when the skeleton lives on the meta device, and that copy is file-backed page cache the kernel can evict and share rather than anonymous memory.
is the data touched per training step, with
sequences per batch,
tokens per sequence, and
bytes per token id (2 for uint16 when the vocabulary has at most 65,536 entries).
Worked Example (one 64 GB box, 40 GB checkpoint, 2 TB corpus):
The checkpoint numbers explain the teammate’s experience. A 20B-parameter fp16 model is 40 GB, and the classic pickle path needs about 80 GB of anonymous memory, so on a 64 GB box it swaps or gets OOM-killed before load_state_dict finishes. The mmap path holds one evictable copy, and the unavoidable cost is the raw read itself, roughly 13 s at 3 GB/s from NVMe. Hugging Face’s own GPT-2 benchmark reports tens of times faster CPU loading with a warm page cache and about 2x on GPU, where the host-to-device copy dominates; part of the CPU number is deferred I/O, since pages are read on first touch rather than at open. The corpus numbers are even more lopsided. A 2048-token uint16 sequence is exactly 4096 bytes, one page, so the 2 TB file holds about 490 million sequences and a 512-sequence batch is 512 random 4 KiB reads. A datacenter NVMe drive serves several hundred thousand such reads per second, which puts each step’s I/O on the order of a millisecond.

Figure 2: Schematic resident memory on the 64 GB box. (a) The pickle path holds a random-initialized model and the unpickled state dict at once and needs about 80 GB, while the mmap path keeps the weights in evictable page cache. (b) Reading the 2 TB corpus into RAM fails after 64 GB, whereas a memory-mapped corpus keeps process RSS near 2 GB and lets the page cache cycle at the RAM ceiling.
Inside transformers, from_pretrained runs a fixed chain: resolve repo id and revision → fetch files into the hub cache (content-addressed blobs behind snapshot symlinks) → read config.json and pick the model class → open model.safetensors.index.json, whose weight_map assigns every tensor name to a shard → build the module tree on the meta device → per shard, safe_open, read each tensor, cast to torch_dtype and assign → tie shared weights and place layers by device_map. When only pytorch_model.bin exists, the same chain unpickles instead. That is why Hugging Face’s conversion bot opened safetensors pull requests on popular repos and why save_pretrained now writes safetensors by default.
The dataset side uses the same operating-system trick on a different file format. load_dataset converts source files once into Apache Arrow tables in the local cache, and a Dataset object is a view over those memory-mapped files. Arrow stores a token column as one contiguous values buffer plus an offsets buffer, so row is two offset lookups and a slice, with no Python objects created until you ask for them. Many pretraining codebases go one step simpler and write a single flat uint16 token array read with numpy.memmap, where sample
is a slice at byte
. When 2 TB exceeds local disk too, streaming=True returns an IterableDataset that pulls shards over HTTP as iteration proceeds and shuffles approximately with a shard-order shuffle plus a fixed-size sample buffer.
| Property | safetensors | Pickle .bin (torch.save) |
|---|---|---|
| What the file is | Passive data: 8-byte length, JSON index, raw tensor bytes | A pickle program inside a zip archive, plus raw storage entries |
| Opening an untrusted file | No code path; a malformed header fails bounds checks | Opcodes can import and call any function, so loading runs attacker code |
| Load path | mmap, zero-copy views, pages read on first touch | Unpickle, rebuild objects, copy storages into fresh memory |
| Peak host RAM, 40 GB model | About one evictable copy with a meta-device skeleton | About two copies: initialized model plus state dict |
| Partial reads | get_tensor and get_slice fetch one tensor or one slice | The whole program is unpickled; mmap=True since PyTorch 2.1 avoids only the storage copies |
| What it can store | Tensors plus a flat string-to-string metadata map | Any Python object: optimizer state, schedulers, custom classes |
| Readers | Rust core with PyTorch, NumPy, JAX, TensorFlow and MLX bindings | Python with the exact classes importable, in practice PyTorch only |
Leave a Reply