Saving, Loading, and Pretrained Weights

Dive into Deep Learning · §5.6

File I/O, Checkpoints, and Serialization
state dictionaries · pickle RCE vs. safetensors · 5-part atomic checkpoints · pretrained key auditing

Why Checkpointing and Safe Files Are Mission-Critical

Fault Tolerance & Security

  • Hardware failures are routine: During 54 days of pre-training Llama 3 405B on 16{,}384 GPUs, Meta recorded 419 unexpected interruptions (~1 crash every 3 hours).
  • Resuming requires more than weights: Restarting Adam from saved weights alone causes the very first update step to blow up the loss by >100\times.
  • Arbitrary code execution on load: Downloading a third-party pickle checkpoint can execute malicious shell commands the moment load is called.

We Serialize the State Tree, Never the Python Class Code

State vs. Architecture

  • The state dictionary stores only (path, shape, dtype, raw_bytes), with no trace of the MLP class:
class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.hidden = nn.Linear(20, 256)
        self.output = nn.Linear(256, 10)

    def forward(self, x):
        return self.output(F.relu(self.hidden(x)))

net = MLP()
X = torch.randn(2, 20)
Y = net(X)
{name: tuple(t.shape) for name, t in net.state_dict().items()}
{'hidden.weight': (256, 20),
 'hidden.bias': (256,),
 'output.weight': (10, 256),
 'output.bias': (10,)}

Security Hazard: Python Pickle Executes Code on Load

Why Pickle Is Unsafe for Sharing

  • Python’s pickle format is a stack-based virtual machine that executes arbitrary callables returned by __reduce__:
class Tripwire:
    def __reduce__(self):  # pickle calls print(...) to rebuild the object
        return (print, ('*** payload executed while loading ***',))
torch.save(Tripwire(), 'tripwire.pt')
_ = torch.load('tripwire.pt', weights_only=False)  # the payload runs here
*** payload executed while loading ***

Hardened Loaders Refuse Arbitrary Objects by Default

Allowlist Unpicklers

  • Hardened loaders refuse arbitrary pickled objects, while safetensors eliminates the opcode parser attack surface completely:
try:
    torch.load('tripwire.pt')  # weights_only=True, the default
except Exception as e:
    print(type(e).__name__, str(e).split('.')[0])
UnpicklingError Weights only load failed

The safetensors Format: Zero Code, Zero-Copy mmap

Safe Weight Interchange

A safetensors file holds passive metadata and raw tensor bytes in three flat segments:

  1. 8-byte unsigned little-endian integer (<Q): Exact byte length n of the JSON header.
  2. UTF-8 JSON header (n bytes): Maps each tensor’s path name to its dtype, shape, and [begin, end] byte offsets relative to the data segment.
  3. Packed raw tensor bytes: Contiguous array buffers aligned back to back, enabling instant zero-copy memory mapping (mmap) and single-tensor random access without reading the whole file.

Saving and Auditing a safetensors File Byte by Byte

safetensors Round-Trip & Header Inspection

  • We save our MLP to mlp.safetensors, verify bit-for-bit restoration, and parse its header using standard struct and json.

Saving and Restoring a safetensors File

safetensors Round-Trip & Header Inspection

save_file(net.state_dict(), 'mlp.safetensors')
clone = MLP()
clone.load_state_dict(load_file('mlp.safetensors'))
torch.equal(clone(X), Y)

Parsing the safetensors Header by Hand

safetensors Round-Trip & Header Inspection

with open('mlp.safetensors', 'rb') as f:
    n = struct.unpack('<Q', f.read(8))[0]  # header length, little-endian
    header = json.loads(f.read(n))
print('header length:', n, 'bytes')
for name, entry in sorted(header.items(), key=lambda e: e[1]['data_offsets']):
    print(f"{name:18s} {entry['dtype']} {str(entry['shape']):10s} "
          f"bytes {entry['data_offsets']}")
header length: 296 bytes
hidden.bias        F32 [256]      bytes [0, 1024]
hidden.weight      F32 [256, 20]  bytes [1024, 21504]
output.bias        F32 [10]       bytes [21504, 21544]
output.weight      F32 [10, 256]  bytes [21544, 31784]

Why Resuming Training Requires Optimizer State

Stateful Optimization with Adam

\mathbf{w} \leftarrow \mathbf{w} - \eta \, \frac{\hat{\mathbf{m}}}{\sqrt{\hat{\mathbf{v}}} + \epsilon}

  • Why a fresh Adam spikes the loss: Discarding \mathbf{m} and \mathbf{v} on resume (\mathbf{m}_0 = \mathbf{v}_0 = \mathbf{0}) forces step-1 bias correction to set \hat{\mathbf{m}}_1 = \mathbf{g} and \hat{\mathbf{v}}_1 = \mathbf{g} \odot \mathbf{g}.
  • Full-step shock: Every parameter steps by \Delta w_i = -\eta \, \frac{g_i}{|g_i| + \epsilon} \approx \pm \eta, jumping out of the converged basin.

The Five Compartments of a Resumable Training Checkpoint

Complete Checkpoint Anatomy

  • Five required states: Model state (parameters + buffers), optimizer state (\mathbf{m}, \mathbf{v}), PRNG states (CPU, GPU, data loader), step counter t, and architecture config.
  • Crash-safe atomic writes: Always write to a temporary file (path + '.tmp') and call os.replace(tmp, path) so a crash mid-write never corrupts the previous checkpoint.

Sizing an 8B-Parameter Checkpoint: 96 GB on Disk

Checkpoint Storage Arithmetic

  • Inference file (16 GB in bf16): Stores only the 2\text{ B/param} model weights \mathbf{w}.
  • Resumable training checkpoint (96 GB in fp32): Stores weights \mathbf{w} (32 GB) + Adam \mathbf{m} (32 GB) + Adam \mathbf{v} (32 GB) = 12\text{ B/param} (6\times larger than inference; gradients \mathbf{g} are not saved to disk).

Implementing Atomic Save and Load Helpers

Crash-Safe Checkpointing in Code

  • Our save_checkpoint helper bundles all five compartments and commits them atomically via os.replace.

Atomic Save and Load Helpers in Code

Crash-Safe Checkpointing in Code

def save_checkpoint(path, model, optimizer, step, cfg=None, rng=None):
    """Atomically write a resumable training checkpoint."""
    ckpt = {'model': model.state_dict(),
            'optimizer': optimizer.state_dict(),
            'step': step,
            'cpu_rng': torch.get_rng_state()}
    if cfg is not None:
        ckpt['cfg'] = asdict(cfg)
    if rng is not None:                        # a torch.Generator
        ckpt['rng'] = rng.get_state()
    if torch.cuda.is_available():
        ckpt['cuda_rng'] = torch.cuda.get_rng_state_all()
    tmp = path + '.tmp'
    torch.save(ckpt, tmp)
    os.replace(tmp, path)

def load_checkpoint(path, model, optimizer=None, rng=None):
    """Restore the state written by save_checkpoint; return the raw dict."""
    ckpt = torch.load(path, weights_only=True)
    model.load_state_dict(ckpt['model'])
    if optimizer is not None:
        optimizer.load_state_dict(ckpt['optimizer'])
    if rng is not None:
        rng.set_state(ckpt['rng'])
    torch.set_rng_state(ckpt['cpu_rng'])
    if torch.cuda.is_available() and 'cuda_rng' in ckpt:
        torch.cuda.set_rng_state_all(ckpt['cuda_rng'])
    return ckpt

Testing Bit-for-Bit Resumption After 200 Steps

Experimental Verification

  • Restoring all five compartments reproduces steps 201–205 down to the last bit (0.0 difference), whereas omitting RNG state replays early minibatches:
for name, kwargs in (('full checkpoint', {}),
                     ('without the generator', {'restore_rng': False})):
    resumed, _ = resume(path, 205, **kwargs)
    print(f'{name:22s} max |difference| {max_diff(resumed, net):.3g}')
full checkpoint        max |difference| 0
without the generator  max |difference| 0.00397

Dropping Optimizer State Wrecks Near-Converged Models

The Fresh-Adam Loss Spike

  • Resuming from step 200 with saved weights and RNG state—but a freshly initialized Adam optimizer—makes the loss jump by roughly three orders of magnitude right after its first update:
_, full = resume(path, 205)
_, fresh = resume(path, 205, restore_optimizer=False)
print('saved optimizer:', [round(l, 4) for l in full])
print('fresh optimizer:', [round(l, 4) for l in fresh])
saved optimizer: [0.0009, 0.0017, 0.0022, 0.001, 0.0019]
fresh optimizer: [0.0009, 2.1294, 0.6979, 0.7146, 0.9511]

Loading Pretrained Backbone Weights Under a New Head

Transfer Learning Setup

When adapting an ImageNet-pretrained ResNet-50 (\sim 25\text{M} parameters, 1{,}000 classes) to a 10-class dataset, we keep the pretrained backbone and replace the final linear head (2048 -> 10):

net = resnet50(weights=ResNet50_Weights.DEFAULT)  # ~100 MB once
net.fc = nn.Linear(net.fc.in_features, 10)        # new 10-class head
net.fc
Linear(in_features=2048, out_features=10, bias=True)

Auditing Missing and Unexpected Keys on Partial Loads

Catching Silent Checkpoint Mismatches

  • When loading external weights into a modified architecture non-strictly, always inspect the missing and unexpected keys.

Reading the Key Audit of a Partial Load

Catching Silent Checkpoint Mismatches

damaged = {k: v for k, v in net.state_dict().items()
           if not k.startswith(('fc.', 'layer4.'))}
target = resnet50(weights=None)
target.fc = nn.Linear(target.fc.in_features, 10)
report = target.load_state_dict(damaged, strict=False)
print('missing by block:', dict(Counter(
    k.split('.')[0] for k in report.missing_keys)))
print('unexpected:', report.unexpected_keys)
missing by block: {'layer4': 50, 'fc': 2}
unexpected: []

Concept Check: Serialization & Checkpoint Resumption

Concept Check

Work out these three checkpointing questions:

  1. An MLP (20 \to 256 \to 10, float32) is saved to mlp.safetensors with a JSON header of n = 280 bytes. What is the exact total file size in bytes?
  2. Our 20 \to 64 \to 1 regressor has 20 \times 64 + 64 + 64 \times 1 + 1 = 1{,}409 parameters. If we resume at \eta = 0.05 with a fresh Adam optimizer (\mathbf{m}=\mathbf{v}=\mathbf{0}) and every gradient entry is nonzero, what is the Euclidean norm \|\Delta \mathbf{w}\|_2 of the very first parameter update?
  3. You rename self.fc to self.classifier in ResNet-50 and load an original pretrained checkpoint with strict=False. What appears in missing_keys and unexpected_keys?

Answers:

  1. 8 + 280 + 4 \times 7{,}946 = 32{,}072 bytes: 8-byte length prefix + 280-byte JSON header + 31{,}784 bytes for the 7{,}946 float32 parameters.
  2. \|\Delta \mathbf{w}\|_2 \approx 0.05 \sqrt{1{,}409} \approx 1.88: Every coordinate steps by \pm \eta = \pm 0.05 regardless of how small \|\mathbf{g}\|_2 is.
  3. missing_keys lists classifier.weight, classifier.bias (left random); unexpected_keys lists fc.weight, fc.bias (ignored from file).

Summary: Saving, Loading, and Pretrained Weights

Key Takeaways

  • State dicts & safetensors: Save tensor data keyed by tree path; use safetensors (8-byte length + JSON + raw bytes) for zero-RCE, zero-copy mmap sharing.
  • 5-part atomic checkpoints: Save model state, optimizer \mathbf{m}, \mathbf{v}, PRNG states, step t, and config (12\text{ B/param} = 96\text{ GB} for 8B) via .tmp + os.replace.
  • Pretrained key auditing: Assert missing_keys and unexpected_keys match only intentionally replaced layers.