Skip to main content

Tracking & sharing

Author

Marie-Hélène Burle

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.

import subprocess
from pathlib import Path

import torch
from safetensors.torch import load_file, safe_open, save_file

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 along
True
{'val_acc': '0.964', 'epoch': '5'}
  • .contiguous().cpu() because safetensors writes raw memory: tensor data must be contiguous and on the CPU.
  • metadata is your space for provenance: validation score, epoch, git commit, anything that helps future-you.
  • safe_open can 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:

  1. 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.
  2. The environment: the uv.lock file pins every version (ours lives beside this page’s source); uv sync rebuilds 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.
  3. 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.
  4. 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()

Sharing

Sharing a trained model is more than uploading weights. The community format is the model card: what the model is, what it was trained on, how well it does on which data, what it should and should not be used for, and under which licence. Datasets get the equivalent dataset card.

Licences deserve the last word because they are the part that bites:

  • EuroSAT is distributed under MIT: permissive, commercial use allowed. Not everything is.
  • Pretrained weights keep their own licence, independent of the code: some of the backbones you will meet in timm are research-only, some forbid commercial use, and a model you fine-tune from them inherits the restriction.

Before you publish a fine-tune, the checklist is: your data’s licence allows it, the base model’s licence allows it, and the card says both.

Your turn:

Convert the from-scratch baseline (data/best.pt) to safetensors with metadata that includes the git commit hash, then verify the round trip.

  • Hint: the checkpoint stores the whole state["model"] dict; metadata values must be strings.