Experiment Tracking and Model Registry with MLflow
The most common reproducibility failure in applied ML is not a lost dataset â it is a lost decision. Someone trains a gradient boosting model at 2:00 AM, notes "0.91 AUC" in a Slack thread, and three weeks later nobody can reconstruct which data snapshot, feature set, or hyperparameter combination produced it. Experiment tracking closes that gap by making every run an immutable record: parameters, metrics, code version, environment, and artifacts, all queryable.
MLflow is the most widely adopted open-source tool for this job. Its Tracking server records runs; its Models abstraction packages a model with everything needed to load and serve it; its Registry adds versioning and stage transitions for governance. This lesson covers the tracking API in depth, patterns for organizing sweeps and pipelines, and the registry workflows that separate "a model exists" from "this exact model version is approved for production".
What You'll Learn
- 1Log parameters, metrics, models, and artifacts with the MLflow tracking API
- 2Structure nested runs for hyperparameter sweeps and pipelines
- 3Package custom models with pyfunc flavors and signatures
- 4Promote model versions through registry stages with tags and approval metadata
Prerequisites
- !scikit-learn model training
- !Basic command line and HTTP
- !Understanding of model serialization concerns
The four components and when you need each
MLflow is often described as four packages, but you adopt them gradually. Tracking is the part you need on day one â even a local file-based store beats notebooks, because it turns an informal "I think the run with dropout 0.3 was better" into a queryable record with parameters, metrics, and the exact model artifact attached. Projects pin environment definitions (conda.yaml or MLproject) for reproducing a training entry point on someone else's machine. Models standardizes how a trained artifact is logged and loaded across frameworks through flavors â sklearn, pytorch, transformers, pyfunc â so a colleague can load your model without knowing which library trained it. Registry adds a model-name-centric view with versions and stages, which matters once more than one person ships models and someone must answer "which version is live in production right now".
A minimal tracking-only setup runs as a single Python package and writes to ./mlruns, which is enough for solo experimentation and survives laptop-to-laptop collaboration via a shared folder. A shared team setup runs the tracking server backed by a database (SQLite for small teams, Postgres for larger ones) and object storage for artifacts (S3, GCS, or Azure Blob), with access control so experiments stay private to their teams. Start local; migrate later by pointing the tracking URI at the server â the client API does not change, so nothing in your training scripts needs rewriting.
| Component | Solves | You need it when |
|---|---|---|
| Tracking | Lost parameters, metrics, artifacts | Day one â even solo |
| Projects | "Works on my machine" training envs | Multiple contributors, scheduled retraining |
| Models | Framework-specific packaging | Serving or sharing models across tools |
| Registry | Which version is approved for prod | Multiple model versions, compliance needs |
Logging a training run end to end
The tracking API centers on start_run. Everything logged inside the context is attached to that run: log_params for the configuration, log_metric for scalars (multiple steps supported), log_model for the packaged artifact, and log_artifact for any file â plots, confusion matrices, sliced metrics.
import mlflow
import mlflow.sklearn
import mlflow.models
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import (accuracy_score, f1_score, roc_auc_score,
confusion_matrix, classification_report)
mlflow.set_tracking_uri("http://localhost:5000")
mlflow.set_experiment("breast-cancer-screening")
X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
params = {"n_estimators": 300, "max_depth": 3, "learning_rate": 0.05,
"subsample": 0.8, "random_state": 42}
with mlflow.start_run(run_name="gbm-baseline") as run:
mlflow.log_params(params)
mlflow.set_tags({"stage": "baseline", "author": "data-science",
"dataset": "sklearn-breast-cancer-v1"})
model = GradientBoostingClassifier(**params)
model.fit(X_tr, y_tr)
proba = model.predict_proba(X_te)[:, 1]
pred = (proba >= 0.5).astype(int)
mlflow.log_metrics({
"accuracy": accuracy_score(y_te, pred),
"f1": f1_score(y_te, pred),
"roc_auc": roc_auc_score(y_te, proba),
"train_rows": len(X_tr),
})
signature = mlflow.models.infer_signature(X_tr, model.predict(X_tr))
mlflow.sklearn.log_model(
model, artifact_path="model",
signature=signature,
input_example=X_tr[:3],
registered_model_name="cancer-screening-gbm",
)
print(classification_report(y_te, pred, digits=3))
print(f"run_id={run.info.run_id}")
Two details pay off later. The signature records input and output schemas, so downstream serving code can validate requests instead of failing deep inside a numpy call. The input example generates a saved example the MLflow UI uses for one-click scoring tests. Logging both costs seconds and prevents a class of integration bugs.
Organizing sweeps with nested runs
A flat list of hundreds of runs becomes unsearchable. Nesting creates hierarchy: a parent run for the sweep as a whole, child runs for each configuration. The parent records the best result; children remain individually comparable in the UI.
from itertools import product as cartesian
param_grid = {
"n_estimators": [100, 300],
"max_depth": [3, 5, 7],
"learning_rate": [0.01, 0.05],
}
with mlflow.start_run(run_name="gbm-grid-search") as parent:
best_auc, best_params = 0.0, None
for n_est, depth, lr in cartesian(*param_grid.values()):
cfg = {"n_estimators": n_est, "max_depth": depth,
"learning_rate": lr, "random_state": 42}
with mlflow.start_run(nested=True, run_name=f"n{n_est}_d{depth}_lr{lr}"):
mlflow.log_params(cfg)
clf = GradientBoostingClassifier(**cfg)
clf.fit(X_tr, y_tr)
auc = roc_auc_score(y_te, clf.predict_proba(X_te)[:, 1])
mlflow.log_metric("roc_auc", auc)
if auc > best_auc:
best_auc, best_params = auc, cfg
mlflow.log_params({f"best_{k}": v for k, v in best_params.items()})
mlflow.log_metric("best_roc_auc", best_auc)
print(f"best={best_auc:.4f} params={best_params}")
For searches larger than a few dozen configurations, prefer a search library (Optuna, Ray Tune) and use its MLflow adapter rather than hand-rolling loops. Optuna's integration logs trials automatically and handles pruning â early stopping unpromising configurations â which cuts wall-clock dramatically on expensive models.
Packaging custom models with pyfunc
Real inference rarely equals model.predict(X). Preprocessing, feature assembly, and post-processing live outside the sklearn object. The pyfunc flavor lets you ship a custom Python class that encapsulates the entire transformation chain behind one predict interface, with a pinned environment.
import mlflow.pyfunc
import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
class ScreeningModel(mlflow.pyfunc.PythonModel):
def __init__(self, pipeline: Pipeline, feature_names, threshold: float = 0.5):
self.pipeline = pipeline
self.feature_names = feature_names
self.threshold = threshold
def predict(self, context, model_input: pd.DataFrame):
values = model_input[self.feature_names].to_numpy()
proba = self.pipeline.predict_proba(values)[:, 1]
label = (proba >= self.threshold).astype(int)
return pd.DataFrame({"risk_score": proba, "flag": label})
pipeline = Pipeline([
("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
feature_names = load_breast_cancer().feature_names.tolist()
pipeline.fit(pd.DataFrame(X_tr, columns=feature_names), y_tr)
wrapped = ScreeningModel(pipeline, feature_names, threshold=0.6)
with mlflow.start_run(run_name="screening-pyfunc") as run:
mlflow.pyfunc.log_model(
artifact_path="screening",
python_model=wrapped,
pip_requirements=["scikit-learn==1.4.0", "pandas==2.2.0", "numpy==1.26.0"],
signature=mlflow.models.infer_signature(
pd.DataFrame(X_tr[:3], columns=feature_names),
wrapped.predict(None, pd.DataFrame(X_tr[:3], columns=feature_names)),
),
registered_model_name="cancer-screening",
)
loaded = mlflow.pyfunc.load_model(f"runs:/{run.info.run_id}/screening")
sample = pd.DataFrame(X_te[:2], columns=feature_names)
print(loaded.predict(sample))
The pinned pip_requirements (or a conda environment) is what makes the model loadable next quarter on a different machine. Treat the environment file as part of the model, reviewed in code review like any other dependency change.
Registry stages and promotion workflow
The registry organizes models by name and version. Stages â None, Staging, Production, Archived â encode lifecycle. Promotion is an audited operation: who moved version 4 to Production, when, and on what evidence.
from mlflow.tracking import MlflowClient
client = MlflowClient()
# Register a new version from an existing run
model_uri = f"runs:/{run.info.run_id}/screening"
registered = mlflow.register_model(model_uri, "cancer-screening")
version = registered.version
client.update_model_version(
name="cancer-screening", version=version,
description="Pyfunc screening model, threshold 0.6, validated on holdout 2026-01",
)
client.set_model_version_tag("cancer-screening", version, "validation_auc", "0.981")
client.set_model_version_tag("cancer-screening", version, "reviewer", "a.smith")
# Promote through stages
client.transition_model_version_stage("cancer-screening", version, stage="Staging")
# ... integration tests against Staging ...
client.transition_model_version_stage(
"cancer-screening", version, stage="Production", archive_existing_versions=True
)
# Consumers load by name and stage â no code change at promotion time
production_model = mlflow.pyfunc.load_model("models:/cancer-screening/Production")
for v in client.search_model_versions("name='cancer-screening'"):
print(f"v{v.version}: {v.current_stage} tags={v.tags}")
archive_existing_versions=True enforces a single production version at a time, which prevents the ambiguous state where two "production" models serve different traffic. In newer MLflow releases, Registered Model Aliases (for example @champion and @challenger) complement or replace stages for teams that prefer name-based routing over lifecycle stages â pick one convention and standardize on it across the organization, because mixed conventions are worse than either choice alone.
The registry also becomes the natural home for model governance metadata. Attach tags for validation metrics, training data versions, and the reviewer who approved promotion; store a link to the evaluation report as a model-version artifact. When an auditor asks who approved version 4 for production and on what evidence, those tags and artifacts answer the question without a Slack archaeology expedition. For teams under formal model-risk management, the registry is often the system of record that regulators actually inspect â treat its metadata with the same rigor as the code that generates it.
Serving and the tracking-to-serving handoff
The cleanest handoff is a service that loads by registry reference rather than a baked file path:
from fastapi import FastAPI
import mlflow.pyfunc
import pandas as pd
app = FastAPI(title="Screening Service")
model = mlflow.pyfunc.load_model("models:/cancer-screening/Production")
@app.post("/score")
def score(payload: dict):
df = pd.DataFrame([payload["features"]])
result = model.predict(df)
return {"result": result.to_dict(orient="records")[0],
"model_version": model.metadata.run_id}
@app.get("/model")
def model_info():
return {"run_id": model.metadata.run_id,
"signature": str(model.metadata.signature)}
Include the run ID in every response. When a downstream team questions a score, that single field lets you pull the exact parameters, data version, and validation report that produced the model â the entire point of the tracking discipline. The same discipline extends to batch scoring jobs: log the batch window, the input row count, and the model version as run tags so a monthly report can be reproduced months later without archaeology through shared drives. Teams that skip this usually rediscover why it matters the first time a stakeholder asks why a particular customer received a particular score on a particular day.
Common Mistakes
Logging metrics but not the dataset version or data slice definitions
Fix: Log dataset identifiers, row counts, and time ranges as params or tags; a metric without a data version is not reproducible.
Training locally and manually copying model files to a server
Fix: Log models through the API to the tracking server from the start; manual file copies lose metadata and drift from the registry.
Leaving hundreds of runs with no tags, then spending hours searching the UI
Fix: Tag every run with author, dataset, and stage; use nested runs for sweeps so the parent captures the headline result.
Promoting registry versions without archived predecessors
Fix: Always archive existing production versions on promotion (or use aliases like champion/challenger) to keep a single unambiguous live version.
Best Practices
- Log parameters, metrics, tags, and the model signature on every run â metadata costs seconds, reconstruction costs days
- Use nested runs for sweeps; log the best configuration to the parent for one-glance results
- Wrap preprocessing and postprocessing in a pyfunc model so the logged artifact is the full inference graph, not just the estimator
- Pin environments in pip_requirements or conda.yaml and review them like production dependencies
- Record the run ID in serving responses so every prediction is traceable to its exact training record
Interview Questions
Q1: What is the difference between MLflow Tracking and the Model Registry?
Tracking records individual runs â parameters, metrics, artifacts â organized by experiment. The Registry organizes those logged models by name and version with stages or aliases for lifecycle governance and promotion.
Q2: Why log a model signature and input example?
The signature validates serving-time inputs against the training schema and enables tooling like MLflow's scoring server and UI previews. The input example powers one-click test predictions and documents expected feature shapes.
Q3: How would you make training reproducible end to end with MLflow?
Log the data version or snapshot identifier, all hyperparameters, the code commit hash as a tag, the environment definition, and fixed seeds; then load the run's logged model and environment to recreate predictions exactly.
Key Takeaways
- MLflow Tracking gives every run an immutable record of parameters, metrics, artifacts, and environment â start logging on day one
- Nested runs keep sweeps organized; let Optuna or Ray Tune drive large searches with automatic MLflow logging
- pyfunc models ship preprocessing and postprocessing with the estimator, closing the training-serving skew gap
- Registry stages (or aliases) encode promotion governance; archive predecessors to keep one unambiguous production version
- Embed the run ID in serving responses â traceability is the payoff of the entire tracking discipline