🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Experiment Tracking: Run Records That Actually Reproduce

MLOpsExperiment Tracking⭐ Premium

Experiment Tracking: Run Records That Actually Reproduce

Difficulty: Senior Level | Companies: Google, Meta, Netflix, Uber, Stripe

Prerequisites

  • !Training a scikit-learn or PyTorch model
  • !Knowing what hyperparameters and metrics are
  • !Comfort reading a Python training script

What You'll Learn

  • 1Define the minimum fields a reproducible run record needs
  • 2Log parameters, metrics, and artifacts with MLflow in a training loop
  • 3Stream epoch-level metrics from PyTorch into Weights & Biases
  • 4Choose the right metric and comparison method when picking a winner

The question tracking has to answer

Six weeks after a model ships, someone will ask why version three is worse than version two, and the only honest answer should come from a database rather than a colleague's memory. Experiment tracking exists to make that answer boring. Without it, teams rebuild the same random forest four times because the winning configuration lived in a terminal scrollback, and the "improvement" later turns out to have come from a different train-test split rather than a better model. Reproducibility is not an academic nicety here — it is what separates a measured improvement from a coincidence that happens to have a chart attached.

The trap is that tracking feels like bookkeeping you can start later. In practice the metadata you wish you had recorded is exactly the metadata that disappears: the seed, the data snapshot identifier, the commit hash of the feature code, the reason a run was abandoned. Every one of those is cheap to capture at run time and nearly impossible to reconstruct afterwards. Treat the tracker as a flight recorder, not a reporting tool — it writes continuously, and you only read it when something goes wrong.

What a complete run record contains

A useful run has four categories of information, and most "unreproducible" experiments fail on the third and fourth. Parameters describe what you deliberately chose: learning rate, tree depth, embedding dimension. Metrics describe what you measured: accuracy, F1, latency, training loss per epoch. Artifacts are the things a number cannot represent: the serialized model, the confusion matrix, the feature importance file, the sample of misclassified rows. Context is everything you did not choose but that still changes the answer: git commit, data version, library versions, random seed, and hardware.

CategoryExamplesCaptured howFailure when missing
Parameterslearning rate, batch size, regularizationExplicit log call before trainingTuning decisions silently repeat
Metricsaccuracy, F1, loss curvesLogged per epoch or per evaluationYou cannot rank runs or spot overfitting
Artifactsmodel weights, plots, eval tablesUpload at run completionThe best model cannot be served or audited
Contextcommit hash, data version, seedAuto-captured from the environmentTwo identical runs disagree and nobody knows why
Statusrunning, failed, killed, durationUpdated on exitDead runs crowd the comparison view

Note the last row. A tracker that only stores completed runs teaches you to distrust it, because engineers then keep a side spreadsheet of the runs that crashed. Record failures too, along with duration and the error string — the pattern of what fails is often more informative than the leaderboard.

Logging a full scikit-learn run with MLflow

MLflow keeps the surface area small: set an experiment, start a run, log each category, and close the run. The wrapper below is deliberately defensive — it captures the environment, records metrics from a held-out set, and always marks the run failed if training raises, so the comparison view never hides a crash.

python
# mlflow_tracking.py
import hashlib
import platform
import subprocess
from typing import Any, Dict

import mlflow
import mlflow.sklearn
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score


def git_commit() -> str:
    try:
        out = subprocess.run(
            ["git", "rev-parse", "HEAD"],
            capture_output=True, text=True, timeout=5,
        )
        return out.stdout.strip() or "unknown"
    except Exception:
        return "unknown"


def log_environment() -> None:
    mlflow.log_param("git_commit", git_commit())
    mlflow.log_param("python", platform.python_version())
    mlflow.log_param("platform", platform.platform())


def train_and_track(model, params: Dict[str, Any], X_train, X_test, y_train, y_test,
                    data_version: str, run_name: str) -> str:
    mlflow.set_experiment("churn-prediction")
    with mlflow.start_run(run_name=run_name) as run:
        try:
            mlflow.log_params(params)
            mlflow.log_param("data_version", data_version)
            mlflow.log_param("n_train", len(X_train))
            mlflow.log_param("n_test", len(X_test))
            log_environment()

            model.fit(X_train, y_train)
            y_pred = model.predict(X_test)

            metrics = {
                "accuracy": accuracy_score(y_test, y_pred),
                "f1": f1_score(y_test, y_pred, average="weighted"),
                "precision": precision_score(y_test, y_pred, average="weighted", zero_division=0),
                "recall": recall_score(y_test, y_pred, average="weighted", zero_division=0),
            }
            mlflow.log_metrics(metrics)

            importance = getattr(model, "feature_importances_", None)
            if importance is not None:
                payload = "\n".join(f"{i}\t{float(v):.6f}" for i, v in enumerate(importance))
                mlflow.log_text(payload, "feature_importance.tsv")

            mlflow.sklearn.log_model(model, artifact_path="model")
            return run.info.run_id
        except Exception as exc:
            mlflow.set_tag("status", "failed")
            mlflow.set_tag("error", str(exc)[:500])
            raise

Two details in that code are worth more than they look. Hashing the data snapshot into data_version means a run can never claim a metric on data you no longer have. And logging the test set size next to the metrics stops the classic mistake of comparing a model evaluated on 400 rows against one evaluated on 40,000, which will look different purely through variance.

Streaming epoch metrics from PyTorch into W&B

Deep training needs step-level curves rather than a single end-of-run score, and that is where Weights & Biases earns its place. The pattern is the same — configuration in, curves and artifacts out — but the granularity changes: you log on every epoch, and you let the run object carry the hyperparameters so the sweep tooling can read them later.

python
# wandb_training.py
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
import wandb


class MLP(nn.Module):
    def __init__(self, in_dim: int, hidden: int, classes: int):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(in_dim, hidden), nn.ReLU(), nn.Linear(hidden, classes)
        )

    def forward(self, x):
        return self.net(x)


def run_experiment(config: dict) -> dict:
    wandb.init(project="tabular-classification", config=config)
    cfg = wandb.config

    torch.manual_seed(cfg.seed)
    X = torch.randn(4000, cfg.in_dim)
    y = (X[:, 0] + 0.5 * X[:, 1] > 0).long()
    loader = DataLoader(TensorDataset(X, y), batch_size=cfg.batch_size, shuffle=True)

    model = MLP(cfg.in_dim, cfg.hidden, 2)
    opt = torch.optim.Adam(model.parameters(), lr=cfg.lr)
    loss_fn = nn.CrossEntropyLoss()

    for epoch in range(cfg.epochs):
        model.train()
        total, correct, running = 0, 0, 0.0
        for xb, yb in loader:
            opt.zero_grad()
            logits = model(xb)
            loss = loss_fn(logits, yb)
            loss.backward()
            opt.step()
            running += loss.item()
            correct += (logits.argmax(1) == yb).sum().item()
            total += yb.size(0)

        wandb.log({
            "epoch": epoch,
            "train/loss": running / len(loader),
            "train/accuracy": correct / total,
            "lr": opt.param_groups[0]["lr"],
        })

    artifact = wandb.Artifact("mlp-model", type="model")
    torch.save(model.state_dict(), "model.pt")
    artifact.add_file("model.pt")
    wandb.log_artifact(artifact)
    final_acc = correct / total
    wandb.summary["final_accuracy"] = final_acc
    wandb.finish()
    return {"accuracy": final_acc}


if __name__ == "__main__":
    run_experiment({"lr": 1e-3, "batch_size": 64, "hidden": 128,
                    "epochs": 8, "in_dim": 20, "seed": 42})

Note that the seed is part of the configuration. If a run is not seed-pinned, its metric carries an unmeasured error bar, and ranking two runs that differ by 0.4% becomes an exercise in reading noise.

Comparing runs without lying to yourself

Selecting a winner is where tracking systems most often mislead. Sorting a table by accuracy descending is fine when runs share a split and a seed; it is worthless otherwise, because a single test set estimate moves by a percentage point or two just through resampling. Before comparing, filter to runs with the same data_version and the same evaluation protocol, then look at metric distributions across seeds rather than one number. If you only have one seed, treat any gap smaller than roughly one percentage point as a tie and go collect more evidence.

The second trap is multiple comparisons. If you tried thirty configurations and the best one beat baseline by 2%, the honest expectation of that lead is much smaller than it looks — some of that gap is the winner's curse of having picked the maximum. A cheap correction is to confirm the winner on a fresh holdout that the search never touched, or to report the mean and standard deviation across five seeds for the top three candidates rather than the single best score.

Naming, tagging, and the taxonomy that scales

Run names are for humans; tags are for queries. Prefix run names with the model family and the purpose — rf-baseline, gbdt-tuned-round2 — so the UI stays readable, and put the machine-queryable facts in tags: team, dataset version, stage, whether the run is a sweep member. Experiments should map to a business question rather than to a framework: one experiment for churn prediction, another for lifetime value, rather than one experiment per notebook file.

Keep parameter names identical across experiments. learning_rate, lr, and Lr will fragment every chart you ever build, and a shared naming convention is one of the few tracking decisions that is expensive to change later. A simple lint in CI that rejects new parameter spellings outside an approved list costs ten lines and saves an argument every quarter.

💡Capture the failure, not just the win

Tag failed runs with the error message and keep them. The fastest way to notice that a data pipeline changed is a sudden cluster of runs failing at the same step, which you will never see if crashes are discarded before they reach the tracker.

Common Mistakes

Logging only the final metric of a training run

Fix: Log per-epoch curves as well, so overfitting and divergence are visible instead of inferred from one number.

Comparing runs produced on different data snapshots

Fix: Record a data version or snapshot hash with every run and filter on it before any comparison.

Leaving the random seed out of the configuration

Fix: Store the seed as a parameter and repeat the top candidates across several seeds before declaring a winner.

Letting every notebook invent its own parameter names

Fix: Keep one approved vocabulary and enforce it with a lightweight check in CI.

Best Practices

  • Log parameters before fitting so a crashed run still records what it attempted
  • Attach the environment: commit hash, Python version, and key library versions
  • Version artifacts through the tracker rather than a shared model folder
  • Separate business-question experiments from framework-specific scratch work
  • Review the run list weekly and archive runs nobody has queried in a quarter

Interview Questions

Q1: What is the minimum you must log to reproduce a training run?

Code version, data version, hyperparameters, random seed, environment versions, and the evaluation definition — metrics alone are not reproducible.

Q2: MLflow or Weights and Biases: how do you choose?

Self-hosting requirements and collaboration style. MLflow suits artifact and registry-centric workflows you control; W&B suits teams that want rich interactive charts and sweeps with minimal operations.

Q3: Why might the best run in a sweep not be the best model?

Winner's curse from many comparisons plus single-seed variance. Confirmation on untouched data resolves it.

Q4: How do you track experiments across distributed workers?

Give each worker its own run with a shared experiment, tag the parent sweep identifier, and aggregate by that tag rather than merging runs into one writer.

Key Takeaways

  • A run record needs parameters, metrics, artifacts, context, and status to be reproducible
  • Record data version and evaluation protocol, or comparisons are meaningless
  • MLflow suits end-of-run logging; W&B suits step-level curves and sweeps
  • Rank runs only within an identical split and seed, and confirm winners on fresh data
  • Keep failed runs with their errors — they are your earliest change detector
🔒

Premium Content

Experiment Tracking: Run Records That Actually Reproduce

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement