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:
| Component | How to obtain it | What happens if missing |
|---|---|---|
| Weights | model.state_dict() | Model restarts |
| Optimizer | opt.state_dict(): Adam moments , and step counter, and param_groups with current lr | Adam starts from zero and its first step measures in each coordinate |
| Scheduler | sched.state_dict(): last_epoch and latest learning rates | Learning rate returns to warmup |
| GradScaler | scaler.state_dict(): current scale and growth counter | Scale returns to ; first steps may overflow and be skipped |
| Python, NumPy and PyTorch RNG | random.getstate(), np.random.get_state(), torch.get_rng_state() | Different dropout masks and augmentation noise |
| CUDA RNG | torch.cuda.get_rng_state_all(), one per GPU | Different GPU dropout even if CPU is correct |
| Data | epoch, batch within epoch and sampler state (or seed) | Batches repeat or are skipped in another order |
| Metadata | step, metric, git commit, configuration as dict, versions | You 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 be the set of all possible states (weights, moments, counters, generator states, data position) and state after steps. One training step is a function
that reads the batch dictated by position saved in , draws dropout masks with the generator saved in , computes gradient and updates everything. Saving a checkpoint applies a projection keeping some state components; resuming reconstructs state from the file and what the script does at startup.
Proof
By induction on . For , by hypothesis. If , then , where the second equality uses being a function: two calls with the same argument give the same result. The converse is an observation, not a theorem: if , the trajectory already differs at , and if the differing component is one 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. 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.
The figure reproduces typical omission symptoms, useful to recognize in a real curve. Without optimizer, Adam resets and ; with bias correction, its first update is coordinate by coordinate (except denominator ), a step of size 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.
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.replaceusesrename(2)on POSIX andMoveFileExon 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 (EXDEVon POSIX,WinError 17on Windows), and the alternativeshutil.movecopies 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.ptis 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
fsyncon 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 withos.open, and NTFS journals rename. - Atomicity on Windows. Python documentation guarantees
os.replaceatomicity as a POSIX requirement. On Windows,MoveFileExwithin 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.replacefails withPermissionError. 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.
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 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 , none.
Safety costs space: during a save the prior , 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.
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"])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 anndarray, rejected bytorch.loadrestricted mode; save it as a list of integers and reconstruct it on load. On restoration, PyTorch states go to CPU with.cpu(), becausetorch.load(..., map_location="cuda")also moves thoseByteTensors to GPU andtorch.set_rng_staterequires 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ñoindices without loading a single previously seen batch example. This is a variant of the sampler withset_epochyou 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.
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)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.
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"])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=Truehas 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 withtorch.serialization.add_safe_globals([...])or context managertorch.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.loadwithweights_only=Truein 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:
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}")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 (an unsigned 64-bit little-endian integer), 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.
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)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 inparam_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
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.
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.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?D:/scratch/ckpt.tmp and publish it with os.replace('D:/scratch/ckpt.tmp', 'C:/runs/ckpt.pt'). What happens?restaurar_rng is called after constructing model, optimizer, scheduler and GradScaler and loading their states, just before the loop. Why that order?meta = {'torch': torch.__version__, 'config': cfg}, with cfg a dataclass instance. torch.load(ruta) rejects it with Unsupported global. What is the best fix?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)Summary
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.