Skip to main content

Tracking & sharing

Author

Marie-Hélène Burle

A model nobody can reproduce or run is a useless model. This section is about good habits while training models: 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 file 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.

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 takes a few lines (serialization is a CPU affair, so no accelerator needed):

from pathlib import Path

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


def main():
    root = Path("/project/def-sponsor00/data")

    # map_location="cpu": the file was saved on a GPU; load its tensors on the CPU
    state = torch.load(root / "best_ft.pt", weights_only=True, map_location="cpu")
    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(f"Saved {len(tensors)} tensors")

    loaded = load_file(root / "best_ft.safetensors")
    print("Round trip intact:", torch.equal(loaded["fc.weight"], tensors["fc.weight"]))

    with safe_open(root / "best_ft.safetensors", framework="pt") as f:
        print("Metadata:", f.metadata())  # our metadata travelled along
        print(
            "Shape of one tensor, without loading it:",
            f.get_slice("fc.weight").get_shape(),
        )


if __name__ == "__main__":
    main()
  • map_location="cpu": the file was saved on a GPU. This loads its tensors on the CPU whatever the machine, and the script thus runs on a node without a GPU.
  • .contiguous().cpu(): because safetensors writes raw memory, tensor data must be contiguous and on the CPU.
  • metadata: your space for provenance (validation score, epoch, git commit, anything that helps future-you). The values must be strings.
  • load_file() brings everything back. safe_open() reads the metadata, or single tensors, without loading the whole file: handy for very large models.

Run it on a CPU node of the training cluster:

srun --mem=3800 --cpus-per-task=1 python to_safetensors.py

The run takes seconds, but the script writes best_ft.safetensors to our shared root folder: if 2 people run it at the same time, there could be a conflict writing to the same file.

Results

This is what I got on the training cluster:

Saved 122 tensors
Round trip intact: True
Metadata: {'val_acc': '0.962', 'epoch': '5'}
Shape of one tensor, without loading it: [10, 512]

And on my laptop:

Saved 122 tensors
Round trip intact: True
Metadata: {'val_acc': '0.963', 'epoch': '5'}
Shape of one tensor, without loading it: [10, 512]

The weights made the round trip intact, and the metadata (here, the validation accuracy and the epoch of the best checkpoint) travelled along. The accuracy differs slightly between the 2 machines because each fine-tuned its own model.

A reproducibility checklist

  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: on your machine, if you use uv, the uv.lock file pins every version (so put it under version control) and uv sync rebuilds the environment exactly. On the clusters, where the environment is a virtual environment built with pip, keep the list of the installed versions in a file:

    python -m pip freeze > requirements.txt

    Record the CUDA version (torch.version.cuda) and the GPU model. They belong 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.

Finally, licences:

  • 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 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 (best.pt) to safetensors with some metadata of your choice, then verify the round trip.

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