Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 20 min · revision 2

Worked Example: Checkpoint, Crash, Resume

Save a complete training checkpoint (model, optimizer, scheduler, epoch and random-number-generator states) atomically, kill the run in the middle of an epoch, resume it, and prove that the resumed run ends with exactly the same weights as an uninterrupted one; then see what goes wrong when only part of the state is restored.

Contentsand lesson path

What you will learn

  • Checkpoint and resume training with model, optimizer, scheduler and random-number-generator state, and get repeatable results from fixed seeds.

Prerequisites: Deep Learning Fundamentals

01. The problem

Long training runs get interrupted: a spot instance is reclaimed, a job hits its time limit, a node fails. A checkpoint is a file that holds enough of the training state to continue from where it stopped. The question this worked example answers is: how much state is enough? The test is strict. A run that is killed and resumed should end with the same weights as a run that was never interrupted, not just similar ones. If it does not, you cannot tell whether a change in results came from your experiment or from the interruption.

The setting is small so that every step runs in seconds on a CPU: a two-layer network with dropout (which zeroes random activations during training, so it consumes random numbers), the AdamW optimizer, a one-cycle learning-rate schedule that warms up and then decays the rate once per batch, and a DataLoader that shuffles with its own seeded generator. All of these carry state that changes as training goes on.

You need Python 3.12 and PyTorch 2 (CPU build is fine), as in the DataLoader lab. Your numbers may differ from the ones below in the last digits on another CPU or PyTorch version; what must hold on your machine is that the uninterrupted and the resumed run agree exactly with each other.

Terminal
mkdir resume-demo && cd resume-demo
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install "torch==2.15.*" \
  --index-url https://download.pytorch.org/whl/cpu

02. Step 1: A training script that checkpoints every epoch

Read the script before running it. Three parts do the work.

seed_everything fixes the starting point. torch.manual_seed seeds the CPU generator and every GPU. torch.use_deterministic_algorithms(True) makes PyTorch raise an error for any operation that has no deterministic implementation, instead of silently giving slightly different results each run, and cudnn.benchmark = False stops cuDNN on a GPU from picking its convolution algorithm by timing, which can differ between runs. Seeds alone only make the start repeatable; resuming needs the state at the moment of the checkpoint.

save_checkpoint stores that state as a dictionary: the state_dict() of the model, the optimizer and the scheduler, the epoch number, and three random-number-generator states (the global PyTorch generator used by dropout, Python's random module and the loader's own generator that drives shuffling). It writes to a temporary file and then calls os.replace, which swaps the new file in with one atomic rename. If the process dies while writing, the previous checkpoint is still intact.

The --resume branch loads the file with weights_only=True, which only accepts tensors and plain Python data, so a checkpoint from an untrusted source cannot run code while it is unpickled. --restore lets you choose how much state to put back, for the experiments in step 5, and --crash-in-epoch kills the process in the middle of an epoch with os._exit(1), which, like a real crash, skips all clean-up.

Python · train.py
"""Train for 6 epochs with full checkpoints; can crash on purpose and resume."""
import argparse
import os
import random

import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

EPOCHS, STEPS_PER_EPOCH = 6, 8


def seed_everything(seed):
    random.seed(seed)
    torch.manual_seed(seed)  # seeds the CPU and every CUDA device
    torch.use_deterministic_algorithms(True)  # error on non-deterministic ops
    torch.backends.cudnn.benchmark = False  # no run-to-run kernel choice on GPUs


def make_data():
    g = torch.Generator().manual_seed(123)
    x = torch.randn(640, 20, generator=g)
    y = (x[:, :4].sum(1) + 0.5 * torch.randn(640, generator=g) > 0).long()
    return TensorDataset(x[:512], y[:512]), TensorDataset(x[512:], y[512:])


def save_checkpoint(path, **state):
    tmp = path + ".tmp"
    torch.save(state, tmp)
    os.replace(tmp, path)  # atomic: the old file stays valid until this line


def main(args):
    seed_everything(0)
    train_ds, val_ds = make_data()
    loader_gen = torch.Generator().manual_seed(0)
    train = DataLoader(train_ds, batch_size=64, shuffle=True, generator=loader_gen)
    model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Dropout(0.3),
                          nn.Linear(64, 2))
    opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
    sched = torch.optim.lr_scheduler.OneCycleLR(
        opt, max_lr=3e-3, total_steps=EPOCHS * STEPS_PER_EPOCH)
    start = 1
    if args.resume:
        ckpt = torch.load(args.resume, weights_only=True)  # tensors and plain data only
        model.load_state_dict(ckpt["model"])
        if args.restore in ("all", "no-rng"):
            opt.load_state_dict(ckpt["optimizer"])
            sched.load_state_dict(ckpt["scheduler"])
        if args.restore == "all":
            torch.set_rng_state(ckpt["torch_rng"])  # dropout masks
            random.setstate(ckpt["python_rng"])
            loader_gen.set_state(ckpt["loader_rng"])  # shuffle order
        start = ckpt["epoch"] + 1
        print(f"resumed at epoch {start}, restored: {args.restore}")
    for epoch in range(start, EPOCHS + 1):
        model.train()
        for step, (x, y) in enumerate(train, start=1):
            if epoch == args.crash_in_epoch and step == 5:
                print(f"crash in epoch {epoch}, step {step}", flush=True)
                os._exit(1)  # simulate a killed process: no clean-up at all
            loss = nn.functional.cross_entropy(model(x), y)
            opt.zero_grad()
            loss.backward()
            opt.step()
            sched.step()  # per batch, as OneCycleLR expects
        model.eval()
        with torch.no_grad():
            x, y = val_ds.tensors
            val_loss = nn.functional.cross_entropy(model(x), y).item()
        print(f"epoch {epoch}: lr {sched.get_last_lr()[0]:.2e}, "
              f"val loss {val_loss:.6f}")
        save_checkpoint(
            "ckpt.pt", epoch=epoch, model=model.state_dict(),
            optimizer=opt.state_dict(), scheduler=sched.state_dict(),
            torch_rng=torch.get_rng_state(), python_rng=random.getstate(),
            loader_rng=loader_gen.get_state())
    checksum = sum(p.double().sum().item() for p in model.parameters())
    print(f"final weight checksum {checksum:.10f}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--resume")
    parser.add_argument("--crash-in-epoch", type=int, default=0)
    parser.add_argument("--restore", choices=["all", "no-rng", "model"], default="all")
    main(parser.parse_args())

03. Step 2: The reference run

First run the whole training without interruption. The weight checksum at the end, the sum of every weight in double precision, is a cheap fingerprint: two runs with different weights almost never give the same ten decimals.

Terminal
python train.py
Expected output
epoch 1: lr 1.99e-03, val loss 0.709704
epoch 2: lr 2.96e-03, val loss 0.652105
epoch 3: lr 2.32e-03, val loss 0.601092
epoch 4: lr 1.25e-03, val loss 0.557262
epoch 5: lr 3.10e-04, val loss 0.537033
epoch 6: lr 6.56e-06, val loss 0.534084
final weight checksum -4.1246735547

The learning rate rises to its peak around epoch 2 and decays to almost zero by epoch 6, as a one-cycle schedule should. The validation loss falls from 0.71 to 0.534. Save this output: it is what the resumed run has to match.

04. Step 3: Crash in the middle of epoch 4

Terminal
python train.py --crash-in-epoch 4; echo "exit code $?"
cp ckpt.pt ckpt-epoch3.pt
Expected output
epoch 1: lr 1.99e-03, val loss 0.709704
epoch 2: lr 2.96e-03, val loss 0.652105
epoch 3: lr 2.32e-03, val loss 0.601092
crash in epoch 4, step 5
exit code 1

The run completed epochs 1 to 3, saving a checkpoint after each, and died four batches into epoch 4. The flush=True on the crash message matters: os._exit does not flush Python's output buffers, so without it the last line would be lost when output goes to a file or a pipe, exactly as log lines are lost in real crashes. The copy ckpt-epoch3.pt keeps the checkpoint for the experiments in step 5.

The four batches of epoch 4 are lost: the checkpoint only knows the state at the end of epoch 3, so the resumed run will redo epoch 4 from its first batch. Checkpointing more often loses less work but costs time for every save; resuming from the middle of an epoch is possible but also needs the position inside the epoch and the loader state.

Python · inspect_ckpt.py
import torch

ckpt = torch.load("ckpt.pt", weights_only=True)
print("keys:", ", ".join(ckpt))
print("epoch:", ckpt["epoch"])
state = ckpt["optimizer"]["state"][0]  # AdamW state of the first weight matrix
print("AdamW state per parameter:", {k: tuple(v.shape) for k, v in state.items()})
print("scheduler position:", ckpt["scheduler"]["last_epoch"], "steps")
print("RNG states:", {k: tuple(ckpt[k].shape) for k in ("torch_rng", "loader_rng")})
Terminal
python inspect_ckpt.py
Expected output
keys: epoch, model, optimizer, scheduler, torch_rng, python_rng, loader_rng
epoch: 3
AdamW state per parameter: {'step': (), 'exp_avg': (64, 20), 'exp_avg_sq': (64, 20)}
scheduler position: 24 steps
RNG states: {'torch_rng': (5056,), 'loader_rng': (5056,)}

The checkpoint holds more than weights. For every parameter, AdamW keeps a step count and two tensors of the parameter's shape, exp_avg and exp_avg_sq, the running averages of the gradient and of its square. The scheduler knows it has taken 24 of its 48 steps. The generator states are byte tensors that capture where each random sequence currently is.

05. Step 4: Resume with the full state

Terminal
python train.py --resume ckpt.pt
Expected output
resumed at epoch 4, restored: all
epoch 4: lr 1.25e-03, val loss 0.557262
epoch 5: lr 3.10e-04, val loss 0.537033
epoch 6: lr 6.56e-06, val loss 0.534084
final weight checksum -4.1246735547

Epochs 4 to 6 print the same learning rates and validation losses as the reference run, to six decimals, and the final checksum is identical. The interruption left no trace. That is the standard to hold a resume path to, and it is easy to test in continuous integration with a run of a few steps.

06. Step 5: What partial restores do

Now resume from the same epoch-3 checkpoint twice more: once restoring only the model weights, and once restoring model, optimizer and scheduler but none of the generator states.

Terminal
cp ckpt-epoch3.pt ckpt.pt && python train.py --resume ckpt.pt --restore model
cp ckpt-epoch3.pt ckpt.pt && python train.py --resume ckpt.pt --restore no-rng
Expected output
resumed at epoch 4, restored: model
epoch 4: lr 1.99e-03, val loss 0.584929
epoch 5: lr 2.96e-03, val loss 0.527521
epoch 6: lr 2.32e-03, val loss 0.468804
final weight checksum -4.8261786338
resumed at epoch 4, restored: no-rng
epoch 4: lr 1.25e-03, val loss 0.557258
epoch 5: lr 3.10e-04, val loss 0.536847
epoch 6: lr 6.56e-06, val loss 0.533997
final weight checksum -4.1565630166

With only the weights, a fresh optimizer and a fresh schedule start at epoch 4. The learning rate jumps back to 1.99e-03, the value from epoch 1, and at the end of epoch 6 it is still high instead of near zero: the run never finishes its decay. AdamW also restarts with empty running averages, so its first steps are scaled differently from the steps it would have taken. Here the validation loss even ends lower (0.469), because the run got extra high-rate training; in other runs the restart causes a loss spike instead. Either way you are now running a different experiment from the one you planned, and its results cannot be compared with the reference.

Without the generator states, everything about the schedule and the optimizer is right, but dropout draws different masks and the loader shuffles epochs 4 to 6 in a different order. The losses agree to three or four decimals and then drift, and the checksum differs. That small drift is the kind that makes two "identical" runs disagree and wastes an afternoon of debugging.

07. Check your understanding

Practice check · 3 questions

Checkpoints and resuming

Use the script and the runs of this worked example.

Q1. `save_checkpoint` writes `ckpt.pt.tmp` and then calls `os.replace(tmp, path)`. Which failure does this protect against?
Q2. In step 5, the run resumed with `--restore model` ends with a validation loss of 0.469, lower than the 0.534 of the reference run. Why is it still the wrong way to resume?
Q3. A teammate stores a dataclass with the run settings inside the checkpoint, and `torch.load(path, weights_only=True)` now fails with "Unsupported global". What is the safest fix?
Practice only: not graded, not saved, not evidence.

08. Apply it

In your practice package:

  1. Add save_checkpoint and a resume function that restore model, optimizer, scheduler, epoch, scaler (if used) and every generator your code uses.
  2. Write a test that trains for 3 epochs, crashes in epoch 2, resumes and checks that the final weights equal those of an uninterrupted 3-epoch run.
  3. Run your real training once interrupted and once not, and report how far apart the final validation metrics are. Explain any gap.

09. Review prompt

Without looking back, list everything a complete checkpoint holds and what goes wrong without each part; explain why the checkpoint is written to a temporary file first; explain what seeds alone guarantee and what they do not; describe what torch.use_deterministic_algorithms(True) changes; and state what happens to the work done between the last checkpoint and a crash.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check