Sign in

Tracking

Experiment tracking

A local experiment tracker that records each run's parameters, metric curves and artifacts as plain files and compares runs afterwards.

Overview

Training a model means trying many settings. After a week you have a good number and no memory of which settings produced it. A tracker is a lab notebook that fills itself in. Each attempt, called a run, gets its own folder holding the settings used, the metrics measured at every step, and the files produced, such as the model weights. Later you can ask which run was best, what it used, and how its loss moved over time.

A short history

Experiment tracking is the laboratory notebook of machine learning, an engineering practice with no single inventor. As deep learning made runs longer and settings more numerous, teams needed a record of which parameters produced which curves. TensorBoard, released with TensorFlow in 2015, made logged metric curves routine. MLflow, open sourced by Databricks in 2018, popularised the model of experiments, runs, parameters, metrics and artifacts that most trackers now share.

How it works

  1. Create a Tracker for one experiment. Its runs live in the folder <root_dir>/<experiment>/.
  2. Call start_run(name, params) to open a Run. Parameters are written once and cannot be changed afterwards.
  3. During training call log_metric(key, value, step). Each point is appended to a JSON-lines file, buffered by flush_every.
  4. Save outputs with log_artifact(name, data): text, bytes, NumPy arrays or JSON.
  5. Used in a with block, the run ends as finished, or as failed when an exception escapes.
  6. Query across runs with list_runs, metric_history, best_run (by last or best value, min or max) and compare.

Watch out for

  • Logging only the final metric hides how the run got there. A curve shows whether the loss was still falling, flat or rising at the end.
  • A setting you do not log cannot be recovered later, so log the data version, the seed and the code version along with the hyperparameters.
  • Choosing the best run by a validation metric and then quoting that same metric as the model's performance is optimistic. Check the winner on a test set.
  • With flush_every above 1, a process that is killed outright loses the points still in the buffer.
  • This template stores plain files in folders. It has no server, no web UI and no database, which larger tracking tools add.

Use cases

When to use it

From the first experiment on. As soon as two runs exist, the question of which settings produced which number comes up. Point root_dir at a shared or backed-up folder when the results matter.

In industry

Research labs
A group training many variants of a network records every run's settings and curves, so a result in a paper can be traced to the exact run that produced it.
Regulated industries
Banks and medical device makers must show how a deployed model was produced. Stored parameters, metrics and artifacts form that audit trail.
Product teams
Engineers compare this week's retraining run with last week's on the same metrics before promoting the new model.

Choosing it: what must hold

  • More than one run to compare, now or soon.
  • Parameters fixed at the start of a run and logged before training begins.
  • A folder that persists, is backed up and can hold the artifacts.
  • Agreed metric names, so runs can be compared key by key.

When to choose something else

IfUse instead
Many people need a shared view with charts and searchA tracking server such as MLflow or Weights and Biases
You only need a final ranked summary to hand to othersThe evaluation reporting lesson
Runs are generated by an automated searchThe hyperparameter optimization lesson, which records its own trials, logged to a tracker

Math foundations

  1. Summary of one metric curve

    vlast=vT,vmin⁡=min⁡tvt,vmax⁡=max⁡tvtv_{\text{last}} = v_{T}, \qquad v_{\min} = \min_{t} v_t, \qquad v_{\max} = \max_{t} v_t

    A run's curve is the sequence of logged values in step order. get_run reduces it to its last, smallest and largest value, which is what runs are compared on.

  2. Picking the best run

    r∗=arg⁡min⁡r  vlast(r)orr∗=arg⁡min⁡r  min⁡tvt(r)r^{*} = \arg\min_{r}\; v^{(r)}_{\text{last}} \qquad \text{or} \qquad r^{*} = \arg\min_{r}\; \min_{t} v^{(r)}_{t}

    best_run with mode min takes the run with the lowest final value (use last) or the lowest value reached at any step (use best). Mode max swaps min for max. The two answers differ when a run got worse after its best point.

  3. Points at risk in the buffer

    nlost≤f−1n_{\text{lost}} \le f - 1

    With flush_every set to ff, points are written in groups of ff. If the process is killed, at most f−1f - 1 points have not reached the disk.

Symbols

vtv_t
value of a metric logged at step t
TT
last step of the run
v(r)v^{(r)}
the curve of run r
r∗r^{*}
the chosen run
ff
flush_every
nlostn_{\text{lost}}
metric points not yet written to disk

Worked by hand

Two runs do 20 steps of gradient descent on w2w^2 from w=5w = 5, logging the loss each step. Each step multiplies ww by 1−2η1 - 2\eta. Run A uses η=0.1\eta = 0.1 and run B uses η=0.01\eta = 0.01.

vlast(A)=25×(1−0.2)40=25×0.840=25×0.000133=0.0033v^{(A)}_{\text{last}} = 25 \times (1 - 0.2)^{40} = 25 \times 0.8^{40} = 25 \times 0.000133 = 0.0033
vlast(B)=25×(1−0.02)40=25×0.9840=25×0.4457=11.14v^{(B)}_{\text{last}} = 25 \times (1 - 0.02)^{40} = 25 \times 0.98^{40} = 25 \times 0.4457 = 11.14
r∗=arg⁡min⁡{0.0033,  11.14}=Ar^{*} = \arg\min\{0.0033,\; 11.14\} = A

best_run("loss", mode="min") returns run A with its parameter lr = 0.1. The curve of run B shows it was still falling slowly, so it needed more steps or a larger rate.

Visual example

Loading the example.

Try this

  • Slide the steps logged so far and watch points move from the buffer to the file in groups of flush_every.
  • Choose process killed: the points still in the buffer never reach the file, and the run still claims to be running.
  • Add gradient noise, then switch use between last and best and see whether the winning run changes.

Code sample

import tempfile
import numpy as np
from impl import Tracker
from config import TrackingConfig

tracker = Tracker(TrackingConfig(root_dir=tempfile.mkdtemp(), experiment="demo"))
for lr in (0.1, 0.01):
    with tracker.start_run(name=f"lr-{lr}", params={"lr": lr}) as run:
        w = 5.0
        for epoch in range(20):
            w -= lr * 2 * w                      # gradient descent on w**2
            run.log_metric("loss", w * w, step=epoch)
        run.log_artifact("weights.npy", np.array([w]))

best = tracker.best_run("loss", mode="min")
print(best["run_id"], best["params"], best["metrics"]["loss"]["last"])    # 0000-lr-0.1 {'lr': 0.1} ...
print(tracker.metric_history(best["run_id"], "loss")[:2])
Read the implementation (253 lines)
"""Experiment tracking on the local file system: parameters, metric curves, artifacts and run comparison.

Standard library and NumPy only, no server. Layout on disk, all of it plain JSON a person can read:

    <root_dir>/<experiment>/<run_id>/meta.json        name, status, start and end time, tags
                                     params.json      the hyperparameters of the run
                                     metrics.jsonl    one {"key", "value", "step", "time"} object per line
                                     artifacts/       files saved with the run

`Tracker` creates runs and answers questions across them (list, history of a metric, best run, comparison).
`Run` is the handle used inside the training code.
"""
from __future__ import annotations

import json
import math
import os
import re
import threading
import time

import numpy as np

try:
    from .config import TrackingConfig
except ImportError:  # run from the template's own folder
    from config import TrackingConfig


def _write_json(path: str, data) -> None:
    """Write JSON through a temporary file so a reader never sees half a file."""
    with open(path + ".tmp", "w", encoding="utf-8") as handle:
        json.dump(data, handle, indent=2, sort_keys=True)
    os.replace(path + ".tmp", path)


def _read_json(path: str):
    with open(path, encoding="utf-8") as handle:
        return json.load(handle)


def _plain(value):
    """NumPy scalars and arrays as plain Python, so json can store them."""
    if isinstance(value, np.ndarray):
        return value.tolist()
    if isinstance(value, np.generic):
        return value.item()
    return value


class Run:
    """One tracked run. Create it with `Tracker.start_run`. Works as a context manager:
    leaving the block normally ends the run as "finished", leaving it through an exception as "failed".
    """

    def __init__(self, directory: str, run_id: str, name: str, tags: dict, flush_every: int) -> None:
        self.directory, self.run_id = directory, run_id
        self._flush_every = flush_every
        self._lock = threading.Lock()
        self._buffer: list[str] = []
        self._next_step: dict[str, int] = {}
        self._params: dict = {}
        self._meta = {"run_id": run_id, "name": name, "status": "running", "start_time": time.time(),
                      "end_time": None, "tags": dict(tags)}
        os.makedirs(os.path.join(directory, "artifacts"))
        _write_json(os.path.join(directory, "meta.json"), self._meta)
        _write_json(os.path.join(directory, "params.json"), {})

    # ------------------------------------------------------------------------------------------ logging
    def log_params(self, params: dict) -> None:
        """Record hyperparameters. A key may be logged once; changing it later is refused, because a
        run's parameters are what make its results reproducible."""
        with self._lock:
            for key, value in params.items():
                value = _plain(value)
                if key in self._params and self._params[key] != value:
                    raise ValueError(f"param {key!r} is already {self._params[key]!r}, cannot change it to {value!r}")
                self._params[key] = value
            _write_json(os.path.join(self.directory, "params.json"), self._params)

    def log_metric(self, key: str, value: float, step: int | None = None) -> None:
        """Record one point of a metric curve.

        step: position on the x axis (epoch, batch, ...). Left out, each key counts 0, 1, 2, ... by itself.
        """
        value = float(value)
        if not math.isfinite(value):
            raise ValueError(f"metric {key!r} is {value}, refusing to log a non-finite value")
        with self._lock:
            if step is None:
                step = self._next_step.get(key, 0)
            self._next_step[key] = int(step) + 1
            self._buffer.append(json.dumps({"key": key, "value": value, "step": int(step), "time": time.time()}))
            if len(self._buffer) >= self._flush_every:
                self._flush()

    def log_metrics(self, metrics: dict, step: int | None = None) -> None:
        """Record several metrics at the same step."""
        for key, value in metrics.items():
            self.log_metric(key, value, step)

    def set_tag(self, key: str, value: str) -> None:
        """Attach a label to the run (data version, git commit, owner, ...)."""
        with self._lock:
            self._meta["tags"][key] = value
            _write_json(os.path.join(self.directory, "meta.json"), self._meta)

    def log_artifact(self, name: str, data) -> str:
        """Save a file with the run and return its path.

        data: str (written as UTF-8 text), bytes, a NumPy array (saved in .npy format) or anything json can
        encode (dict, list). `name` is the file name inside the run's artifacts folder.
        """
        if not re.fullmatch(r"[A-Za-z0-9._-]+", name) or name in (".", ".."):
            raise ValueError(f"artifact name must be a plain file name, got {name!r}")
        path = os.path.join(self.directory, "artifacts", name)
        if isinstance(data, np.ndarray):
            with open(path, "wb") as handle:
                np.save(handle, data)
        elif isinstance(data, bytes):
            with open(path, "wb") as handle:
                handle.write(data)
        elif isinstance(data, str):
            with open(path, "w", encoding="utf-8") as handle:
                handle.write(data)
        else:
            _write_json(path, data)
        return path

    # ---------------------------------------------------------------------------------------- lifecycle
    def _flush(self) -> None:
        if self._buffer:
            with open(os.path.join(self.directory, "metrics.jsonl"), "a", encoding="utf-8") as handle:
                handle.write("\n".join(self._buffer) + "\n")
            self._buffer = []

    def flush(self) -> None:
        """Write buffered metric points to disk now."""
        with self._lock:
            self._flush()

    def end(self, status: str = "finished") -> None:
        """Close the run: flush the metrics and record the status and end time."""
        with self._lock:
            self._flush()
            self._meta["status"], self._meta["end_time"] = status, time.time()
            _write_json(os.path.join(self.directory, "meta.json"), self._meta)

    def __enter__(self) -> "Run":
        return self

    def __exit__(self, exc_type, exc, traceback) -> None:
        self.end("failed" if exc_type else "finished")


class Tracker:
    """Create runs in one experiment and query them."""

    def __init__(self, config: TrackingConfig | None = None) -> None:
        self.config = config or TrackingConfig()
        self.directory = os.path.join(self.config.root_dir, self.config.experiment)
        os.makedirs(self.directory, exist_ok=True)
        self._lock = threading.Lock()

    def start_run(self, name: str = "run", params: dict | None = None, tags: dict | None = None) -> Run:
        """Open a new run. Its id is a counter plus the name, for example "0003-baseline"."""
        safe = re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip("-.") or "run"
        with self._lock:
            index = len(self.run_ids())
            while True:  # another process may have taken the number in the meantime
                run_id = f"{index:04d}-{safe}"
                taken = any(existing.startswith(f"{index:04d}-") for existing in self.run_ids())
                if not taken:
                    break
                index += 1
            run = Run(os.path.join(self.directory, run_id), run_id, name, tags or {}, self.config.flush_every)
        if params:
            run.log_params(params)
        return run

    # ------------------------------------------------------------------------------------------ queries
    def run_ids(self) -> list[str]:
        """Ids of all runs of the experiment, oldest first."""
        return sorted(d for d in os.listdir(self.directory) if os.path.isfile(os.path.join(self.directory, d, "meta.json")))

    def _points(self, run_id: str) -> list[dict]:
        path = os.path.join(self.directory, run_id, "metrics.jsonl")
        if not os.path.exists(path):
            return []
        with open(path, encoding="utf-8") as handle:
            return [json.loads(line) for line in handle if line.strip()]

    def metric_history(self, run_id: str, key: str) -> list[tuple[int, float]]:
        """The curve of one metric of one run as (step, value) pairs in step order."""
        return sorted((p["step"], p["value"]) for p in self._points(run_id) if p["key"] == key)

    def get_run(self, run_id: str) -> dict:
        """Everything about one run: meta fields, "params", and "metrics" = {key: {"last", "min", "max", "count"}}."""
        directory = os.path.join(self.directory, run_id)
        info = _read_json(os.path.join(directory, "meta.json"))
        info["params"] = _read_json(os.path.join(directory, "params.json"))
        curves: dict[str, list] = {}
        for point in self._points(run_id):
            curves.setdefault(point["key"], []).append((point["step"], point["value"]))
        info["metrics"] = {}
        for key, curve in curves.items():
            values = [value for _, value in sorted(curve)]
            info["metrics"][key] = {"last": values[-1], "min": min(values), "max": max(values), "count": len(values)}
        info["artifacts"] = sorted(os.listdir(os.path.join(directory, "artifacts")))
        return info

    def list_runs(self, status: str | None = None) -> list[dict]:
        """`get_run` for every run, oldest first, optionally only those with the given status."""
        runs = [self.get_run(run_id) for run_id in self.run_ids()]
        return [run for run in runs if status is None or run["status"] == status]

    def best_run(self, metric: str, mode: str = "min", use: str = "last") -> dict:
        """The run with the best value of a metric.

        mode: "min" (losses) or "max" (accuracies). use: which point of each run's curve counts: "last"
        (the final value) or "best" (the best value reached at any step).
        Runs that never logged the metric are ignored. Raises ValueError when none did.
        """
        if mode not in ("min", "max") or use not in ("last", "best"):
            raise ValueError('mode must be "min" or "max" and use must be "last" or "best"')
        field = "last" if use == "last" else mode
        candidates = [run for run in self.list_runs() if metric in run["metrics"]]
        if not candidates:
            raise ValueError(f"no run has logged the metric {metric!r}")
        pick = min if mode == "min" else max
        return pick(candidates, key=lambda run: run["metrics"][metric][field])

    def compare(self, metric: str, params: list[str] | None = None) -> list[dict]:
        """One row per run with its id, status, the last value of `metric` and the chosen params,
        sorted by the metric (ascending, runs without it last). Handy for a quick table."""
        rows = []
        for run in self.list_runs():
            row = {"run_id": run["run_id"], "status": run["status"],
                   metric: run["metrics"].get(metric, {}).get("last")}
            for key in params or sorted(run["params"]):
                row[key] = run["params"].get(key)
            rows.append(row)
        return sorted(rows, key=lambda row: (row[metric] is None, row[metric] or 0.0))

    def load_artifact(self, run_id: str, name: str):
        """Read an artifact back: arrays for .npy, parsed data for .json, text otherwise."""
        path = os.path.join(self.directory, run_id, "artifacts", name)
        if name.endswith(".npy"):
            return np.load(path)
        if name.endswith(".json"):
            return _read_json(path)
        with open(path, encoding="utf-8") as handle:
            return handle.read()
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Run the template's README example with learning rates 0.1, 0.01 and 1.1. Call tracker.compare("loss", params=["lr"]), then best_run("loss", mode="min", use="last") and the same with use="best". Print metric_history for the lr 1.1 run and explain its shape.

Check on learning

  1. One run reached a loss of 0.20 at step 50 and ended at 0.35. Another ended at 0.25 and never went lower. Which is best, and what does your answer assume?
    A way to think about it

    It depends on which model you can actually use. Ask whether the weights from step 50 of the first run were saved.

  2. Why are parameters write-once in a run while metrics can be appended freely?
    A way to think about it

    A parameter describes what the run is. Ask what a comparison table would mean if the learning rate recorded for a run could be changed after it finished.

  3. You reproduce last month's best run with the same logged parameters and get a clearly worse number. List what might not have been logged.
    A way to think about it

    Think of everything that affects a result besides hyperparameters: the data, the random seed, the code, the library versions.

  4. Setting flush_every to 100 makes logging cheaper. What do you trade away, and for which kind of run is that a poor trade?
    A way to think about it

    Consider a long run that is killed outright by the operating system. Count how much of its recent curve you can still read.

  5. You run 200 configurations and pick the one with the best validation loss. Why might its test loss disappoint, even with no bug?
    A way to think about it

    Each validation loss is true quality plus noise. Selecting the minimum of 200 favours runs whose noise happened to be negative.