Experiment Tracking & MLOps for Training

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Training a deep network or a tuned ensemble is a loop of change, run, compare. After a few dozen runs nobody remembers which learning rate, data snapshot and code revision produced the best number. Experiment tracking records each run so it can be compared and reproduced, and MLOps extends that discipline to the whole path from data to a monitored production model. This page covers the training side; the serving side is in Deploying & Serving ML Models.

The facts below were checked on 2026-10-30 against Python 3.13, PyTorch 2.15, scikit-learn 1.9, MLflow 3.17.2 and DVC 3.67.1. The Python examples were run on Python 3.13 with PyTorch 2.15 (CPU), scikit-learn 1.9 and MLflow 3.17.2 against a local tracking server on 2026-11-01; the DVC, pipeline and CI commands follow the official documentation and were not executed. The basics of pinned environments, seeds, a first DVC pipeline and a first MLflow run are introduced in Reproducibility & MLOps Basics. This page builds on it: it assumes you have read that page and goes further into deep-learning runs, registries and automation. The wider LLM-focused practices (prompt and model management, evaluation in CI, governance) are in Prompt and Model Management, Evaluation in CI and Data Operations.

What to record for every run

A run is reproducible when each of its inputs is either fixed or written down. For model training that means:

Input What to record

Code

Git commit hash and whether the working tree was dirty; the exact command line.

Data

A version identifier of the training, validation and test data: a content hash (DVC), a dated snapshot, or a table version. Never "the CSV in the shared folder".

Environment

Python and library versions (a lock file), CUDA and driver versions, hardware (GPU model and count).

Parameters

Every hyperparameter, including the ones that look like defaults: learning rate, batch size, schedule, weight decay, architecture sizes, augmentation, number of epochs, early stopping settings.

Randomness

The seeds for Python, NumPy and the framework, and whether deterministic algorithms were enabled (see Training Deep Networks). Bit-for-bit reproducibility on GPUs needs extra settings and still costs speed.

Metrics

Training and validation curves per step or epoch, the final test metrics, wall-clock time and cost.

Artifacts

The model weights, the preprocessing objects, plots, confusion matrices and sample predictions.

Record the test metric once, for the model you chose, after all comparisons are done. Comparing many runs on the test set turns it into a validation set (see Model Evaluation & Validation). For the process of tuning itself, see Deep Learning Tuning Playbook.

The tool landscape

Tool Role

MLflow

Open source. Tracking server and UI, model packaging with signatures, registry, evaluation, deployment, and (in version 3) tracing and evaluation for generative-AI applications. The default open-source choice.

DVC

Open source. Git-style versioning of large data and models plus reproducible pipelines (dvc.yaml) and experiments; storage on S3, GCS, Azure, SSH and others.

Weights & Biases, Neptune, Comet, ClearML

Hosted (or self-hosted) tracking products with rich dashboards, sweeps and collaboration. Compare current pricing and data-residency terms.

TensorBoard

Visualises scalars, histograms, graphs and embeddings from SummaryWriter (PyTorch) or the Keras TensorBoard callback. Good for curves, weak as a registry.

Orchestrators and platforms

Kubeflow, Airflow, Dagster, Prefect, Vertex AI, SageMaker, Azure ML, Databricks. They schedule and run pipelines; most integrate with MLflow.

Feature stores

Feast and the cloud equivalents keep feature definitions identical between training and serving.

Tools matter less than the habit. A plain CSV of runs plus Git beats an unused platform; pick the smallest tool the team will keep using.

MLflow 3

MLflow 3 organises work into experiments that contain runs. A run stores parameters, metrics (optionally per step), tags, and artifacts. In MLflow 3, a logged model is a first-class LoggedModel entity that links to the run that produced it, the metrics and the evaluation datasets, and a model can be registered under a name in the Model Registry.

Start a local tracking server with a SQL backend (recommended over the plain file store for anything beyond a demonstration) and open the UI:

pip install "mlflow>=3.17,<4" scikit-learn
mlflow server --backend-store-uri sqlite:///mlflow.db --default-artifact-root ./mlartifacts --port 5000

The following script tracks a scikit-learn run with parameters, cross-validated and test metrics, a plot and a logged model with an inferred signature. It does one run per hyperparameter value so the UI can compare them.

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import mlflow
import mlflow.sklearn
from mlflow.models import infer_signature
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import ConfusionMatrixDisplay, roc_auc_score
from sklearn.model_selection import cross_val_score, train_test_split

mlflow.set_tracking_uri("http://localhost:5000")
mlflow.set_experiment("breast-cancer-hgb")

X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)

for learning_rate in (0.03, 0.1, 0.3):
    params = {"learning_rate": learning_rate, "max_iter": 200, "random_state": 0}
    with mlflow.start_run(run_name=f"hgb-lr-{learning_rate}"):
        mlflow.log_params(params)
        mlflow.set_tags({"data_version": "sklearn-builtin", "stage": "tuning"})

        model = HistGradientBoostingClassifier(**params)
        cv = cross_val_score(model, X_train, y_train, cv=5, scoring="roc_auc")
        mlflow.log_metric("cv_auc_mean", cv.mean())
        mlflow.log_metric("cv_auc_std", cv.std())

        model.fit(X_train, y_train)
        mlflow.log_metric("test_auc", roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]))

        fig, ax = plt.subplots()
        ConfusionMatrixDisplay.from_estimator(model, X_test, y_test, ax=ax)
        mlflow.log_figure(fig, "confusion_matrix.png")
        plt.close(fig)

        signature = infer_signature(X_test, model.predict(X_test))
        mlflow.sklearn.log_model(
            model,
            name="model",
            signature=signature,
            input_example=X_test.iloc[:3],
            # skops (the default format) asks you to trust this scikit-learn internal type
            skops_trusted_types=["sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor"],
        )

Details of this call:

  • mlflow.sklearn.log_model takes name; the argument was called artifact_path in MLflow 2 and tutorials written for it need updating.

  • MLflow 3 saves scikit-learn models in the skops format by default, which refuses to save a model whose types are not on its trusted list. HistGradientBoostingClassifier needs its internal TreePredictor type listed in skops_trusted_types; without it log_model raises an MlflowException naming the untrusted type. Trust only types you have reviewed, or pass serialization_format="cloudpickle" for files you will only load yourself.

  • infer_signature records input and output column names and types. The signature is validated when the model is loaded as a pyfunc model, which turns a wrong column order into an error instead of silently wrong predictions.

  • The test metric appears here only because the example has no separate selection step; in a real tuning loop log it only for the finalist.

  • mlflow.sklearn.autolog() logs parameters, metrics, the model and (for search classes) the child runs automatically. Autologging exists for scikit-learn, PyTorch Lightning, Keras, XGBoost, LightGBM and others. It is convenient for a start, but explicit logging documents what you consider important and avoids surprises when a library changes.

Tracking a PyTorch training loop

Log hyperparameters once and metrics per epoch with the step argument so the UI can plot curves.

import mlflow
import mlflow.pytorch
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

torch.manual_seed(0)
X = torch.randn(2048, 16)
y = (X[:, 0] + X[:, 1] > 0).long()
train_loader = DataLoader(TensorDataset(X[:1600], y[:1600]), batch_size=64, shuffle=True)
X_val, y_val = X[1600:], y[1600:]

config = {"hidden": 32, "lr": 1e-2, "epochs": 20, "weight_decay": 1e-4}
model = nn.Sequential(nn.Linear(16, config["hidden"]), nn.ReLU(), nn.Linear(config["hidden"], 2))
optimizer = torch.optim.AdamW(model.parameters(), lr=config["lr"], weight_decay=config["weight_decay"])
loss_fn = nn.CrossEntropyLoss()

mlflow.set_experiment("toy-classifier")
with mlflow.start_run():
    mlflow.log_params(config)
    mlflow.log_param("torch_version", torch.__version__)
    for epoch in range(config["epochs"]):
        model.train()
        for xb, yb in train_loader:
            optimizer.zero_grad()
            loss = loss_fn(model(xb), yb)
            loss.backward()
            optimizer.step()
        model.eval()
        with torch.inference_mode():
            val_logits = model(X_val)
            val_loss = loss_fn(val_logits, y_val).item()
            val_acc = (val_logits.argmax(dim=1) == y_val).float().mean().item()
        mlflow.log_metrics({"val_loss": val_loss, "val_accuracy": val_acc}, step=epoch)
    mlflow.pytorch.log_model(model, name="model", input_example=X_val[:2].numpy())

For checkpoints during long runs, save the model, optimizer, scheduler, gradient scaler and random-number-generator states so a preempted job resumes exactly (see Training Deep Networks) and log the best one with mlflow.log_artifact. Writing to local disk first and uploading the final file keeps the tracking server out of the hot path. Hugging Face Trainer supports report_to="mlflow" (or "wandb", "tensorboard") for the same purpose.

The model registry and aliases

The registry gives a model a stable name and numbered versions with metadata, so that serving code asks for "the production model" rather than a file path. MLflow’s older stages (Staging, Production) are deprecated; use aliases (movable named pointers such as champion and challenger) and tags instead.

import mlflow
from mlflow import MlflowClient

mlflow.set_tracking_uri("http://localhost:5000")
client = MlflowClient()

run_id = client.search_runs(
    experiment_ids=[client.get_experiment_by_name("breast-cancer-hgb").experiment_id],
    order_by=["metrics.cv_auc_mean DESC"],
    max_results=1,
)[0].info.run_id

# register the logged model of the best run under a name
version = mlflow.register_model(f"runs:/{run_id}/model", "breast-cancer-classifier")

client.set_model_version_tag("breast-cancer-classifier", version.version, "validated_by", "ci")
client.set_registered_model_alias("breast-cancer-classifier", "champion", version.version)

# consumers load by alias, so a rollback is moving the alias back
model = mlflow.pyfunc.load_model("models:/breast-cancer-classifier@champion")
print(model.metadata.signature)

Treat a promotion as a pull request: it should require passing automated checks (metrics above a threshold on a frozen evaluation set, a latency test, a data-schema test, a fairness check) and leave an audit trail. mlflow models serve -m "models:/breast-cancer-classifier@champion" starts a local scoring server for smoke tests; production serving options are in Deploying & Serving ML Models.

MLflow 3 also introduced tracing and evaluation for generative-AI applications, which is covered from the LLM side in Observability Platforms and Evaluation Methodology.

DVC: data and pipelines

Git is a poor store for gigabytes of data. DVC keeps small pointer files (.dvc files and dvc.lock) in Git and the content in a remote (S3, GCS, Azure Blob, SSH, a local directory). The pointer file contains a content hash, so a Git commit identifies an exact dataset.

git init && dvc init
dvc remote add -d storage s3://my-bucket/dvc-store      # or a local path for a trial
dvc add data/raw/train.csv                              # creates data/raw/train.csv.dvc, ignores the CSV in Git
git add data/raw/train.csv.dvc data/raw/.gitignore .dvc/config
git commit -m "Track raw training data with DVC"
dvc push                                                # upload content to the remote

# elsewhere, or later:
git checkout <commit>
dvc pull                                                # restore exactly that data version

A pipeline describes stages with their dependencies, parameters, outputs and metrics. DVC reruns only the stages whose inputs changed.

# params.yaml
train:
  learning_rate: 0.1
  max_iter: 200
  seed: 0
# dvc.yaml
stages:
  prepare:
    cmd: python src/prepare.py data/raw/train.csv data/prepared
    deps:
      - src/prepare.py
      - data/raw/train.csv
    outs:
      - data/prepared
  train:
    cmd: python src/train.py data/prepared models/model.joblib
    deps:
      - src/train.py
      - data/prepared
    params:
      - train.learning_rate
      - train.max_iter
      - train.seed
    outs:
      - models/model.joblib
    metrics:
      - metrics/scores.json:
          cache: false
    plots:
      - metrics/roc.csv:
          x: fpr
          y: tpr
dvc repro                         # run what is out of date, write dvc.lock
dvc params diff                   # parameters changed since the last commit
dvc metrics diff                  # metric changes since the last commit
dvc exp run -S train.learning_rate=0.3 --name lr-0.3   # an experiment, not committed to Git
dvc exp show                      # table of experiments, params and metrics
dvc exp apply lr-0.3              # make an experiment the workspace state, then commit it

dvc.lock records the exact hashes of every dependency and output, which makes the pipeline’s result verifiable: dvc status reports which stages are out of date. DVC and MLflow overlap in tracking experiments but differ in emphasis: DVC is strongest at data and pipeline versioning with Git semantics; MLflow is strongest at the tracking UI, packaging and registry. Many teams use both, with a DVC stage calling a training script that logs to MLflow.

From scripts to a pipeline

A notebook is for exploration; a repeatable run is a script or pipeline with explicit inputs. A common project layout is: src/ for importable code (data loading, features, model, training, evaluation), configs/ or params.yaml for parameters, tests/ for unit and data tests, dvc.yaml for the pipeline, and a lock file for the environment. Configuration systems such as Hydra or plain YAML plus command-line overrides keep hyperparameters out of code. Parameter sweeps run through Optuna (see Grid, Randomized & Halving Search for the scikit-learn tools) log each trial as a child run.

Test the things that break silently: schema and range checks on input data, a unit test that a tiny model overfits a tiny batch (a correctly wired training loop must be able to), an invariance test (the metric must not change when the row order is shuffled), and a regression test against the last accepted metric.

CI, CD and continuous training

MLOps usually distinguishes three automation loops:

  • CI (continuous integration): on every change, run linting, unit and data tests and a small training smoke test.

  • CD (continuous delivery): package the model with its serving code into a versioned image or registry entry and deploy it through a gated release (shadow, canary, rollback as described in Deploying & Serving ML Models).

  • CT (continuous training): retrain on new data automatically, on a schedule or when monitoring detects drift, then pass the new model through the same evaluation gate as a human-built one.

flowchart LR data["Versioned data (DVC)"] --> train["Training pipeline (dvc repro)"] code["Code and params (Git)"] --> train train --> track["Runs, metrics, artifacts (MLflow)"] track --> gate{"Passes evaluation gate?"} gate -- no --> iterate["Change data, features or params"] iterate --> train gate -- yes --> registry["Model registry: new version"] registry --> release["Shadow, canary, then alias champion"] release --> monitor["Monitoring: latency, drift, quality"] monitor -- "drift or decay" --> data

GitHub Actions, GitLab CI or Jenkins run the CI part; CML (Continuous Machine Learning, an open-source companion to DVC) posts metrics and plots into pull requests. Heavy GPU training is usually submitted to an orchestrator or cloud service from the pipeline rather than run on the CI runner.

Monitoring and feedback

Production monitoring closes the loop and feeds the next training run: service health, input drift, prediction drift, and delayed ground-truth quality, as described in Deploying & Serving ML Models and, for generative systems, Drift and Regression Monitoring. Log a sample of production inputs and predictions (with attention to privacy) so that mislabelled or surprising cases can be added to the next training set.

Principles from "Rules of Machine Learning"

Google’s practical guide recommends several habits that remain current:

  • Launch a simple, well-instrumented first model before a clever one; the pipeline is the hard part.

  • Make the first pipeline robust and measurable: monitor freshness of features and models, and treat silent failures (stale tables, dropped columns) as bugs.

  • Keep training and serving feature code identical to avoid skew; log features at serving time and train on the logged values.

  • Version everything that can change an outcome, and keep a rollback.

  • Use human review of errors, not only aggregate metrics, to decide what to build next.

The older caution from the "Hidden Technical Debt" paper still applies: data dependencies, undeclared consumers of a model’s output, glue code, and configuration debt cost more over the years than the model’s accuracy gain.

Pitfalls

  • Logging only the final number. Without parameters, data version and code revision, the number cannot be reproduced.

  • Tracking server as a single point of failure. Buffer locally and upload at the end of a run; use a managed database for the backend store.

  • Using the test set during selection. Log the test metric for the chosen run only.

  • MLflow 2 snippets in MLflow 3. artifact_path is now name for logging models, and registry stages are replaced by aliases.

  • Treating DVC as backup. It versions data you add; it does not capture what you forgot to track. Check dvc status and git status together.

  • Secrets in tracked parameters. Never log credentials; tracking servers are readable by many people.

  • Non-deterministic reruns taken as bugs. GPU training varies run to run unless determinism is enforced; compare distributions over several seeds before concluding that one setting is better.

  • Promotion by hand. A model that reaches production through a manual copy has no audit trail.