Module contents
Lesson 21 of 24Core 60 min

Checkpoints, safe serialization and exact resumption

Design a complete training checkpoint, including model, optimizer, scheduler, GradScaler, RNG states, DataLoader progress and configuration, with atomic writes and rotation for exact resumption. Learn about restricted weights_only loading and safetensors.

After this lesson you can

  • List and save all state needed to resume training.
  • Write checkpoints atomically using a temporary file and rename, with rotation and best-checkpoint tracking.
  • Resume training and verify its trajectory matches an uninterrupted run.
  • Explain untrusted pickle execution risk and use weights_only and safetensors.
  • Separate resumption checkpoints from weights for distribution.

Before you start

Motivation: hour seven of an eight-hour training run

You launch an eight-hour training run overnight on the lab laptop. At hour seven, Windows decides to install an update and restarts; or the lid closes and the machine sleeps; or the process dies from an error evaluating the final segment. If you saved nothing, seven hours are lost. If you saved torch.save(model.state_dict(), "ckpt.pt") every hour, you think at most one is lost. Reality is worse than it appears for three reasons this lesson unpacks one by one.

First: a state_dict is not training. Resuming with hour-six weights and a newly created optimizer, Adam has forgotten its moments and step counter, the scheduler returns to the start of warmup, and data shuffling begins another epoch. Loss jumps, learning rate rises when it should fall and, at best, the final result resembles the uninterrupted one; at worst, training diverges. Even if it resembles it, you can no longer compare experiments confident that the only difference is the one you introduced.

Second: saving can destroy what you already had. open("ckpt.pt", "wb") truncates the file to zero bytes as soon as it opens. If power fails during the seconds it takes to write a gigabyte checkpoint, neither the old nor new version remains on disk.

Third: someone else’s checkpoint is not a harmless data file. torch.save uses Python’s pickle format, and Python documentation warns that loading an untrusted pickle can execute code. That is why torch.load now defaults to restricted mode and publicly distributed weights travel in a different format, safetensors.

By the end you will know how to design a complete checkpoint, write it so an interruption cannot destroy it, resume with a trajectory matching an uninterrupted run bit for bit, and load third-party weights with appropriate protections. We build on the state_dict, optimizer API, schedulers, samplers, mixed precision with GradScaler and complete seeding you already know.

What to save

Training is a process with memory. Between steps, not only weights change: optimizer moments, scheduler counter, GradScaler scale, each random generator’s state and position in data traversal change. Everything the next step reads that the preceding step wrote is state, and all state must be in the checkpoint.

The concrete list and what each PyTorch component returns:

ComponentHow to obtain itWhat happens if missing
Weightsmodel.state_dict()Model restarts
Optimizeropt.state_dict(): Adam moments mm, vv and step counter, and param_groups with current lrAdam starts from zero and its first step measures η\eta in each coordinate
Schedulersched.state_dict(): last_epoch and latest learning ratesLearning rate returns to warmup
GradScalerscaler.state_dict(): current scale and growth counterScale returns to 2162^{16}; first steps may overflow and be skipped
Python, NumPy and PyTorch RNGrandom.getstate(), np.random.get_state(), torch.get_rng_state()Different dropout masks and augmentation noise
CUDA RNGtorch.cuda.get_rng_state_all(), one per GPUDifferent GPU dropout even if CPU is correct
Dataepoch, batch within epoch and sampler state (or seed)Batches repeat or are skipped in another order
Metadatastep, metric, git commit, configuration as dict, versionsYou cannot know what code and hyperparameters produced the file

Two components deserve comment. Gradients are absent from the list: the loop calls zero_grad() before each backward, so the next step does not read the previous one’s (if accumulating gradients over several microbatches, save only at a complete accumulation boundary). And configuration is stored as a basic-type dictionary, for example with asdict(cfg) on a dataclass, not as the object: a checkpoint containing instances of your own classes cannot load in torch.load restricted mode and breaks on refactoring.

Resuming means applying the same function again

The idea organizing the lesson is that deterministic training is a discrete dynamical system. Let S\mathcal{S} be the set of all possible states (weights, moments, counters, generator states, data position) and st∈Ss_t \in \mathcal{S} state after tt steps. One training step is a function

st+1=F(st),F:S→S,s_{t+1} = F(s_t), \qquad F : \mathcal{S} \to \mathcal{S},

that reads the batch dictated by position saved in sts_t, draws dropout masks with the generator saved in sts_t, computes gradient and updates everything. Saving a checkpoint applies a projection π\pi keeping some state components; resuming reconstructs state ρ(π(sk))\rho(\pi(s_k)) from the file and what the script does at startup.

Proof

By induction on jj. For j=0j = 0, r0=ρ(π(sk))=skr_0 = \rho(\pi(s_k)) = s_k by hypothesis. If rj=sk+jr_j = s_{k+j}, then rj+1=F(rj)=F(sk+j)=sk+j+1r_{j+1} = F(r_j) = F(s_{k+j}) = s_{k+j+1}, where the second equality uses FF being a function: two calls with the same argument give the same result. The converse is an observation, not a theorem: if r0=s~k≠skr_0 = \tilde s_k \neq s_k, the trajectory already differs at j=0j = 0, and if the differing component is one FF reads, images generally differ too. It might not matter (a generator nobody uses anymore), but this cannot be assumed.

∎

The proof is trivial; its two assumptions are not. Restoration recovering all state is the table above and the checkpoint’s responsibility. FF being a function is a software and hardware property: kernels must be deterministic (in CUDA, operations accumulating with atomic adds, like index_add_ or scatter_add_, add in an order depending on thread scheduling; torch.use_deterministic_algorithms(True) replaces them with deterministic versions or errors), PyTorch, cuBLAS and cuDNN versions and GPU must not change (another version may choose another algorithm and sum in another order), cudnn.benchmark must not choose different algorithms at each startup, and nothing may depend on the clock or external state. With those conditions, bitwise equality is not an ideal: this lesson’s lab achieves it on RTX 4060 with mixed precision.

Why insist on exactness if approximate resumption gives a “statistically equivalent” model? Because exactness makes resumption testable. If the resumed curve matches the continuous one bit for bit, the checkpoint is complete; if it does not, something is missing and the size and shape of deviation show what. Without that reference, a checkpoint missing the scheduler and a complete one are indistinguishable until comparing final results that can no longer be attributed to anything.

InteractiveExact or approximate resumption?
  • uninterrupted reference
  • resumed from checkpoint
  • interruption
Training loss (logarithmic scale)0.2110050100150200250300Learning rate η00.0250.05050100150200250300Distance to reference ‖θ − θ_ref‖10⁻⁴10⁻²1050100150200250300exactly 0
Jump. Adam starts with m=v=0m = v = 0 and t=0t = 0: its first steps are approximately η\eta in each coordinate; learning rate restarts warmup and the cosine, so it remains high when the step budget ends; dropout draws different masks (the RNG returns to the root seed and repeats step-0 masks); epoch 12 repeats from batch 0 using epoch 0's permutation (the sampler returns to its seed): 6 batches were already seen, and the new order repeats some examples and skips others. Missing from checkpoint: optimizer, scheduler, RNG, data position.
150 (epoch 12, batch 6)
Checkpoint saves
View
Max ∥θt−θtref∥\norm{\theta_t - \theta_t^{\text{ref}}}0.643
Final loss0.299 / 0.203
Peak after interruption×1.21
First-step η\eta0.0017 / 0.0302
First-step ∥Δθ∥\norm{\Delta\theta}5.8·10⁻³ / 8.3·10⁻³
Toy training (linear regression with input dropout, Adam, linear warmup plus cosine and shuffled batches) whose state is explicit and copyable. The gray band is the uninterrupted run; blue line resumes from the cut with the selected checkpoint. Anything unsaved is reconstructed as a fresh script would. Start with ‘Only state_dict’: what does learning rate do after the cut and why is final loss worse? Add pieces one by one and watch the lower panel, distance to reference: what minimum leaves it exactly 0? Also try ‘Everything except RNG’ and move the cut: the curve closely resembles the reference, but distance is not 0.

The figure reproduces typical omission symptoms, useful to recognize in a real curve. Without optimizer, Adam resets m=v=0m = v = 0 and t=0t = 0; with bias correction, its first update is η m^1/v^1=η g/∣g∣\eta\, \hat m_1 / \sqrt{\hat v_1} = \eta\, g / \lvert g \rvert coordinate by coordinate (except denominator ε\varepsilon), a step of size η\eta in each direction regardless of how small the gradient was: a loss spike immediately after the cut, which with a cut at step 150 nearly doubles loss. Without scheduler, learning rate returns to warmup and, since the step budget is unchanged, cosine never falls: training ends with high learning rate and worse final loss. Without RNG or without data position, the curve is visually indistinguishable but another trajectory: the only way to detect it is bitwise comparison.

Writing without losing what you already had

Knowing what to save is not enough: save so failure during the write does not leave things worse than before. To see why the naive way fails, we need a minimal model of what happens between f.write and disk.

From Python buffer to disk

A Python write crosses three layers. First, the Python file object’s buffer, emptied by f.flush(). Then the operating system’s page cache: write returns as soon as bytes are in RAM, and the kernel writes them to disk later, when convenient (on Linux, typically a few seconds). Only os.fsync(f.fileno()) forces that file’s data to the device before returning. Power loss erases RAM: page-cache contents not yet written are lost.

Metadata (that the file exists, its size, which blocks its name points to) follows another path: in a journaling filesystem like ext4 or NTFS, each metadata change is atomically recorded in the journal, and after a crash the filesystem recovers to a consistent state. Consistent does not mean complete: a file can remain truncated to zero bytes, or one whose size grows as data reaches disk can remain half written.

In this model, direct open("ckpt.pt", "wb") has an obvious problem: truncation is a metadata change made at opening, and from then until the last block reaches disk the only checkpoint is a prefix of the new one. torch.save writes a zip archive whose central directory is at the end; a prefix cannot be read.

InteractivePower failure while saving
  • v1: previous checkpoint
  • v2: checkpoint being saved
  • fsync
  • os.replace
  • power failure
Direct write to ckpt.ptopen12345678fsyncred band: a crash there leaves no valid checkpointin progress: f.write(chunk 5 of 8)PAGE CACHE (RAM): LOST ON CRASHckpt.ptDISK: WHAT SURVIVESckpt.ptOn restart: RuntimeError: PytorchStreamReader failed reading zip archive: failed finding central directory
Temporary file in same directory and os.replaceopen12345678fsyncno crash time leaves the disk without a valid checkpointin progress: f.write(chunk 5 of 8)PAGE CACHE (RAM): LOST ON CRASHckpt.pt.tmpDISK: WHAT SURVIVESckpt.ptckpt.pt.tmpOn restart, torch.load loads the previous version (v1)
t = 5.30
Direct, after crashcorrupt
Atomic, after crashvalid (v1)
Fatal window, directt ∈ [0.6, 10.6]
Fatal window, atomicnone
open("ckpt.pt", "wb") truncated the only checkpoint on opening. The disk contains a zip prefix without its final central directory: the entire training state is lost. The atomic lane retains v1; the partial temporary file is ignored and deleted on restart.
Two strategies with the same failure instant. Above, direct writing to ckpt.pt; below, writing to a temporary in the same directory and os.replace. Each lane shows call sequence, page cache contents (erased by failure) and disk contents by block: blue is previous version, orange the new one. The red band under each timeline marks all instants when failure leaves no valid checkpoint. Play the save or drag the failure: is there an instant when the atomic lane loses v1? Then disable fsync: why does a fatal window appear in the atomic lane immediately after rename? The model is simplified (times are arbitrary and delayed writing is a fixed delay), but the event order producing each window is real.

Temporary file and atomic rename

The classic solution separates writing from publishing. Write the new checkpoint to a temporary file, force it to disk, and only then rename the temporary over the destination with an operation the filesystem guarantees atomic: after a failure, ckpt.pt points either to the old file or the complete new one, never an intermediate state.

Each step has a specific reason:

  • Same directory. os.replace uses rename(2) on POSIX and MoveFileEx on Windows. Rename only changes directory entries, atomic because it is one metadata operation within one filesystem. Across volumes there is no entry to change: data must be copied, the call fails (EXDEV on POSIX, WinError 17 on Windows), and the alternative shutil.move copies and deletes without atomicity. tempfile.mkstemp(dir=destino.parent) guarantees the same volume and a name not colliding with another concurrent save.
  • fsync before rename. Without it, rename (metadata journaled immediately) can reach disk before temporary data (waiting in page cache). After failure in that interval, ckpt.pt is the half-written new file and the old one already freed. This is the zero-length file failure ext4 suffered in 2009 with delayed allocation; ext4 added a heuristic (auto_da_alloc) forcing data in this specific pattern, but neither POSIX nor other filesystems guarantee it. The figure reproduces it when fsync is disabled.
  • Directory fsync. On POSIX, a directory entry is directory data and durability requires fsync on a directory descriptor. Without it, after a crash the old file can reappear: no valid file is lost, but the latest checkpoint does not count. On Windows a directory cannot be opened with os.open, and NTFS journals rename.
  • Atomicity on Windows. Python documentation guarantees os.replace atomicity as a POSIX requirement. On Windows, MoveFileEx within the same NTFS volume behaves this way in practice, but it is not documented as a formal guarantee. There is also a practical failure: if another process has destination open (antivirus, cloud sync client, viewer), os.replace fails with PermissionError. This is another reason not to store checkpoints in a synced folder.

The next cell checks this on Pyodide’s in-memory filesystem. It cannot cut power, so simulates failure as closely as possible: an object throwing halfway through serialization after 200 kB have been written. The cell’s temporary version is deliberately incomplete, with a fixed name and no cleanup; the final code exercise asks for the robust version.

[ ]Direct writing versus temporary and renameBrowser
import os
import pickle
import tempfile
from pathlib import Path

class FalloAMitad:
    """Lanza una excepción al serializarse: simula un fallo con parte del fichero ya escrita."""
    def __reduce__(self):
        raise OSError("fallo simulado a mitad de escritura")

def guardar_directo(obj, ruta):
    with open(ruta, "wb") as f:          # trunca ckpt.pkl a 0 bytes aquí
        pickle.dump(obj, f)

def guardar_con_temporal(obj, ruta):     # versión mínima: nombre fijo y sin limpieza
    tmp = Path(str(ruta) + ".tmp")
    with open(tmp, "wb") as f:
        pickle.dump(obj, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, ruta)

v1 = {"paso": 1000, "pesos": bytes(200_000)}
v2 = {"paso": 2000, "pesos": bytes(200_000), "extra": FalloAMitad()}

for guardar in (guardar_directo, guardar_con_temporal):
    carpeta = Path(tempfile.mkdtemp())
    ruta = carpeta / "ckpt.pkl"
    guardar_directo(v1, ruta)            # partimos de un checkpoint bueno
    try:
        guardar(v2, ruta)
    except OSError as e:
        print(f"{guardar.__name__}: {e}")
    try:
        with open(ruta, "rb") as f:
            print(f"  ckpt.pkl se lee: paso {pickle.load(f)['paso']}")
    except Exception as e:
        print(f"  ckpt.pkl ilegible: {type(e).__name__} ({ruta.stat().st_size} bytes)")
    print("  en la carpeta:", sorted(p.name for p in carpeta.iterdir()))

Direct writing leaves a little over 200 kB of unreadable ckpt.pkl: the good checkpoint is gone. The temporary version retains step 1000 intact but leaves garbage, a half-written ckpt.pkl.tmp; a real power loss would also leave such a temporary after reboot. A checkpoint manager treats it as what it is, an unpublished save: delete it at startup.

Rotation and best-checkpoint tracking

Saving every so many steps fills disk: a GPT-2 small checkpoint with Adam occupies 1.5 GB, and one hundred saves are 150 GB. Rotation retains the NN most recent (to roll back if the latest is wrong, for example after divergence taking time to manifest) and a separate copy of the best by validation metric, which is the one eventually used. Order matters: install the new one first, then delete the oldest. In reverse, a failure between operations leaves one fewer checkpoint than expected, and if N=1N = 1, none.

Safety costs space: during a save the prior NN, the best and new temporary coexist. One exercise asks for the exact count. If space is tight, the best can be a hard link (os.link) to its checkpoint, which consumes nothing while that checkpoint remains in rotation and survives its deletion; hard links work on NTFS and ext4, but not FAT or many network drives.

A complete checkpoint manager

The preceding pieces come together in a small class. The following lab runs on local GPU: it trains an MLP with dropout, NumPy augmentation noise, AdamW, warmup and cosine, and mixed precision with GradScaler; interrupts it manually at step 130, simulates a new process and resumes from the last checkpoint. It then compares the resumed curve with the continuous one step by step and bit for bit.

The first cell is the manager: atomic save, rotation, best tracking, metadata and loading that warns and tries the previous checkpoint if the latest is corrupt. Note two details. PyTorch version is saved as str(torch.__version__), because torch.__version__ is a str subclass (TorchVersion) rejected by torch.load restricted mode: discovered while writing this lab. And the folder is outside the repository, in the system temporary directory.

[ ]CheckpointManager: atomic saving, rotation and bestLocal GPU
import math, os, random, subprocess, tempfile, time
from dataclasses import dataclass, asdict
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn

device = "cuda" if torch.cuda.is_available() else "cpu"

def guardar_atomico(obj, ruta):
    """torch.save a un temporal del mismo directorio, fsync y os.replace."""
    ruta = Path(ruta)
    fd, tmp = tempfile.mkstemp(dir=ruta.parent, prefix=ruta.name + ".", suffix=".tmp")
    try:
        with os.fdopen(fd, "wb") as f:
            torch.save(obj, f)
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, ruta)
    except BaseException:
        Path(tmp).unlink(missing_ok=True)
        raise
    if os.name == "posix":                    # que el renombrado también sea duradero
        dfd = os.open(ruta.parent, os.O_RDONLY)
        try:
            os.fsync(dfd)
        finally:
            os.close(dfd)

def commit_actual():
    try:
        r = subprocess.run(["git", "rev-parse", "--short", "HEAD"], capture_output=True, text=True, timeout=5)
        return r.stdout.strip() or "desconocido"
    except (OSError, subprocess.SubprocessError):
        return "desconocido"

class CheckpointManager:
    def __init__(self, carpeta, conservar=3, modo="min"):
        self.carpeta = Path(carpeta)
        self.carpeta.mkdir(parents=True, exist_ok=True)
        self.conservar, self.modo = conservar, modo
        for basura in self.carpeta.glob("*.tmp"):     # guardados que no llegaron a publicarse
            basura.unlink()

    def checkpoints(self):
        return sorted(self.carpeta.glob("ckpt-*.pt"))  # el paso con ceros a la izquierda ordena bien

    def _mejor_metrica(self):
        ruta = self.carpeta / "best.pt"
        if not ruta.exists():
            return None
        return torch.load(ruta, map_location="cpu", weights_only=True)["meta"]["metrica"]

    def guardar(self, estado, paso, metrica=None, config=None):
        estado = dict(estado, meta={"paso": paso, "metrica": metrica, "commit": commit_actual(),
                                    "config": config, "torch": str(torch.__version__), "hora": time.time()})
        guardar_atomico(estado, self.carpeta / f"ckpt-{paso:08d}.pt")
        mejor = self._mejor_metrica()
        if metrica is not None and (mejor is None or (metrica < mejor if self.modo == "min" else metrica > mejor)):
            guardar_atomico(estado, self.carpeta / "best.pt")
        for viejo in self.checkpoints()[:-self.conservar]:  # rotar después de instalar el nuevo
            viejo.unlink()

    def cargar_ultimo(self, map_location="cpu"):
        for ruta in reversed(self.checkpoints()):
            try:
                return torch.load(ruta, map_location=map_location, weights_only=True)
            except Exception as e:
                print(f"aviso: {ruta.name} no se puede leer ({type(e).__name__}); pruebo el anterior")
        return None

# prueba rápida: cinco guardados con métricas que suben y bajan, y un sexto corrupto
prueba = CheckpointManager(Path(tempfile.mkdtemp(prefix="atlas-ckpt-")), conservar=3)
for paso, metrica in [(10, 0.9), (20, 0.5), (30, 0.7), (40, 0.6), (50, 0.8)]:
    prueba.guardar({"w": torch.full((4,), float(paso))}, paso, metrica=metrica)
print("en disco:", [p.name for p in sorted(prueba.carpeta.iterdir())])
print("best.pt es el del paso", torch.load(prueba.carpeta / "best.pt", weights_only=True)["meta"]["paso"])
(prueba.carpeta / "ckpt-00000060.pt").write_bytes(b"PK a medias")
print("carga el paso", prueba.cargar_ultimo()["meta"]["paso"])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The second cell defines training. Three design decisions make it resumable:

  • RNG states are converted to basic types. np.random.get_state() contains an ndarray, rejected by torch.load restricted mode; save it as a list of integers and reconstruct it on load. On restoration, PyTorch states go to CPU with .cpu(), because torch.load(..., map_location="cuda") also moves those ByteTensors to GPU and torch.set_rng_state requires a CPU one: another real failure encountered while writing the cell.
  • The sampler derives each epoch’s permutation from (seed, epoch). Thus data position reduces to two integers, epoch and batch, and mid-epoch resumption requests the same permutation and skips its first lote · tamaño indices without loading a single previously seen batch example. This is a variant of the sampler with set_epoch you know from samplers. Iterating DataLoader and discarding batches also works, but pays loading and preprocessing for everything discarded.
  • Restoration order. Construct the model (consuming PyTorch generator numbers for initialization), load its state_dict, create optimizer, scheduler and GradScaler and load theirs, and restore RNG states last, immediately before the loop. Restoring before model construction would make initialization consume part of the restored sequence and the first dropout after resumption would differ.
[ ]Resumable training: RNG, sampler and loopLocal GPU
def capturar_rng():
    np_state = np.random.get_state(legacy=False)
    np_state["state"]["key"] = np_state["state"]["key"].tolist()   # ndarray -> lista de enteros
    return {"python": random.getstate(), "numpy": np_state, "torch": torch.get_rng_state(),
            "cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else []}

def restaurar_rng(s):
    random.setstate(s["python"])
    np_state = dict(s["numpy"], state=dict(s["numpy"]["state"]))
    np_state["state"]["key"] = np.array(np_state["state"]["key"], dtype=np.uint32)
    np.random.set_state(np_state)
    torch.set_rng_state(s["torch"].cpu())                          # map_location pudo moverlo a la GPU
    if s["cuda"]:
        torch.cuda.set_rng_state_all([t.cpu() for t in s["cuda"]])

class SamplerReanudable(torch.utils.data.Sampler):
    """La permutación de cada época sale de (semilla, época): para reanudar basta con (época, lote)."""
    def __init__(self, n, semilla):
        self.n, self.semilla, self.epoca, self.saltar = n, semilla, 0, 0
    def set_epoch(self, epoca, saltar=0):
        self.epoca, self.saltar = epoca, saltar
    def __iter__(self):
        g = torch.Generator().manual_seed(self.semilla * 100_003 + self.epoca)
        return iter(torch.randperm(self.n, generator=g)[self.saltar:].tolist())
    def __len__(self):
        return self.n - self.saltar

@dataclass
class Config:
    semilla: int = 0
    pasos: int = 240
    lote: int = 64
    lr: float = 3e-3
    warmup: int = 20
    p_drop: float = 0.1
    ruido: float = 0.05
    guardar_cada: int = 40
    conservar: int = 3

def datos(n=2048, d=16, semilla=123):
    g = torch.Generator().manual_seed(semilla)
    X = torch.randn(n, d, generator=g)
    y = torch.sin(X @ torch.randn(d, 1, generator=g)) + 0.1 * torch.randn(n, 1, generator=g)
    return torch.utils.data.TensorDataset(X, y)

def construir(cfg):
    torch.manual_seed(cfg.semilla)
    modelo = nn.Sequential(nn.Linear(16, 64), nn.GELU(), nn.Dropout(cfg.p_drop),
                           nn.Linear(64, 64), nn.GELU(), nn.Dropout(cfg.p_drop), nn.Linear(64, 1)).to(device)
    opt = torch.optim.AdamW(modelo.parameters(), lr=cfg.lr, weight_decay=0.01)
    f = lambda s: (s + 1) / cfg.warmup if s < cfg.warmup else 0.5 * (1 + math.cos(math.pi * (s - cfg.warmup) / (cfg.pasos - cfg.warmup)))
    sched = torch.optim.lr_scheduler.LambdaLR(opt, f)
    scaler = torch.amp.GradScaler("cuda", enabled=(device == "cuda"))
    return modelo, opt, sched, scaler

def entrenar(cfg, gestor=None, ck=None, parar_en=None, solo_pesos=False):
    ds = datos()
    modelo, opt, sched, scaler = construir(cfg)       # 1. construir (consume RNG al inicializar)
    sampler = SamplerReanudable(len(ds), cfg.semilla)
    por_epoca = len(ds) // cfg.lote
    paso, perdidas = 0, {}
    random.seed(cfg.semilla); np.random.seed(cfg.semilla)
    if ck is not None:
        modelo.load_state_dict(ck["modelo"])          # 2. pesos
        if not solo_pesos:
            opt.load_state_dict(ck["optimizador"])    # 3. optimizador, scheduler, scaler
            sched.load_state_dict(ck["scheduler"])
            scaler.load_state_dict(ck["scaler"])
            restaurar_rng(ck["rng"])                  # 4. RNG, el último
        paso = ck["progreso"]["paso"]
    while paso < cfg.pasos:
        epoca, lote = divmod(paso, por_epoca)
        sampler.set_epoch(epoca, saltar=lote * cfg.lote)   # 5. posición en los datos
        cargador = torch.utils.data.DataLoader(ds, batch_size=cfg.lote, sampler=sampler, drop_last=True)
        for x, y in cargador:
            x, y = x.to(device), y.to(device)
            x = x + cfg.ruido * torch.from_numpy(np.random.standard_normal(x.shape).astype(np.float32)).to(device)
            with torch.autocast(device, dtype=torch.float16, enabled=(device == "cuda")):
                perdida = nn.functional.mse_loss(modelo(x).float(), y)
            opt.zero_grad(set_to_none=True)
            scaler.scale(perdida).backward()
            scaler.step(opt)
            scaler.update()
            sched.step()
            paso += 1
            perdidas[paso] = perdida.item()
            if gestor and paso % cfg.guardar_cada == 0:   # entre dos pasos: todo es coherente
                gestor.guardar({"modelo": modelo.state_dict(), "optimizador": opt.state_dict(),
                                "scheduler": sched.state_dict(), "scaler": scaler.state_dict(),
                                "rng": capturar_rng(), "progreso": {"paso": paso, "epoca": epoca}},
                               paso, metrica=perdida.item(), config=asdict(cfg))
            if paso == parar_en:
                raise KeyboardInterrupt(f"interrumpido a mano en el paso {paso}")
            if paso >= cfg.pasos:
                break
    return perdidas, modelo

print("entrenamiento definido en", device)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The third cell performs the experiment. Before resuming, it deliberately disturbs all generators, as they would be in a new process that had done other things first.

[ ]Interrupt, resume and compare bit for bitLocal GPU
cfg = Config()
continua, m_ref = entrenar(cfg)

carpeta = Path(tempfile.mkdtemp(prefix="atlas-ckpt-"))
gestor = CheckpointManager(carpeta, conservar=cfg.conservar)
try:
    entrenar(cfg, gestor, parar_en=130)
except KeyboardInterrupt as e:
    print(e)
print("en disco:", [p.name for p in sorted(carpeta.iterdir())])

torch.manual_seed(999); np.random.seed(999); random.seed(999); torch.rand(1000)   # «otro proceso»
ck_a, ck_b = gestor.cargar_ultimo(device), gestor.cargar_ultimo(device)          # dos copias independientes
solo_pesos, _ = entrenar(cfg, None, ck=ck_b, solo_pesos=True)
reanudada, m_res = entrenar(cfg, gestor, ck=ck_a)

print(f"reanudada desde el paso {min(reanudada) - 1}: pasos {min(reanudada)} a {max(reanudada)}")
print("pérdidas idénticas bit a bit:", all(reanudada[k] == continua[k] for k in reanudada))
print("parámetros finales idénticos:", all(torch.equal(a, b) for a, b in zip(m_ref.parameters(), m_res.parameters())))
dif = max(abs(solo_pesos[k] - continua[k]) for k in solo_pesos)
print(f"solo pesos: máxima diferencia de pérdida {dif:.3f}; pérdida final {solo_pesos[cfg.pasos]:.4f} frente a {continua[cfg.pasos]:.4f}")
meta = torch.load(gestor.checkpoints()[-1], weights_only=True)["meta"]
print("metadatos del último:", {k: meta[k] for k in ("paso", "commit", "torch")}, "| lr y pasos de la config:", meta["config"]["lr"], meta["config"]["pasos"])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Losses from steps 121 to 240 are bitwise identical to the continuous run, as are final parameters. They are not “very similar”: they are the same bits, because resumption applied the same function to the same state, as the proposition says. Resuming weights only, by contrast, is another trajectory from the first step: its losses differ from the continuous run by up to 0.04 and end elsewhere. In this MLP the difference is small because the cut falls in a calm cosine region; the previous figure shows this is not always true. If you change one lab line (remove restaurar_rng, or call it before construir, or skip batches with another permutation), equality disappears: that is how a checkpoint is debugged.

Two comments on resumption in a real system. If DataLoader uses worker processes, each is seeded with a base seed the main process draws from its generator at iterator creation, plus worker index; with the generator restored before creating the iterator, worker seeds are reproduced too. And for unattended resumption, the script always does the same at startup: if the experiment folder has a checkpoint, load the latest valid one; otherwise start from scratch. Then relaunching the same command after interruption is the only action needed.

Loading third-party weights

A checkpoint written by your code on your disk is trusted. A .pt downloaded from the internet is not, and Python documentation is explicit: pickle is unsafe and only trusted data should be deserialized. This lesson does not cover crafting a malicious file; as an engineer you need rules for loading others’ weights without exposure.

A few practical rules:

  • weights_only=True has been the default since PyTorch 2.6. Do not disable it to load a third-party file. If your own file fails to load, the error identifies the type responsible: either convert it to basic types when saving (as the lab does with version, configuration and NumPy state) or, if it is your own trusted class, allow it with torch.serialization.add_safe_globals([...]) or context manager torch.serialization.safe_globals([...]). torch.serialization.get_unsafe_globals_in_checkpoint(ruta) lists what a file would require without loading it.
  • Keep PyTorch updated. Restricted mode has also had vulnerabilities: CVE-2025-32434 was published in April 2025, affecting torch.load with weights_only=True in PyTorch 2.5.1 and earlier, and fixed in 2.6.0.
  • Prefer safetensors for anything distributed. A safetensors file contains nothing executable, removing the question of what code to trust.

The following cell checks what restricted mode accepts among types commonly found in checkpoints:

[ ]What torch.load accepts in restricted modeLocal GPU
import io
import pathlib

for nombre, obj in [("asdict(cfg)", asdict(Config())), ("instancia de la dataclass", Config()),
                    ("random.getstate()", random.getstate()), ("np.random.get_state()", np.random.get_state()),
                    ("torch.__version__", torch.__version__), ("str(torch.__version__)", str(torch.__version__)),
                    ("pathlib.Path", pathlib.Path("runs")), ("set de enteros", {1, 2, 3})]:
    b = io.BytesIO()
    torch.save({"x": obj}, b)
    b.seek(0)
    try:
        torch.load(b, weights_only=True)
        print(f"{nombre:28s} se carga")
    except Exception as e:
        motivo = str(e).split("Unsupported global: GLOBAL ")[-1].split(" ")[0]
        print(f"{nombre:28s} rechazado: {motivo}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

safetensors

safetensors is a Hugging Face format for one thing: saving named tensors. A file has three parts: 8 bytes with header length NN (an unsigned 64-bit little-endian integer), NN bytes of JSON header and a byte buffer. The header associates each name with dtype, shape and data_offsets, the occupied buffer segment relative to its start; optional __metadata__ accepts string pairs. The reader validates that segments match types and shapes, do not overlap and cover the buffer, and interprets nothing else.

Two properties make it the usual format for distributing LLM weights. First is what we just saw: JSON and bytes cannot express a call. Second is lazy loading with memory mapping: because each tensor is a contiguous file segment with known offsets, safe_open can map the file and read only requested tensors (or rows), and the OS fetches touched disk pages. A 14 GB model can be inspected or split between GPU and CPU without reading it all. torch.load has a similar mmap=True mode for its own format.

Limitations matter too: safetensors stores tensors and text metadata, nothing else. It cannot store optimizer state with integer counters without conversion, nor RNG states. And it does not permit two names sharing memory: if a model ties embedding and head weights, save_file refuses and save_model must be used, removing duplicates and retying them on loading with load_model.

[ ]safetensors: header, partial loading and tied weightsLocal GPU
import json
from safetensors.torch import save_file, load_file, safe_open, save_model, load_model

carpeta_st = Path(tempfile.mkdtemp(prefix="atlas-st-"))
torch.manual_seed(0)
mlp = nn.Sequential(nn.Linear(1024, 4096), nn.GELU(), nn.Linear(4096, 1024))
ruta = carpeta_st / "mlp.safetensors"
save_file(mlp.state_dict(), ruta, metadata={"arquitectura": "mlp-1024-4096-1024", "paso": "240"})

with open(ruta, "rb") as f:
    n = int.from_bytes(f.read(8), "little")
    cabecera = json.loads(f.read(n))
print(f"cabecera de {n} bytes; fichero de {ruta.stat().st_size / 1e6:.2f} MB")
for nombre, info in cabecera.items():
    print(f"  {nombre:14s} {info}")

with safe_open(ruta, framework="pt", device="cpu") as f:
    print("metadatos:", f.metadata())
    filas = f.get_slice("0.weight")[:2]        # solo 2 de las 4096 filas
print("carga parcial:", tuple(filas.shape))
todo = load_file(ruta)
print("carga completa idéntica:", all(torch.equal(todo[k], v) for k, v in mlp.state_dict().items()))

class Atado(nn.Module):
    def __init__(self):
        super().__init__()
        self.emb = nn.Embedding(100, 16)
        self.cabeza = nn.Linear(16, 100, bias=False)
        self.cabeza.weight = self.emb.weight     # pesos compartidos
atado = Atado()
try:
    save_file(atado.state_dict(), carpeta_st / "atado.safetensors")
except RuntimeError as e:
    print("save_file se niega:", " ".join(str(e).split())[:120], "...")
save_model(atado, carpeta_st / "atado.safetensors")
otro = Atado()
faltan, sobran = load_model(otro, carpeta_st / "atado.safetensors")
print("save_model y load_model:", torch.equal(otro.cabeza.weight, atado.emb.weight), "| faltan:", faltan, "| sobran:", sobran)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Weights to distribute and checkpoints to resume

Two distinct artifacts are often confused. A resumption checkpoint is private, large (weights, two Adam moments, everything else) and tied to a particular code version: it continues this training and nothing else. Weights for distribution are public, small (weights only, often 16-bit), independent of training code and in safetensors, accompanied by JSON configuration describing architecture. After training, export the latter from the former, normally from best.pt.

Code independence motivates PyTorch documentation’s most repeated rule: save model.state_dict(), not torch.save(model). Saving the entire model saves a reference to its class by module and class name; moving the class to another file or renaming it makes the file unloadable. Restricted mode also rejects it. A state_dict contains only parameter names and tensors, and compatibility is managed explicitly:

  • Version the format. Save a checkpoint format version in metadata and, when changing architecture, write a function migrating old state_dicts, for example renaming keys ("blocks.0.attn.c_attn.weight" becomes "layers.0.attn.qkv.weight").
  • Do not silence discrepancies. load_state_dict(strict=False) returns missing and unexpected keys; if you do not inspect them, a naming error leaves layers unloaded and the model trains from random initialization without warning.
  • Optimizer state is positional. opt.state_dict() identifies parameters by position in param_groups, not name. If you add a layer or reorder groups, loading old state assigns moments to the wrong parameters, sometimes without error if shapes match.

Finally, where to save. Never inside the repository: a careless git add . uploads gigabytes to history, and history does not forget. Nor in a cloud-synced folder, which on Windows often includes Desktop and Documents through OneDrive: the client uploads every version of every checkpoint, locks files while reading them (and os.replace fails with PermissionError) and may return an old version after a conflict. Use an experiment folder outside both, specified in configuration.

Common mistakes

Exercises

QuizWhat is missing from a checkpoint
Training uses AdamW, warmup plus cosine with LambdaLR, autocast in float16 with GradScaler, dropout and a DataLoader with shuffle=True. Every hour it saves torch.save({'modelo': modelo.state_dict(), 'optimizador': opt.state_dict(), 'paso': paso}, ruta). It resumes mid-epoch by recreating everything and loading those three keys. Which statements are true? There may be several.

More than one answer may be correct.

NumericGPT-2 small checkpoint size
How many GB (10910^9 bytes) does a float32 checkpoint of a 124-million-parameter model trained with Adam occupy if it saves weights and both moments but no gradients? Ignore counters and metadata.
NumericPeak rotation disk use
With the previous exercise's checkpoint (1.488 GB), a manager retains the 3 most recent checkpoints and a separate best.pt copy. On save, it writes a temporary, renames it and only then deletes the oldest. For a save that does not improve the metric, how many GB does the folder occupy at most at any moment?
Quizos.replace across volumes
To avoid using the system SSD, you write the temporary to D:/scratch/ckpt.tmp and publish it with os.replace('D:/scratch/ckpt.tmp', 'C:/runs/ckpt.pt'). What happens?
QuizWhy restore RNG last?
In the lab, restaurar_rng is called after constructing model, optimizer, scheduler and GradScaler and loading their states, just before the loop. Why that order?
QuizYour own checkpoint will not load
Your checkpoint saves meta = {'torch': torch.__version__, 'config': cfg}, with cfg a dataclass instance. torch.load(ruta) rejects it with Unsupported global. What is the best fix?
CodeA robust atomic save
Implement atomic_save(obj, path), which saves obj with pickle.dump to path atomically: create a uniquely named temporary in the same directory as path (with tempfile.mkstemp), write, flush and os.fsync, and publish with os.replace. If anything fails before rename, delete the temporary and propagate the exception. Call functions as os.fsync and os.replace (tests spy on them). Tests simulate a mid-write failure using an object that raises OSError during serialization.
import os
import pickle
import tempfile
from pathlib import Path

def atomic_save(obj, path):
  # tu código: escribir en un temporal del mismo directorio, fsync y os.replace
  with open(path, "wb") as f:
      pickle.dump(obj, f)
Shift+Enter to run

Summary

Key idea
Training is a dynamical system st+1=F(st)s_{t+1} = F(s_t), and exact resumption means applying the same function to the same state: checkpoint must contain everything the next step reads (weights, optimizer, scheduler, GradScaler, Python, NumPy, PyTorch and CUDA RNG states, data position) plus interpretable metadata, and proof of completeness is a resumed curve matching continuous training bit for bit. Write a temporary in the same directory, with fsync and os.replace, so interruption cannot destroy the previous version, and rotate after installing the new one. Load third-party weights with weights_only=True or, preferably, safetensors, and treat distributed weights as a distinct artifact from resumption checkpoints.