Experiment Tracking & Model Versioning
After this lesson, you will be able to:
- Track every experiment's hyperparameters, metrics, code version, data version, and artifacts in a system of record (W&B, MLflow, Comet, Neptune)
- Use a model registry to manage model versions, lifecycle stages, and approvals for production deployment
- Apply DVC or LakeFS to version datasets alongside code so any experiment is fully reproducible months later
- Recognize when 'it worked on my notebook' becomes 'I can't reproduce my best model from 6 months ago', and the patterns that prevent it
Before you start
#What to Track
| Layer | What | Why |
|---|---|---|
| Hyperparameters | LR, batch size, model size, dropout, optimizer | Reproducibility |
| Metrics | Train/val/test loss, accuracy, F1, custom domain metrics | Best-model selection |
| System metrics | GPU utilization, memory, FLOPs, time-per-step | Cost optimization |
| Code | Git commit SHA, branch, dirty-state warning | Reproducibility |
| Data | Dataset version (DVC hash), preprocessing config | Reproducibility |
| Artifacts | Model weights, configs, plots, sample outputs | Comparison + audit |
| Environment | Python version, package versions (pip freeze), CUDA version | Reproducibility |
#The Major Players in Depth
The market has consolidated around five names. Each makes different tradeoffs; picking the wrong one is annoying but rarely catastrophic, most can export to a common format if you decide to migrate.
| Tool | Hosted / OSS | Strengths | Weaknesses |
|---|---|---|---|
| W&B (Weights & Biases) | Hosted SaaS + self-host | Best UI; collaboration features (reports, sweeps, tables); huge ecosystem | Most expensive at scale; vendor lock-in |
| MLflow | OSS, you host | Free; widely integrated (Databricks built-in); model registry mature | UI dated; multi-team collaboration weaker |
| Comet | Hosted SaaS | Strong on artifacts and reproducibility reports; experiment diffing | Smaller community than W&B |
| Neptune | Hosted SaaS | Lightweight; very fast logging; clean Python API | Fewer integrations; less collaboration tooling |
| ClearML | OSS + hosted | Adds orchestration + agents (think W&B + light Airflow); good for self-hosted teams | Steeper learning curve |
A pragmatic 2026 decision matrix:
- Solo / small team, budget-flexible: W&B Personal (free tier). Best UI, no infra.
- Larger team, budget pressure or compliance: MLflow self-hosted on K8s + S3. Free; works.
- Research lab on Databricks already: Databricks Managed MLflow. Already paid for.
- Need real-time experiment logging from millions of metrics: Neptune. Built for that volume.
- Want orchestration + tracking unified: ClearML or Metaflow.
#What to track at minimum
Across all of them, the must-log list is the same. Memorize it as a checklist:
- Code: git SHA, branch, dirty-state warning (uncommitted changes are a reproducibility risk).
- Data: dataset hash (DVC, LakeFS) or pointer to the immutable snapshot (S3 path with version ID).
- Hyperparameters: every value that affects the result, including the random seed.
- Metrics: train/val/test loss AND domain-specific metrics, logged per-step.
- System metrics: GPU utilization, memory, FLOPs, wall-clock per step.
- Environment:
pip freeze, Python version, CUDA version, container image SHA, GPU model. - Artifacts: the model weights, configs, sample predictions, confusion matrices, gradient-norm plots.
- Tags: experiment family, model architecture, project, team owner, anything you'll want to filter on later.
If any of those eight is missing, your "best run from 6 months ago" is partially unreproducible.
#Hyperparameter Sweeps and the Tie-In to Track 03
# W&B sweep config (canonical 2026 shape)
sweep_config = {
"method": "bayes", # vs "grid" or "random"
"metric": {"name": "val_loss", "goal": "minimize"},
"parameters": {
"lr": {"distribution": "log_uniform_values", "min": 1e-5, "max": 1e-2},
"batch_size": {"values": [16, 32, 64, 128]},
"weight_decay": {"distribution": "log_uniform_values", "min": 1e-6, "max": 1e-2},
"dropout": {"distribution": "uniform", "min": 0.0, "max": 0.5},
},
"early_terminate": {"type": "hyperband", "min_iter": 3}, # kill bad runs early
}
sweep_id = wandb.sweep(sweep_config, project="my-experiment")
wandb.agent(sweep_id, function=train_one_run, count=50)optuna script: every sweep run is automatically logged, tagged, and visible in the same UI you use for one-off runs. You can filter the leaderboard by sweep_id, plot parameter-importance charts, and re-launch the top-K runs with longer schedules. MLflow has similar machinery via mlflow.projects + Hyperopt; Comet wraps Optuna.Why rerun with 5 seeds and compare mean and standard deviation? The uncertainty of a mean over n runs shrinks like sigma divided by the square root of n, derived in Sampling, Standard Error & the Central Limit Theorem.
A research team runs a 200-trial Bayesian sweep using their tracking tool. The leaderboard shows three runs in a tight cluster at the top, with val_loss 0.342, 0.343, 0.344. Statistical noise or real differences?
#Leaderboards and Collaboration Patterns
A tracker's leaderboard becomes the team's shared truth, but only if everyone agrees on what's logged. Three patterns that scale across teams:
- Required tags policy. Enforced by a thin wrapper around
mlflow.start_run()/wandb.init()that refuses to start a run withoutproject,owner,dataset_version, andgit_shaset. A 10-line decorator saves quarters of "what was this run?" archaeology. - Standardized eval suites. A common holdout set (or set of holdouts) every run is evaluated against, logged under canonical metric names. Without this, two runs claiming
val_acc=0.92may be measuring different things and you can't trust the leaderboard. - Reports as the artifact. W&B Reports and MLflow's Markdown UI let you compose narrative artifacts (charts, tables, prose) that link directly to runs. The "report" replaces the death-by-PowerPoint review meeting, reviewers click into individual runs from the prose.
#Tools (2026)
| Tool | Best for |
|---|---|
| W&B (Weights & Biases) | Industry standard, best UI, expensive at scale |
| MLflow | Open-source, self-hostable, good baseline |
| Comet | Strong artifacts/reports, good for research teams |
| Neptune | Lightweight, niche but loyal users |
| TensorBoard | Free, good for local; struggles at team scale |
| ClearML | Open-source W&B alternative |
For most production teams: W&B if budget allows, MLflow if self-hosting required.
#Model Registry: Lifecycle Stages
A model registry tracks model versions with lifecycle states:
None → Staging → Production → Archived
↘ Failed
| Stage | Meaning |
|---|---|
| None | Just trained, no decision made |
| Staging | Candidate for production, in evaluation |
| Production | Currently serving real traffic |
| Archived | Retired, kept for audit/lineage |
Approval gates between stages are critical. "Promote to production" should require: passing eval gates, sign-off from ML lead, monitoring dashboards live.
#Data Versioning with DVC
# Track a dataset
dvc add data/train.parquet
git add data/train.parquet.dvc
git commit -m "Track v1 dataset"
# Later, retrieve any version
git checkout abc123 # specific commit
dvc pull # pulls the matching dataset
#Hands-On
The MLflow and PyTorch version below needs those libraries and a tracking server, so it does not run on this page. Copy it to Google Colab to try it. The logging stub further down runs here and shows the same call shapes.
# Copy to Colab: needs mlflow, torch, so it cannot run on this page.
# Track an experiment with MLflow + log everything needed for reproducibility
import mlflow
import mlflow.pytorch
import torch
import torch.nn as nn
import subprocess
import sys
mlflow.set_tracking_uri("http://localhost:5000") # or "file:///./mlruns" for local
mlflow.set_experiment("classification-experiment")
# --- Hyperparameters ---
config = {
"learning_rate": 1e-3,
"batch_size": 64,
"epochs": 5,
"model_dim": 128,
"optimizer": "AdamW",
"weight_decay": 1e-4,
}
# --- Mock dataset ---
torch.manual_seed(42)
X = torch.randn(1000, 10)
y = (X.sum(dim=1) > 0).long()
# --- Model ---
class Classifier(nn.Module):
def __init__(self, dim):
super().__init__()
self.fc1 = nn.Linear(10, dim)
self.fc2 = nn.Linear(dim, 2)
def forward(self, x):
return self.fc2(torch.relu(self.fc1(x)))
# --- Training run with full logging ---
with mlflow.start_run() as run:
print(f"MLflow run ID: {run.info.run_id}")
# 1. Log hyperparameters
mlflow.log_params(config)
# 2. Log environment
try:
sha = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
dirty = subprocess.check_output(["git", "status", "--porcelain"], text=True).strip()
mlflow.set_tag("git_sha", sha)
mlflow.set_tag("git_dirty", bool(dirty))
except Exception:
mlflow.set_tag("git_sha", "unknown")
mlflow.set_tag("python_version", sys.version)
mlflow.set_tag("torch_version", torch.__version__)
# 3. Train + log metrics per epoch
model = Classifier(config["model_dim"])
opt = torch.optim.AdamW(model.parameters(), lr=config["learning_rate"], weight_decay=config["weight_decay"])
loss_fn = nn.CrossEntropyLoss()
for epoch in range(config["epochs"]):
# Mini-batch training
idx = torch.randperm(len(X))
total_loss = 0.0
for i in range(0, len(X), config["batch_size"]):
batch_idx = idx[i:i + config["batch_size"]]
opt.zero_grad()
out = model(X[batch_idx])
loss = loss_fn(out, y[batch_idx])
loss.backward()
opt.step()
total_loss += loss.item()
# Log per-epoch metrics
with torch.no_grad():
preds = model(X).argmax(dim=-1)
acc = (preds == y).float().mean().item()
mlflow.log_metrics({"loss": total_loss / (len(X) / config["batch_size"]), "accuracy": acc}, step=epoch)
print(f"Epoch {epoch}: loss={total_loss:.3f} acc={acc:.3f}")
# 4. Log the model itself
mlflow.pytorch.log_model(model, "model", registered_model_name="classifier")
print("\nNow open http://localhost:5000 to see the run in the UI.")
print("Compare runs across hyperparameters; reproduce any past experiment via the run ID.")
print("\nCHALLENGE: Run 5 experiments with different learning rates [1e-2, 5e-3, 1e-3, 5e-4, 1e-4].")
print("Use the MLflow UI to find the best run; promote it to 'Staging' in the model registry.")
# --- Solution sketch ---
# Promote to staging:
# from mlflow.tracking import MlflowClient
# client = MlflowClient()
# client.transition_model_version_stage(name='classifier', version=5, stage='Staging')
#
# Then a separate eval pipeline picks up the staging model, runs it through validation,
# and either promotes to Production or rejects to Failed.#A Minimal Logging Stub (W&B and MLflow side-by-side)
The actual API surface for logging is small. Below is a runnable stub that simulates both W&B-style and MLflow-style logging, same data, two protocols. Use it to practice the shape; then drop it into a real script.
Practice swapping between the two shapes is the cheapest way to understand the data model that sits behind both. Once you see that "config / params / hyperparameters" all mean the same thing, that "tags / set_tag / metadata" are the same thing, and that "log / log_metric / log_metrics" are step-indexed scalar time series, you can switch platforms without re-learning anything.
A team logs `train_loss` and `val_loss` every step but no `epoch` field. After 200 runs, they want to plot mean val_loss at the end of epoch 5 across all runs. What's wrong?
#Key Takeaways
- Track everything. Hyperparameters, metrics, system metrics, code SHA, data hash, environment, artifacts; storage is cheap, lost knowledge is expensive
- W&B and MLflow are the dominant tools. W&B for premium UI, MLflow for self-hosted open-source
- Model registries enforce promotion gates. None → Staging → Production with required approvals
- Data versioning with DVC. Git-like ops on datasets, essential for reproducibility
- EU AI Act mandates lineage. Data hash → training run → deployed model → user request
#Quick Check
Why is data versioning (DVC) needed in addition to code versioning (Git)?
Your team self-hosts MLflow. After 18 months they have 12,000 runs. The UI is slow; queries take 30+ seconds; some runs are missing artifacts. Most likely root cause?