DL0226 Checkpoint Formats: safetensors and Memory Mapping

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?

A three-panel question card. The first panel describes one shared checkpoint: file pytorch_model.bin, Python pickle format, 40 GB in fp16, downloaded from a stranger's repo, on a box with 64 GB of RAM, and asks whether it is safe to load and whether it will fit. The second panel shows Hugging Face moving the Hub default from a pickle .bin file to a safetensors file and asks why. The third panel shows 2 TB of token ids on NVMe next to 64 GB of RAM and asks how the corpus fits.

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.

Byte layout of a safetensors file: an 8-byte length N, a JSON header of N bytes, then contiguous tensor data for embed_tokens, layers.0.q_proj, 288 more tensors, and lm_head. Below the header, a box shows a JSON entry with dtype F16, shape 32000 by 4096 and data offsets 0 to 262144000. Below the tensor region, a row of twenty 4 KiB pages mapped into the process shows only the six pages under layers.0.q_proj shaded as resident after one get_tensor call, while the rest are mapped but never read.

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:
\mathrm{start}(t) = 8 + N + b_t
e_t - b_t = s(\tau_t) \prod_{j} d_{t,j}
M_{\mathrm{pickle}} \approx 2 P s
M_{\mathrm{safe}} \approx P s
W_{\mathrm{step}} = B \cdot L \cdot s_{\mathrm{tok}}

Where:

  • \mathrm{start}(t) is the absolute file byte where tensor t begins, N is the JSON header length stored in the first 8 bytes, and b_t is the begin value of its data_offsets, which is relative to the end of the header.
  • e_t is the end offset, s(\tau_t) the bytes per element of dtype \tau_t (2 for F16 and BF16, 4 for F32), and d_{t,j} the shape dimensions; a header where this product disagrees with the byte range is rejected.
  • P is the parameter count and s the bytes per parameter of the stored dtype; M_{\mathrm{pickle}} counts a random-initialized model plus the unpickled state dict held at the same time.
  • M_{\mathrm{safe}} 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.
  • W_{\mathrm{step}} is the data touched per training step, with B sequences per batch, L tokens per sequence, and s_{\mathrm{tok}} 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):
P s = 20 \times 10^{9} \cdot 2\ \mathrm{B} = 40\ \mathrm{GB}
M_{\mathrm{pickle}} \approx 2 \cdot 40\ \mathrm{GB} = 80\ \mathrm{GB} > 64\ \mathrm{GB}
M_{\mathrm{safe}} \approx 40\ \mathrm{GB}
W_{\mathrm{step}} = 512 \cdot 2048 \cdot 2\ \mathrm{B} = 2\ \mathrm{MiB}
2 \times 10^{12}\ \mathrm{B} / 4096\ \mathrm{B} \approx 4.9 \times 10^{8}

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.

Two schematic charts of host RAM. Left: loading a 40 GB fp16 checkpoint, the pickle path climbs to 40 GB during random initialization and then to about 80 GB while torch.load reads the state dict, crossing the 64 GB physical RAM line, while the safetensors path keeps anonymous RAM near 1 GB and its page cache rises to 40 GB. Right: reading a 2 TB corpus, loading it into RAM runs out of memory after 64 GB, while the memory-mapped path keeps process RSS near 2 GB and the page cache saturates just under the RAM ceiling.

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 i 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 i is a slice at byte 4096 i. 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.

PropertysafetensorsPickle .bin (torch.save)
What the file isPassive data: 8-byte length, JSON index, raw tensor bytesA pickle program inside a zip archive, plus raw storage entries
Opening an untrusted fileNo code path; a malformed header fails bounds checksOpcodes can import and call any function, so loading runs attacker code
Load pathmmap, zero-copy views, pages read on first touchUnpickle, rebuild objects, copy storages into fresh memory
Peak host RAM, 40 GB modelAbout one evictable copy with a meta-device skeletonAbout two copies: initialized model plus state dict
Partial readsget_tensor and get_slice fetch one tensor or one sliceThe whole program is unpickled; mmap=True since PyTorch 2.1 avoids only the storage copies
What it can storeTensors plus a flat string-to-string metadata mapAny Python object: optimizer state, schedulers, custom classes
ReadersRust core with PyTorch, NumPy, JAX, TensorFlow and MLX bindingsPython with the exact classes importable, in practice PyTorch only

Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *