import subprocess
from pathlib import Path
import torch
from safetensors.torch import load_file, safe_open, save_fileTracking & sharing
A model nobody can reproduce or run is a result that evaporates. This short closing section is about the habits around the training itself: recording what happened, saving weights in open formats, and sharing models with their context and their licence attached.
Tracking runs
Every run of this course printed its metrics and moved on. Real projects compare dozens of runs, and “the one with the good learning rate, in some terminal, last Tuesday” is not a finding you can build on.
The lightest habit is the one our loop already has: a history dictionary and a checkpoint per run. The standard tool one level up is an experiment tracker. MLflow, which we cover in our webinar MLflow for experiment tracking, wraps the whole loop and records parameters, metrics, and artifacts with three lines:
import mlflow
mlflow.log_params({"model": "resnet18", "lr": 1e-3, "batch_size": 64,
"epochs": 5, "seed": 42})
# inside the epoch loop:
mlflow.log_metric("val_acc", val_acc, step=epoch)The payoff is comparability: every run’s parameters and curves side by side, filtered and searchable, instead of scrollback. Our notes on running TensorBoard as a cluster job predate this; the tracker we teach today is MLflow.
Safetensors
torch.save serializes with pickle, and pickle loads can execute code: never open a checkpoint from a source you do not trust (we kept weights_only=True on every torch.load for that reason). Safetensors is the safe, fast alternative the ecosystem has settled on: a format that can only hold named tensors (plus metadata you choose), and therefore cannot carry code. It is the default on the Hugging Face Hub.
Converting our fine-tuned model is a few lines (serialization is a CPU affair; no accelerator needed):
root = Path("/project/def-sponsor00/data")state = torch.load(root / "best_ft.pt", weights_only=True)
tensors = {k: v.contiguous().cpu() for k, v in state["model"].items()}
save_file(
tensors, root / "best_ft.safetensors",
metadata={"val_acc": f"{state['val_acc']:.3f}", "epoch": str(state["epoch"])},
)
print("saved", len(tensors), "tensors")saved 122 tensors
loaded = load_file(root / "best_ft.safetensors")
print(torch.equal(loaded["fc.weight"], tensors["fc.weight"]))
with safe_open(root / "best_ft.safetensors", framework="pt") as f:
print(f.metadata()) # our metadata travelled alongTrue
{'val_acc': '0.964', 'epoch': '5'}
.contiguous().cpu()because safetensors writes raw memory: tensor data must be contiguous and on the CPU.metadatais your space for provenance: validation score, epoch, git commit, anything that helps future-you.safe_opencan read the metadata, or single tensors, without loading the whole file — handy for very large models.
A reproducibility checklist
Roughly in order of how often each one actually saves people:
- The seed: set it (we did, on every page), and know its limits: cuDNN picks nondeterministic kernels, and a different GPU gives different floating-point sums.
torch.use_deterministic_algorithms(True)exists, costs performance, and still does not span hardware. What is achievable is a reproducible protocol: same code, data, versions, seed — same trajectory up to noise. - The environment: the
uv.lockfile pins every version (ours lives beside this page’s source);uv syncrebuilds it exactly. We cover this in our webinar on uv. Record the hardware too:torch.version.cuda, the GPU model — it belongs in any report. - The data: our split is in
split.pt, but which images were in it depends on the seed and the torch version that drew it. For data that evolves, version it like code. - The code: put the git commit hash in the checkpoint (or its metadata, as above). One line:
commit = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"],
text=True).strip()