5.6  Saving, Loading, and Pretrained Weights

A trained neural network is surprisingly fragile: it exists only in the memory of the process that trained it. The moment that process terminates (whether because your script finished, hit an error, tripped over a server’s power cord, or ran on a preemptible cloud instance), every learned weight vanishes unless saved to disk. For the toy models of earlier chapters, losing progress costs minutes. At modern scale, it can erase weeks of compute, and hardware failures are not rare exceptions: they are routine. Over a 54-day window of pre-training Llama 3 405B on up to 16,384 GPUs, Meta recorded 419 unexpected interruptions, roughly one every three hours (Grattafiori et al. 2024). Without reliable checkpointing and resumption, a run of that scale could never complete.

Saving weights serves a second, equally ubiquitous purpose: sharing trained models so others can run inference or fine-tune them without training from scratch (Section 32.2). Both workflows raise the same practical questions: what exactly belongs on disk, which file formats are safe to load, and how should we verify that weights match our architecture?

The answer to what to save follows directly from Section 5.2. A model consists of code plus state: the code defines the architecture and forward pass, while the state is the collection of named tensors (parameters and buffers alike) produced by training. We serialize only the state, mapping names to tensors, and reconstruct the model by instantiating the architecture in code and loading those tensors back in. Resuming an interrupted training run demands still more: besides model weights, we must save optimizer state (such as Adam’s running moments), random-number generator states, the step counter, and the architecture configuration, making a training checkpoint several times larger than an inference weight file.

In this hands-on section, we first inspect and serialize model state, then contrast unsafe pickle files with the safe safetensors format, build an atomic training checkpoint capable of bit-for-bit resumption, and finish by loading pretrained ResNet-50 weights into a modified architecture while verifying missing and unexpected keys.

import json
import os
import struct
from collections import Counter
from dataclasses import asdict, dataclass
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.models import resnet50, ResNet50_Weights
from safetensors.torch import load_file, save_file
import json
import struct
from collections import Counter
from dataclasses import asdict, dataclass
import numpy as np
import tensorflow as tf
from safetensors.tensorflow import load_file, save_file
import json
import os
import struct
from collections import Counter
from dataclasses import asdict, dataclass
import numpy as np
from mxnet import autograd, gluon, init, np as mnp, npx
from mxnet.gluon import nn
from safetensors.numpy import load_file, save_file
npx.set_np()
import json
import orbax.checkpoint as ocp
import os
import struct
from collections import Counter
from d2l.nnx_resnet import ResNet50
from dataclasses import asdict, dataclass
from flax import traverse_util
from safetensors.flax import load_file, save_file

5.6.1 Model State

Because a model contains dozens or hundreds of tensors, saving it requires storing a mapping from names to tensors. Each framework generates this mapping automatically by traversing the module tree (Section 5.1), keying every tensor by its path from the root. Below we inspect the state of a simple single-hidden-layer MLP with 256 hidden units.

collect_params() and state_dict() map dotted paths (hidden.weight, output.bias) to parameters and buffers:

net.weights lists variables carrying their layer-tree path (mlp/hidden/kernel), using explicit name= arguments to keep paths deterministic:

nnx.state returns a nested state tree keyed by module attribute paths (hidden.kernel, output.bias):

collect_params() and state_dict() map dotted paths (hidden.weight, output.bias) to parameters and buffers:

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,)}
class MLP(tf.keras.Model):
    def __init__(self):
        super().__init__(name='mlp')
        self.hidden = tf.keras.layers.Dense(256, name='hidden')
        self.out = tf.keras.layers.Dense(10, name='output')

    def call(self, x):
        return self.out(tf.nn.relu(self.hidden(x)))

net = MLP()
X = tf.random.normal((2, 20))
Y = net(X)
{v.path: tuple(v.shape) for v in net.weights}
{'mlp/hidden/kernel': (20, 256),
 'mlp/hidden/bias': (256,),
 'mlp/output/kernel': (256, 10),
 'mlp/output/bias': (10,)}
class MLP(nnx.Module):
    def __init__(self, rngs):
        self.hidden = nnx.Linear(20, 256, rngs=rngs)
        self.output = nnx.Linear(256, 10, rngs=rngs)

    def __call__(self, x):
        return self.output(nnx.relu(self.hidden(x)))

net = MLP(nnx.Rngs(d2l.get_key()))
X = jax.random.normal(d2l.get_key(), (2, 20))
Y = net(X)
params = nnx.state(net, nnx.Param)
[(path, tuple(value.shape)) for path, value in params.flat_state()]
[(('hidden', 'bias'), (256,)),
 (('hidden', 'kernel'), (20, 256)),
 (('output', 'bias'), (10,)),
 (('output', 'kernel'), (256, 10))]
class MLP(nn.Block):
    def __init__(self):
        super().__init__()
        self.hidden = nn.Dense(256, activation='relu', in_units=20)
        self.output = nn.Dense(10, in_units=256)

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

net = MLP()
net.initialize()
X = mnp.random.uniform(size=(2, 20))
Y = net(X)
{name: p.shape for name, p in net.collect_params().items()}
{'hidden.weight': (256, 20),
 'hidden.bias': (256,),
 'output.weight': (10, 256),
 'output.bias': (10,)}

Notice that this state dictionary records names, shapes, and numerical values, and nothing else. It contains no trace of the MLP class, its forward logic, or its activation function. Restoring the model therefore requires Python code that recreates the exact matching names and shapes: even renaming an attribute from output to head breaks the mapping despite computing the identical function. We show how to catch and diagnose such mismatches later in this section.

5.6.2 Pickle and safetensors

When checkpoint files never leave your own disk, almost any serialization format suffices. The moment you download pretrained weights from a public hub or accept a checkpoint from someone else, however, a security question arises: can loading that file execute arbitrary code on your machine? Unfortunately, with Python’s default serialization format, the answer is yes.

5.6.2.1 Code Execution on Load

Python’s built-in pickle module does not store passive data: it stores a bytecode program that reconstructs Python objects, and unpickling executes that program, allowing it to call any importable function. Any class can customize what pickle executes via __reduce__, returning a callable and its arguments. Our Tripwire example below benignly invokes print; a malicious checkpoint could just as easily invoke os.system.

class Tripwire:
    def __reduce__(self):  # pickle calls print(...) to rebuild the object
        return (print, ('*** payload executed while loading ***',))

torch.save writes a pickle archive; loading with weights_only=False (the default prior to PyTorch 2.6) executes the payload immediately:

NumPy uses pickle whenever it saves non-primitive Python objects; loading with allow_pickle=True executes the payload immediately:

NumPy uses pickle whenever it saves non-primitive Python objects; loading with allow_pickle=True executes the payload immediately:

NumPy uses pickle whenever it saves non-primitive Python objects; loading with allow_pickle=True executes the payload immediately:

torch.save(Tripwire(), 'tripwire.pt')
_ = torch.load('tripwire.pt', weights_only=False)  # the payload runs here
*** payload executed while loading ***
np.save('tripwire.npy', np.array(Tripwire(), dtype=object))  # pickled
_ = np.load('tripwire.npy', allow_pickle=True)  # the payload runs here
*** payload executed while loading ***
np.save('tripwire.npy', np.array(Tripwire(), dtype=object))  # pickled
_ = np.load('tripwire.npy', allow_pickle=True)  # the payload runs here
*** payload executed while loading ***
np.save('tripwire.npy', np.array(Tripwire(), dtype=object))  # pickled
_ = np.load('tripwire.npy', allow_pickle=True)  # the payload runs here
*** payload executed while loading ***

By default, the loaders reject arbitrary Python objects:

torch.load defaults to weights_only=True since PyTorch 2.6.

np.load refuses pickles unless allow_pickle=True.

np.load refuses pickles unless allow_pickle=True.

np.load refuses pickles unless allow_pickle=True.

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
try:
    np.load('tripwire.npy')  # allow_pickle=False, the default
except ValueError as e:
    print(type(e).__name__, e)
ValueError Object arrays cannot be loaded when allow_pickle=False
try:
    np.load('tripwire.npy')  # allow_pickle=False, the default
except ValueError as e:
    print(type(e).__name__, e)
ValueError Object arrays cannot be loaded when allow_pickle=False
try:
    np.load('tripwire.npy')  # allow_pickle=False, the default
except ValueError as e:
    print(type(e).__name__, e)
ValueError Object arrays cannot be loaded when allow_pickle=False

Restricted unpicklers only protect you insofar as their allowlists have no bugs, and historical vulnerabilities have bypassed even hardened restricted loaders. A file format that simply cannot encode executable instructions eliminates the entire attack surface by design.

PyTorch’s weights_only mode is such a restricted loader.

TensorFlow’s own checkpoint and Keras .weights.h5 files contain no pickle. A whole-model .keras archive can carry code, the function of a Lambda layer, which Keras refuses to run unless we pass safe_mode=False.

5.6.2.2 The safetensors Format

The safetensors format stores strictly raw tensor data and metadata—never code. Its binary layout has just three contiguous segments (Figure 5.6.1): an 8-byte little-endian integer giving the header length, a UTF-8 JSON header mapping each tensor name to its dtype, shape, and byte offsets, and the raw tensor buffers packed back to back. Loading executes zero code; the reader merely validates the JSON header and checks that every byte range stays within the file. As an added systems bonus, knowing exact byte offsets upfront enables memory-mapping (mmap) and random access to individual tensors without reading the entire file. Framework-agnostic and fast, safetensors has become the standard weight distribution format on the Hugging Face Hub.

Figure 5.6.1: The safetensors file of the MLP below as one strip of bytes: an 8-byte length, the JSON header with each tensor’s dtype, shape, and byte range, and the raw bytes of the four tensors back to back, in the order of their names. The offsets under the data are the ranges that the header records.

We save our MLP’s state to mlp.safetensors, load it into a fresh clone, and verify that both instances produce identical outputs.

save_file(net.state_dict(), 'mlp.safetensors')
clone = MLP()
clone.load_state_dict(load_file('mlp.safetensors'))
torch.equal(clone(X), Y)
True
save_file({v.path: v for v in net.weights}, 'mlp.safetensors')
clone = MLP()
clone(X)                                   # build the variables first
restored = load_file('mlp.safetensors')
for v in clone.weights:
    v.assign(restored[v.path])
bool(tf.reduce_all(clone(X) == Y))
True
def to_flat(tree):
    return {'.'.join(path): value
            for path, value in traverse_util.flatten_dict(tree).items()}

def from_flat(flat):
    return traverse_util.unflatten_dict(
        {tuple(name.split('.')): value for name, value in flat.items()})

save_file(to_flat(nnx.to_pure_dict(params)), 'mlp.safetensors')
clone = MLP(nnx.Rngs(d2l.get_key()))
clone_params = nnx.state(clone, nnx.Param)
nnx.replace_by_pure_dict(clone_params, from_flat(load_file('mlp.safetensors')))
nnx.update(clone, clone_params)
bool(jnp.array_equal(clone(X), Y))
True
state = {name: p.data().asnumpy() for name, p in net.collect_params().items()}
save_file(state, 'mlp.safetensors')
clone = MLP()
clone.load_dict({name: mnp.array(v)
                 for name, v in load_file('mlp.safetensors').items()})
(clone(X) == Y).all()
array(True)

The round trip is bit-for-bit exact. Even better, because the header is plain JSON at a fixed offset, we can inspect the file’s contents using nothing beyond Python’s standard library:

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]
header length: 312 bytes
mlp/hidden/bias    F32 [256]      bytes [0, 1024]
mlp/hidden/kernel  F32 [20, 256]  bytes [1024, 21504]
mlp/output/bias    F32 [10]       bytes [21504, 21544]
mlp/output/kernel  F32 [256, 10]  bytes [21544, 31784]
header length: 296 bytes
hidden.bias        F32 [256]      bytes [0, 1024]
hidden.kernel      F32 [20, 256]  bytes [1024, 21504]
output.bias        F32 [10]       bytes [21504, 21544]
output.kernel      F32 [256, 10]  bytes [21544, 31784]
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]

Every byte interval equals the tensor’s element count times 4 bytes (F32 = float32): the 256-entry hidden bias occupies the first 1,024 bytes, the \(256 \times 20 = 5{,}120\)-entry hidden weight occupies the next 20,480 bytes, and each block begins immediately where the previous one ends—pure tensor data with zero hidden code.

For private scratch checkpoints on your own machine, native framework formats are perfectly fine. Whenever weights cross a trust boundary—published to users or downloaded from the web—use a code-free format like safetensors paired with a cryptographic checksum so recipients can verify integrity.

5.6.3 Training Checkpoints

A bare weights file suffices for inference, but not for resuming training. The reason is stateful optimization. Most modern deep learning runs use Adam (Section 9.5), which tracks two per-parameter running averages (Section 5.2): \(\mathbf{m}\) for the gradient \(\mathbf{g}\) and \(\mathbf{v}\) for its elementwise square \(\mathbf{g} \odot \mathbf{g}\), updating each parameter opposite its smoothed gradient scaled down where recent gradients have been large:

\[ \mathbf{w} \leftarrow \mathbf{w} - \eta\, \frac{\hat{\mathbf{m}}}{\sqrt{\hat{\mathbf{v}}} + \epsilon}. \tag{5.6.1}\]

Here \(\eta\) is the learning rate, \(\epsilon\) is a small constant (typically \(10^{-8}\)), division and square root act elementwise, and the hats indicate bias-correction factors compensating for zero initialization (derived in Section 9.5). Crucially, \(\mathbf{m}\) and \(\mathbf{v}\) encode the optimization history: discard them, and Adam behaves as if training had just started from scratch.

A truly resumable training checkpoint therefore packs five distinct components (Figure 5.6.2): (1) model state (parameters and buffers), (2) optimizer state (\(\mathbf{m}\) and \(\mathbf{v}\)), (3) random-number generator states so minibatch shuffling and dropout continue seamlessly, (4) the step counter governing Adam’s bias correction and any learning-rate schedule, and (5) the model configuration needed to rebuild the architecture. Gradients are omitted because the next step recomputes them immediately. That leaves 12 of the 16 bytes per parameter held during fp32 Adam training (Section 5.2), namely weights plus two moments, so a resumable checkpoint for an 8-billion-parameter model weighs in at 96 GB: three times its 32 GB fp32 weights and six times its 16 GB bf16 inference file (Section 5.5).

Figure 5.6.2: A checkpoint file’s five compartments, each paired by an arrow with what it restores on resume: model state with the weights, optimizer state with Adam’s two running averages, RNG state with the data order and dropout, step with the position in the schedule, and config with the architecture.

Checkpointing must also be crash-safe: overwriting an existing checkpoint in place risks losing both old and new versions if the job dies mid-write. Instead, we write to a temporary file and atomically rename it over the destination once finished, guaranteeing that any reader sees either the complete previous checkpoint or the complete new one. The rename protects against a crash of the process. Surviving a power loss also takes an os.fsync on the file and on its directory, which the exercises work out.

We pack model state, optimizer state, step, asdict(cfg), and CPU/CUDA/torch.Generator RNG states into a pure-tensor/primitive dict compatible with weights_only=True, saving via a .tmp file and os.replace:

We write .params (model), .states (Trainer pickle—load only from trusted disk), and .json (step, config, and NumPy RNG state) to .tmp files before atomically replacing each with os.replace. Each file is replaced atomically, but the set of three is not: a crash between two renames pairs new parameters with old optimizer state. The exercises build a manifest that closes this gap.

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
def save_checkpoint(prefix, model, trainer, step, cfg=None, rng=None):
    """Replace each component of a resumable MXNet checkpoint."""
    meta = {'step': step}
    if cfg is not None:
        meta['cfg'] = asdict(cfg)
    if rng is not None:                        # a NumPy random generator
        meta['rng'] = rng.bit_generator.state
    model.save_parameters(prefix + '.params.tmp')
    trainer.save_states(prefix + '.states.tmp')
    with open(prefix + '.json.tmp', 'w') as f:
        json.dump(meta, f)
    for ext in ('.params', '.states', '.json'):
        os.replace(prefix + ext + '.tmp', prefix + ext)

def load_checkpoint(prefix, model, trainer=None, rng=None):
    """Restore the state written by save_checkpoint; return the metadata."""
    model.load_parameters(prefix + '.params')
    if trainer is not None:
        trainer.load_states(prefix + '.states')
    with open(prefix + '.json') as f:
        meta = json.load(f)
    if rng is not None:
        rng.bit_generator.state = meta['rng']
    return meta

To test checkpoint resumption, we train a small 64-hidden-unit MLP regressor with Adam (\(\eta = 0.05\)) on 256 noisy linear examples in 20 dimensions, drawing minibatches of 64 examples using a dedicated random generator seeded at 0 so that minibatch ordering becomes part of the checkpointed state. As in Section 5.1, a Config dataclass captures all architectural and training hyperparameters so they travel directly inside the checkpoint.

@dataclass
class Config:
    num_inputs: int = 20
    num_hiddens: int = 64
    num_outputs: int = 1
    batch_size: int = 64
    lr: float = 0.05

We train for 200 steps, write a checkpoint, and immediately continue the same run for 5 more steps to create our uninterrupted 205-step ground truth. Each call to train records the minibatch loss before each update step.

tf.train.Checkpoint bundles the model, optimizer, step variable, and tf.random.Generator into numbered checkpoint files (run-tf-1, …), paired with a .cfg.json config file. TensorFlow runs these operations on a GPU when one is visible, and on a GPU it does not add up the terms of the gradient of a bias in a fixed order; two runs can then differ in the last bits, so train runs on the CPU:

We pack the model state tree, optimizer state tree, PRNG key array, step, and config dict into one dictionary and save it atomically via Orbax (ocp.StandardCheckpointer):

def build(cfg):
    net = nn.Sequential(nn.Linear(cfg.num_inputs, cfg.num_hiddens),
                        nn.ReLU(),
                        nn.Linear(cfg.num_hiddens, cfg.num_outputs))
    for layer in (net[0], net[2]):
        nn.init.xavier_uniform_(layer.weight)
        nn.init.zeros_(layer.bias)
    return net

cfg = Config()
data = torch.randn(256, cfg.num_inputs)
target = data @ torch.randn(cfg.num_inputs, 1) + 0.1 * torch.randn(256, 1)
loss = nn.MSELoss()

def train(model, opt, rng, num_steps):
    losses = []
    for _ in range(num_steps):
        idx = torch.randint(len(data), (cfg.batch_size,), generator=rng)
        opt.zero_grad()
        l = loss(model(data[idx]), target[idx])
        l.backward()
        opt.step()
        losses.append(l.detach())
    return [l.item() for l in losses]

net = build(cfg)
opt = torch.optim.Adam(net.parameters(), lr=cfg.lr)
rng = torch.Generator().manual_seed(0)      # draws the minibatches
train(net, opt, rng, 200)
path = 'run.pt'
save_checkpoint(path, net, opt, step=200, cfg=cfg, rng=rng)
uninterrupted = train(net, opt, rng, 5)
def build(cfg):
    net = tf.keras.Sequential([             # biases start at zero
        tf.keras.layers.Dense(cfg.num_hiddens, activation='relu',
                              kernel_initializer='glorot_uniform'),
        tf.keras.layers.Dense(cfg.num_outputs,
                              kernel_initializer='glorot_uniform')])
    net(tf.zeros((1, cfg.num_inputs)))          # build the variables
    return net

cfg = Config()
data = tf.random.normal((256, cfg.num_inputs))
target = (data @ tf.random.normal((cfg.num_inputs, 1))
          + 0.1 * tf.random.normal((256, 1)))
loss = tf.keras.losses.MeanSquaredError()

def train(model, opt, rng, num_steps):
    losses = []
    with tf.device('/CPU:0'):                   # bitwise repeatable
        for _ in range(num_steps):
            idx = rng.uniform((cfg.batch_size,), maxval=len(data),
                              dtype=tf.int32)
            with tf.GradientTape() as tape:
                l = loss(tf.gather(target, idx), model(tf.gather(data, idx)))
            opt.apply_gradients(zip(tape.gradient(l, model.trainable_variables),
                                    model.trainable_variables))
            losses.append(l)
    return [float(l) for l in losses]

net = build(cfg)
opt = tf.keras.optimizers.Adam(cfg.lr)
rng = tf.random.Generator.from_seed(0)      # draws the minibatches
train(net, opt, rng, 200)
ckpt = tf.train.Checkpoint(model=net, optimizer=opt, step=tf.Variable(200),
                           rng=rng)
path = ckpt.save('run-tf')                  # a numbered save: 'run-tf-1'
with open(path + '.cfg.json', 'w') as f:
    json.dump(asdict(cfg), f)
uninterrupted = train(net, opt, rng, 5)
def build(cfg, rngs):
    xavier = nnx.initializers.xavier_uniform()  # biases start at zero
    return nnx.Sequential(
        nnx.Linear(cfg.num_inputs, cfg.num_hiddens, kernel_init=xavier,
                   rngs=rngs),
        nnx.relu,
        nnx.Linear(cfg.num_hiddens, cfg.num_outputs, kernel_init=xavier,
                   rngs=rngs))

def fresh_state(cfg):
    model = build(cfg, nnx.Rngs(d2l.get_key()))
    return model, nnx.Optimizer(model, optax.adam(cfg.lr), wrt=nnx.Param)

def checkpoint_tree(model, optimizer, key, step, cfg):
    return {'model': nnx.to_pure_dict(nnx.state(model)),
            'optimizer': nnx.to_pure_dict(nnx.state(optimizer)),
            'rng': key, 'step': step, 'cfg': asdict(cfg)}

cfg = Config()
data = jax.random.normal(d2l.get_key(), (256, cfg.num_inputs))
target = (data @ jax.random.normal(d2l.get_key(), (cfg.num_inputs, 1))
          + 0.1 * jax.random.normal(d2l.get_key(), (256, 1)))

def loss(model, X, y):
    return jnp.mean((model(X) - y) ** 2)

@nnx.jit
def step(model, optimizer, idx):
    l, grads = nnx.value_and_grad(loss)(model, data[idx], target[idx])
    optimizer.update(model, grads)
    return l

def train(model, optimizer, key, num_steps):
    losses = []
    for _ in range(num_steps):
        key, subkey = jax.random.split(key)
        idx = jax.random.randint(subkey, (cfg.batch_size,), 0, len(data))
        losses.append(step(model, optimizer, idx))
    return key, [float(l) for l in losses]

net, opt = fresh_state(cfg)
key = jax.random.key(0)                     # draws the minibatches
key, _ = train(net, opt, key, 200)
path = os.path.abspath('run-jax')           # orbax wants an absolute path
ckptr = ocp.StandardCheckpointer()
ckptr.save(path, checkpoint_tree(net, opt, key, 200, cfg), force=True)
ckptr.wait_until_finished()
key, uninterrupted = train(net, opt, key, 5)
def build(cfg):
    net = nn.Sequential()
    net.add(nn.Dense(cfg.num_hiddens, activation='relu',
                     in_units=cfg.num_inputs),
            nn.Dense(cfg.num_outputs, in_units=cfg.num_hiddens))
    net.initialize(init.Xavier())           # biases start at zero
    return net

cfg = Config()
data = mnp.random.normal(size=(256, cfg.num_inputs))
target = (data @ mnp.random.normal(size=(cfg.num_inputs, 1))
          + 0.1 * mnp.random.normal(size=(256, 1)))

def train(model, trainer, rng, num_steps):
    losses = []
    for _ in range(num_steps):
        idx = mnp.array(rng.integers(len(data), size=cfg.batch_size),
                        dtype='int32')
        with autograd.record():
            l = ((model(data[idx]) - target[idx]) ** 2).mean()
        l.backward()
        trainer.step(batch_size=1)           # the loss is already a mean
        losses.append(l)
    return [float(l) for l in losses]

net = build(cfg)
trainer = gluon.Trainer(net.collect_params(), 'adam',
                        {'learning_rate': cfg.lr})
rng = np.random.default_rng(0)              # draws the minibatches
train(net, trainer, rng, 200)
path = 'run-mx'
save_checkpoint(path, net, trainer, step=200, cfg=cfg, rng=rng)
uninterrupted = train(net, trainer, rng, 5)

Now we simulate restarting in a fresh process: resume rebuilds the model and optimizer from the saved config, optionally restores the optimizer and RNG states alongside the weights, and runs the remaining steps up to num_steps, while max_diff reports the largest elementwise weight discrepancy between two models:

Because Keras’s Adam creates its moment variables lazily on the first update, resume calls opt.build(model.trainable_variables) before restoring into the optimizer.

def resume(path, num_steps, restore_optimizer=True, restore_rng=True):
    cfg = Config(**torch.load(path, weights_only=True)['cfg'])  # saved config
    model = build(cfg)
    opt = torch.optim.Adam(model.parameters(), lr=cfg.lr)
    rng = torch.Generator().manual_seed(0)  # seeded as at the start
    ckpt = load_checkpoint(path, model, opt if restore_optimizer else None,
                           rng=rng if restore_rng else None)
    return model, train(model, opt, rng, num_steps - ckpt['step'])

def max_diff(a, b):
    return max((p - q).abs().max().item()
               for p, q in zip(a.parameters(), b.parameters()))
def resume(path, num_steps, restore_optimizer=True, restore_rng=True):
    with open(path + '.cfg.json') as f:
        cfg = Config(**json.load(f))
    model, opt = build(cfg), tf.keras.optimizers.Adam(cfg.lr)
    rng = tf.random.Generator.from_seed(0)  # seeded as at the start
    step = tf.Variable(0)
    parts = {'model': model, 'step': step}
    if restore_optimizer:
        opt.build(model.trainable_variables)  # create Adam's variables first
        parts['optimizer'] = opt
    if restore_rng:
        parts['rng'] = rng
    status = tf.train.Checkpoint(**parts).restore(path)
    status.assert_existing_objects_matched().expect_partial()
    return model, train(model, opt, rng, num_steps - int(step))

def max_diff(a, b):
    return max(float(tf.reduce_max(tf.abs(p - q)))
               for p, q in zip(a.weights, b.weights))
def load_into(obj, saved):
    state = nnx.state(obj)
    nnx.replace_by_pure_dict(state, saved)
    nnx.update(obj, state)

def resume(path, num_steps, restore_optimizer=True, restore_rng=True):
    ckpt = ckptr.restore(path)              # the saved tree, as it is
    model, opt = fresh_state(Config(**ckpt['cfg']))
    load_into(model, ckpt['model'])
    if restore_optimizer:
        load_into(opt, ckpt['optimizer'])
    key = jax.random.key(0)                 # seeded as at the start
    if restore_rng:
        key = ckpt['rng']
    _, losses = train(model, opt, key, num_steps - ckpt['step'])
    return model, losses

def max_diff(a, b):
    return max(float(jnp.abs(p - q).max()) for p, q in
               zip(jax.tree.leaves(nnx.state(a)), jax.tree.leaves(nnx.state(b))))
def resume(path, num_steps, restore_optimizer=True, restore_rng=True):
    with open(path + '.json') as f:
        cfg = Config(**json.load(f)['cfg'])  # the config travels with the run
    model = build(cfg)
    trainer = gluon.Trainer(model.collect_params(), 'adam',
                            {'learning_rate': cfg.lr})
    rng = np.random.default_rng(0)           # seeded as at the start
    meta = load_checkpoint(path, model,
                           trainer if restore_optimizer else None,
                           rng=rng if restore_rng else None)
    return model, train(model, trainer, rng, num_steps - meta['step'])

def max_diff(a, b):
    return max(float(mnp.abs(p.data() - q.data()).max()) for p, q in
               zip(a.collect_params().values(), b.collect_params().values()))

We compare restoring the full checkpoint against omitting only the random generator (restore_rng=False, as if a script simply re-seeded from 0) and measure the maximum weight discrepancy against the uninterrupted 205-step net:

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
full checkpoint        max |difference| 0
without the generator  max |difference| 0.0144
full checkpoint        max |difference| 0
without the generator  max |difference| 0.0076
full checkpoint        max |difference| 0
without the generator  max |difference| 0.00742

Restoring the full checkpoint reproduces the uninterrupted weights with zero error (bit for bit). Omitting the RNG state causes the resumed loop to replay the very first minibatches instead of drawing the next ones, introducing weight differences of roughly 0.004 to 0.02 (note that bit-for-bit equality also assumes deterministic operations, which we examine in Section 5.8).

Dropping the optimizer state is far more destructive. Below we resume with the saved weights and RNG state intact, but with a freshly constructed Adam optimizer, and compare the five post-resume minibatch losses side by side:

_, 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]
saved optimizer: [0.0033, 0.0024, 0.002, 0.0047, 0.0038]
fresh optimizer: [0.0033, 2.2394, 0.3548, 0.4566, 0.8753]
saved optimizer: [0.0026, 0.0035, 0.0017, 0.003, 0.0022]
fresh optimizer: [0.0026, 4.4987, 0.5426, 1.8454, 2.1844]
saved optimizer: [0.0008, 0.001, 0.001, 0.001, 0.0009]
fresh optimizer: [0.0008, 1.9411, 0.5375, 1.8789, 0.8948]

With the saved optimizer state, training picks up smoothly with losses hovering near 0.01 or below. With a fresh Adam optimizer, a single step blows the loss up roughly a thousandfold, and even four steps later it remains over a hundred times higher than before.

Why does one step of a fresh Adam wreck a nearly converged model? Equation Equation 5.6.1 tells the whole story. Starting from \(\mathbf{m} = \mathbf{0}\) and \(\mathbf{v} = \mathbf{0}\), Adam’s bias correction on step 1 divides out the exact initialization factor, leaving \(\hat{\mathbf{m}} = \mathbf{g}\) and \(\hat{\mathbf{v}} = \mathbf{g} \odot \mathbf{g}\). Every parameter with any nonzero gradient therefore steps by \(\eta\, |g_i| / (|g_i| + \epsilon) \approx \eta = 0.05\): the full learning rate, no matter how tiny its gradient. By contrast, the saved \(\mathbf{v}\) remembers the much larger squared gradients from earlier in training, keeping \(\sqrt{\hat{\mathbf{v}}}\) large relative to the tiny late-stage gradients so updates remain gentle. The closer a model is to convergence, the more violent an uninitialized Adam restart becomes. Weights alone are never enough to resume training.

5.6.4 Pretrained Weights

We now turn to the second major use of saved state: initializing from weights trained by someone else. A backbone trained on ImageNet (1.2 million images across 1,000 categories) learns rich visual representations that transfer cleanly to new tasks. Adapting it to a 10-class problem is simple: load every layer except the final classifier head, and swap in a fresh 10-output linear layer. Below we demonstrate this with ResNet-50 (~25 million parameters, or 23.5 million excluding its 1,000-class head). We will study convolutional networks in Chapter 6 and Chapter 7; for weight loading, ResNet-50 is simply a state dictionary of a few hundred named tensors.

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)
backbone = tf.keras.applications.ResNet50(        # ~95 MB once
    weights='imagenet', include_top=False, pooling='avg')
net = tf.keras.Sequential([backbone, tf.keras.layers.Dense(10, name='head')])
net(tf.zeros((1, 224, 224, 3)))                   # create the new head
net.layers[-1].kernel.shape
TensorShape([2048, 10])
net = ResNet50.from_pretrained()                  # ~100 MB once
net.fc = nnx.Linear(2048, 10, rngs=nnx.Rngs(d2l.get_key()))  # new head
net.fc.kernel.shape
(2048, 10)
net = gluon.model_zoo.vision.resnet50_v1(pretrained=True)  # ~100 MB once
net.output = nn.Dense(10, in_units=2048)          # new 10-class head
net.output.initialize()
net.output
Dense(2048 -> 10, linear)

External weight files rarely match a custom target model one-to-one, and silently ignoring mismatches is a notorious source of bugs. To see how a careful loader audits partial transfers, we strip two groups of tensors from our pretrained ResNet-50 state: the classification head (which we intend to replace) and the entire final stage of the backbone (simulating a corrupted or mismatched checkpoint). Loading the remaining tensors into a fresh 10-class ResNet-50 lets us inspect two diagnostic sets: missing keys (model parameters absent from the file, left randomly initialized) and unexpected keys (file entries unused by the model).

load_state_dict(..., strict=False) loads matching keys and returns (missing_keys, unexpected_keys) directly:

We compute the missing and unexpected keys as set differences between the model’s parameter paths and the checkpoint’s keys:

We compute the missing and unexpected keys as set differences between the model’s parameter paths and the checkpoint’s keys:

We compute the missing and unexpected keys as set differences between the model’s parameter paths and the checkpoint’s keys:

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: []
damaged = {v.path: v for v in backbone.weights
           if not v.path.startswith('conv5_')}
target = tf.keras.Sequential([
    tf.keras.applications.ResNet50(weights=None, include_top=False,
                                   pooling='avg'),
    tf.keras.layers.Dense(10, name='head')])
target(tf.zeros((1, 224, 224, 3)))
for v in target.weights:
    if v.path in damaged:
        v.assign(damaged[v.path])         # raises if the shapes differ
paths = {v.path for v in target.weights}
print('missing by block:', dict(Counter(
    p.split('/')[-2].split('_')[0] for p in sorted(paths - set(damaged)))))
print('unexpected:', sorted(set(damaged) - paths))
missing by block: {'conv5': 60, 'head': 2}
unexpected: []
def flat_state(model):
    return traverse_util.flatten_dict(nnx.to_pure_dict(nnx.state(model)))

damaged = {path: v for path, v in flat_state(net).items()
           if path[0] != 'fc' and path[:2] != ('stages', 3)}
target = ResNet50(num_classes=10, rngs=nnx.Rngs(d2l.get_key()))
fresh = flat_state(target)
state = nnx.state(target)
nnx.replace_by_pure_dict(state, traverse_util.unflatten_dict(
    {**fresh, **{p: v for p, v in damaged.items() if p in fresh}}))
nnx.update(target, state)
print('missing by block:', dict(Counter(
    f'stages.{p[1]}' if p[0] == 'stages' else p[0]
    for p in sorted(set(fresh) - set(damaged)))))
print('unexpected:', sorted(set(damaged) - set(fresh)))
missing by block: {'fc': 2, 'stages.3': 50}
unexpected: []
damaged = {name: p.data() for name, p in net.collect_params().items()
           if not name.startswith(('output', 'features.7'))}
target = gluon.model_zoo.vision.resnet50_v1(classes=10)
target.initialize()
target.load_dict(damaged, allow_missing=True, ignore_extra=True)  # silent
names = set(target.collect_params())
print('missing by block:', dict(Counter(
    '.'.join(k.split('.')[:2]) if k.startswith('features') else k.split('.')[0]
    for k in sorted(names - set(damaged)))))
print('unexpected:', sorted(set(damaged) - names))
missing by block: {'features.7': 56, 'output': 2}
unexpected: []

Missing keys for the new 10-class head’s weight and bias are expected, since that head starts from random initialization. The missing keys from the final backbone stage are a red flag: had we loaded blindly with partial matching, a huge chunk of our “pretrained” ResNet-50 would silently remain random noise. Here the unexpected set is empty; a nonempty unexpected set typically signals a renamed module whose weights were never loaded. In production code, always assert explicitly that the missing and unexpected sets match only the layers you intended to replace or drop, raising an error on anything else.

Once verified, transfer learning typically begins by freezing the pretrained backbone (Section 5.2.3.2) so initial updates train only the new head, before selectively unfreezing deeper layers (Section 32.2).

Everything in this chapter so far has lived in host CPU memory. In Section 5.7, we move both state and computation onto GPUs.

5.6.5 Summary

Persisting a model saves its state (a dictionary mapping module-tree paths to parameter and buffer tensors), while the architecture itself lives in code. Because Python’s pickle executes arbitrary code on load, weights shared across trust boundaries should use a code-free format such as safetensors (an 8-byte length prefix, a JSON header, and packed tensor bytes). Crash-safe training checkpoints write atomically via temporary files and capture five components: model state, optimizer state, RNG state, step counter, and config. Restoring all five resumes training bit for bit; dropping RNG state drifts the data stream, and dropping Adam’s moments causes the first resumed step to move every parameter by the full learning rate, spiking the loss by orders of magnitude. When loading pretrained weights into a modified architecture, always audit the missing and unexpected key sets against your expectations rather than ignoring mismatches silently.

5.6.6 Exercises

  1. [code] Safetensors header. The header length of the MLP’s safetensors file is the 8-byte little-endian integer at the start of the file (Figure 5.6.1).
    1. Predict, then measure, how that length changes when the hidden width is doubled and when a third layer is added. Explain which parts of the header depend on tensor sizes at all.
    2. Read the hidden layer’s bias from the file using only the header and file seeks, without the safetensors library. Decode the bytes with the dtype and shape that the header records, and check that the result equals the tensor that load_file returns.
    3. Explain why a pickle-based checkpoint cannot offer the same single-tensor read without deserializing the whole object graph.
  2. [code] Partial loading. Define MLP2, a copy of MLP that inserts a second hidden layer hidden2 of width 256 before the output layer and renames the attribute output to head.
    1. Load mlp.safetensors into MLP2 with load_state_dict(..., strict=False). Read the returned report and explain each missing and each unexpected key.
    2. Rename the file’s keys to the names that MLP2 uses before loading. Confirm that only hidden2 keeps its fresh initialization, and make the load raise on any unexpected key and on any missing key outside hidden2.
    Adapted from Matthew Inkawhich, Saving and Loading Models, “Warmstarting Model Using Parameters from a Different Model”.
  3. [code] Dtype round trip. ● A float16 number stores 5 exponent bits and 10 mantissa bits, against 8 and 23 in float32 (Section 5.5). Cast the parameters of an MLP to float16, save them, and load them back into a float32 MLP.
    1. Predict the largest relative error of a restored parameter from the mantissa width. Measure the maximum absolute difference and, over the nonzero parameters, the maximum relative difference between the restored and the original values. Explain any parameter whose relative error exceeds the prediction.
    2. Compare the outputs of the original and the restored MLP on X, and decide whether the round trip is acceptable for inference.
    3. Adam keeps a running average of squared gradients. Compute what float16 stores for the square of a gradient entry of \(10^{-4}\), and explain why a resumable checkpoint keeps the optimizer state in float32.
  4. [extended] Crash-safe manifest. ●
    1. Build a utility that writes model state, optimizer state, and a JSON metadata file under a fresh step-numbered prefix, then publishes the three by renaming into place one manifest that records each file’s name, size, and checksum.
    2. Simulate two failures: a crash after the three files are written but before the manifest rename, and the truncation of one file of a published checkpoint. Show that reloading resumes from the previous complete checkpoint in the first case and rejects the corrupt checkpoint in the second.
    3. A rename is atomic, so a reader sees either the old manifest or the new one. POSIX does not require the data of the renamed files to reach the disk before the rename does. os.fsync forces the buffered writes of a file, or of a directory’s entries, to disk. State where the utility must call os.fsync so that a power loss leaves either the previous checkpoint or the new one intact, and explain each call.
  1. [code] Safetensors header. The header length of the MLP’s safetensors file is the 8-byte little-endian integer at the start of the file (Figure 5.6.1).
    1. Predict, then measure, how that length changes when the hidden width is doubled and when a third layer is added. Explain which parts of the header depend on tensor sizes at all.
    2. Read the hidden layer’s bias from the file using only the header and file seeks, without the safetensors library. Decode the bytes with the dtype and shape that the header records, and check that the result equals the tensor that load_file returns.
    3. Explain why a pickle-based checkpoint cannot offer the same single-tensor read without deserializing the whole object graph.
  2. [code] Partial loading. Define MLP2, a copy of MLP that inserts a second hidden layer named hidden2 of width 256 before the output layer and names the output layer head instead of output.
    1. Load mlp.safetensors into MLP2 by assigning each variable whose path appears in the file. List the variables that keep their fresh initialization and the file entries that find no variable, and explain each.
    2. Rename the file’s keys to the paths that MLP2 uses before assigning. Confirm that only hidden2 keeps its fresh initialization, and make the load raise on any unexpected key and on any missing path outside hidden2.
    Adapted from Matthew Inkawhich, Saving and Loading Models, “Warmstarting Model Using Parameters from a Different Model”.
  3. [code] Dtype round trip. ● A float16 number stores 5 exponent bits and 10 mantissa bits, against 8 and 23 in float32 (Section 5.5). Cast the parameters of an MLP to float16, save them, and load them back into a float32 MLP.
    1. Predict the largest relative error of a restored parameter from the mantissa width. Measure the maximum absolute difference and, over the nonzero parameters, the maximum relative difference between the restored and the original values. Explain any parameter whose relative error exceeds the prediction.
    2. Compare the outputs of the original and the restored MLP on X, and decide whether the round trip is acceptable for inference.
    3. Adam keeps a running average of squared gradients. Compute what float16 stores for the square of a gradient entry of \(10^{-4}\), and explain why a resumable checkpoint keeps the optimizer state in float32.
  4. [extended] Crash-safe manifest. ●
    1. Build a utility that writes model state, optimizer state, and a JSON metadata file under a fresh step-numbered prefix, then publishes the three by renaming into place one manifest that records each file’s name, size, and checksum.
    2. Simulate two failures: a crash after the three files are written but before the manifest rename, and the truncation of one file of a published checkpoint. Show that reloading resumes from the previous complete checkpoint in the first case and rejects the corrupt checkpoint in the second.
    3. A rename is atomic, so a reader sees either the old manifest or the new one. POSIX does not require the data of the renamed files to reach the disk before the rename does. os.fsync forces the buffered writes of a file, or of a directory’s entries, to disk. State where the utility must call os.fsync so that a power loss leaves either the previous checkpoint or the new one intact, and explain each call.
  1. [code] Safetensors header. The header length of the MLP’s safetensors file is the 8-byte little-endian integer at the start of the file (Figure 5.6.1).
    1. Predict, then measure, how that length changes when the hidden width is doubled and when a third layer is added. Explain which parts of the header depend on tensor sizes at all.
    2. Read the hidden layer’s bias from the file using only the header and file seeks, without the safetensors library. Decode the bytes with the dtype and shape that the header records, and check that the result equals the tensor that load_file returns.
    3. Explain why a pickle-based checkpoint cannot offer the same single-tensor read without deserializing the whole object graph.
  2. [code] Partial loading. Define MLP2, a copy of MLP that inserts a second hidden layer hidden2 of width 256 before the output layer and renames the attribute output to head.
    1. Load mlp.safetensors into MLP2 with a key-set merge like the one that loads the damaged ResNet-50 state. Report the missing and unexpected key sets, and explain each entry.
    2. Rename the file’s keys to the names that MLP2 uses before the merge. Confirm that only hidden2 keeps its fresh initialization, and make the merge raise on any unexpected key and on any missing key outside hidden2.
    Adapted from Matthew Inkawhich, Saving and Loading Models, “Warmstarting Model Using Parameters from a Different Model”.
  3. [code] Dtype round trip. ● A float16 number stores 5 exponent bits and 10 mantissa bits, against 8 and 23 in float32 (Section 5.5). Cast the parameters of an MLP to float16, save them, and load them back into a float32 MLP.
    1. Predict the largest relative error of a restored parameter from the mantissa width. Measure the maximum absolute difference and, over the nonzero parameters, the maximum relative difference between the restored and the original values. Explain any parameter whose relative error exceeds the prediction.
    2. Compare the outputs of the original and the restored MLP on X, and decide whether the round trip is acceptable for inference.
    3. Adam keeps a running average of squared gradients. Compute what float16 stores for the square of a gradient entry of \(10^{-4}\), and explain why a resumable checkpoint keeps the optimizer state in float32.
  4. [extended] Crash-safe manifest. ●
    1. Build a utility that writes model state, optimizer state, and a JSON metadata file under a fresh step-numbered prefix, then publishes the three by renaming into place one manifest that records each file’s name, size, and checksum.
    2. Simulate two failures: a crash after the three files are written but before the manifest rename, and the truncation of one file of a published checkpoint. Show that reloading resumes from the previous complete checkpoint in the first case and rejects the corrupt checkpoint in the second.
    3. A rename is atomic, so a reader sees either the old manifest or the new one. POSIX does not require the data of the renamed files to reach the disk before the rename does. os.fsync forces the buffered writes of a file, or of a directory’s entries, to disk. State where the utility must call os.fsync so that a power loss leaves either the previous checkpoint or the new one intact, and explain each call.
  1. [code] Safetensors header. The header length of the MLP’s safetensors file is the 8-byte little-endian integer at the start of the file (Figure 5.6.1).
    1. Predict, then measure, how that length changes when the hidden width is doubled and when a third layer is added. Explain which parts of the header depend on tensor sizes at all.
    2. Read the hidden layer’s bias from the file using only the header and file seeks, without the safetensors library. Decode the bytes with the dtype and shape that the header records, and check that the result equals the tensor that load_file returns.
    3. Explain why a pickle-based checkpoint cannot offer the same single-tensor read without deserializing the whole object graph.
  2. [code] Partial loading. Define MLP2, a copy of MLP that inserts a second hidden layer hidden2 of width 256 before the output layer and renames the attribute output to head.
    1. Load mlp.safetensors into MLP2 with load_dict(..., allow_missing=True, ignore_extra=True). Compute the missing and unexpected key sets, and explain each entry.
    2. Rename the file’s keys to the names that MLP2 uses before loading. Confirm that only hidden2 keeps its fresh initialization, and make the load raise on any unexpected key and on any missing key outside hidden2.
    Adapted from Matthew Inkawhich, Saving and Loading Models, “Warmstarting Model Using Parameters from a Different Model”.
  3. [code] Dtype round trip. ● A float16 number stores 5 exponent bits and 10 mantissa bits, against 8 and 23 in float32 (Section 5.5). Cast the parameters of an MLP to float16, save them, and load them back into a float32 MLP.
    1. Predict the largest relative error of a restored parameter from the mantissa width. Measure the maximum absolute difference and, over the nonzero parameters, the maximum relative difference between the restored and the original values. Explain any parameter whose relative error exceeds the prediction.
    2. Compare the outputs of the original and the restored MLP on X, and decide whether the round trip is acceptable for inference.
    3. Adam keeps a running average of squared gradients. Compute what float16 stores for the square of a gradient entry of \(10^{-4}\), and explain why a resumable checkpoint keeps the optimizer state in float32.
  4. [extended] Crash-safe manifest. ●
    1. Build a utility that writes model state, optimizer state, and a JSON metadata file under a fresh step-numbered prefix, then publishes the three by renaming into place one manifest that records each file’s name, size, and checksum.
    2. Simulate two failures: a crash after the three files are written but before the manifest rename, and the truncation of one file of a published checkpoint. Show that reloading resumes from the previous complete checkpoint in the first case and rejects the corrupt checkpoint in the second.
    3. A rename is atomic, so a reader sees either the old manifest or the new one. POSIX does not require the data of the renamed files to reach the disk before the rename does. os.fsync forces the buffered writes of a file, or of a directory’s entries, to disk. State where the utility must call os.fsync so that a power loss leaves either the previous checkpoint or the new one intact, and explain each call.

Discussions