Track parameters, metrics, data and code versions with MLflow 3 and a local SQLite store, compare runs from Python, log models with signatures, and serve them through registry aliases with pinned environments.
A result you cannot reproduce is an anecdote. Reproducing a model months later requires the exact data, code, parameters, environment and random seeds, plus the metrics to check that you got it right. This tutorial uses MLflow with a local SQLite store to record all of that, compare runs from Python, and promote a model through the registry with aliases, so that "the model in production" always points to a specific, traceable version.
The examples were run on Python 3.13.7 with MLflow 3.18.0, scikit-learn 1.9.1, pandas 3.1.2 and numpy 2.5.5; MLflow pulled in skops 0.16.0 for model serialization. The lock file examples use uv 0.13.13. MLflow's Python API changed noticeably in the 3.x series, so the code below targets 3.18 specifically. Everything runs locally: no server, no network access after installation.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "mlflow>=3.18,<4" "scikit-learn>=1.9,<2" "pandas>=3.1,<4"
The example trains regressors on scikit-learn's bundled diabetes dataset, which ships with the library and needs no download. Run the blocks in order in one session.
An experiment tracker is useful exactly to the extent that it answers "how was this model made?" without relying on anyone's memory. That means recording six kinds of information for every run:
| What | Why | How in MLflow |
|---|---|---|
| Parameters | Rebuild the same model | log_params, autologging |
| Metrics | Compare and select runs | log_metrics, autologging |
| Artifacts | Plots, reports, the model itself | log_dict, log_artifact, log_model |
| Data version | Same code on different data is a different experiment | log_input plus a content hash tag |
| Code version | Find the exact training code | git commit tag, set automatically or by hand |
| Environment | Same code on different library versions can differ | requirements.txt in the logged model, a lock file in the repository |
The common failure is tracking only parameters and metrics. Those tell you which run was best, but not how to recreate it.
MLflow separates the backend store (runs, parameters, metrics, tags, registry) from the artifact store (files). In MLflow 3.18 the default backend store is a SQLite database, mlflow.db in the working directory. The older file-based store in ./mlruns is in maintenance mode, and selecting it now raises an error:
MlflowException: The filesystem tracking backend (e.g., './mlruns') is in maintenance
mode and will not receive further updates. Please migrate to a database backend (e.g.,
'sqlite:///mlflow.db') to access the latest MLflow features. The `mlflow migrate-filestore`
tool migrates your existing data losslessly. ...
Setting MLFLOW_ALLOW_FILE_STORE=true opts out, but there is little reason to: features such as the model registry need a database anyway. Set the URI explicitly so the script does not depend on the working directory's defaults:
import hashlib
import os
import platform
import subprocess
import mlflow
import numpy as np
import pandas as pd
import sklearn
from mlflow import MlflowClient
from mlflow.models import infer_signature
from sklearn.datasets import load_diabetes
from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestRegressor
from sklearn.metrics import mean_absolute_error, root_mean_squared_error
from sklearn.model_selection import train_test_split
mlflow.set_tracking_uri("sqlite:///mlflow.db")
mlflow.set_experiment("myproject-diabetes")
SEED = 42
X, y = load_diabetes(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=SEED)
Artifacts still go to the file system, under ./mlruns/<experiment_id>/. To browse runs, start the UI against the same database. It binds to 127.0.0.1:5000 by default:
mlflow ui --backend-store-uri sqlite:///mlflow.db
Three helpers give every run a data hash, a code version and the runtime versions. The data fingerprint hashes the content of the frame including the index, so reordering or editing a single cell changes it. The git helper appends -dirty when the working tree has uncommitted changes, because a commit hash is only meaningful if the code actually matches the commit.
def data_fingerprint(df: pd.DataFrame) -> str:
hashed = pd.util.hash_pandas_object(df, index=True).to_numpy()
return hashlib.sha256(hashed.tobytes()).hexdigest()[:16]
def git_sha() -> str:
"""Commit hash, suffixed with -dirty if there are uncommitted changes."""
try:
sha = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True,
stderr=subprocess.DEVNULL).strip()
dirty = subprocess.check_output(["git", "status", "--porcelain"], text=True).strip()
return sha + ("-dirty" if dirty else "")
except (subprocess.CalledProcessError, FileNotFoundError):
return "unknown"
def run_tags() -> dict:
return {"git_sha": git_sha(),
"data_sha": data_fingerprint(pd.concat([X, y], axis=1)),
"python": platform.python_version(),
"sklearn": sklearn.__version__}
MLflow already sets the tag mlflow.source.git.commit (and mlflow.source.git.branch) automatically when a script runs inside a git repository. It does not record whether the tree was dirty, which is why the explicit tag is still useful. In this tutorial's scratch directory there is no repository, so the helper returns unknown.
A run is opened with a context manager; everything logged inside belongs to that run, and the run is marked finished or failed when the block exits.
with mlflow.start_run(run_name="rf-baseline") as run:
params = {"n_estimators": 200, "max_depth": 6, "random_state": SEED}
model = RandomForestRegressor(**params).fit(X_train, y_train)
pred = model.predict(X_test)
mlflow.log_params(params)
mlflow.log_metrics({"test_mae": mean_absolute_error(y_test, pred),
"test_rmse": root_mean_squared_error(y_test, pred)})
mlflow.set_tags(run_tags())
train_ds = mlflow.data.from_pandas(pd.concat([X_train, y_train], axis=1),
targets="target", name="diabetes-train")
mlflow.log_input(train_ds, context="training")
importances = dict(zip(X.columns, model.feature_importances_.round(4).tolist()))
mlflow.log_dict(importances, "feature_importances.json")
run_data = mlflow.get_run(run.info.run_id).data
print({k: round(v, 2) for k, v in run_data.metrics.items()})
print(sorted(k for k in run_data.tags if not k.startswith("mlflow.")))
print(run.info.artifact_uri)
{'test_mae': 42.81, 'test_rmse': 53.81}
['data_sha', 'git_sha', 'python', 'sklearn']
file:C:/.../mlruns/1/f4ec83016f654a7fbdb3c5ed8ce609cd/artifacts
log_input records the dataset as a first-class entity with a name, a digest and its schema, and links it to the run with a context such as training or evaluation. It does not upload the data. Store the data itself in versioned storage and log the path or version alongside the digest. log_dict writes a small JSON artifact without a temporary file.
Autologging patches fit so that parameters and training metrics are recorded without explicit calls. It is a good default for exploration and a safety net against forgotten parameters.
mlflow.sklearn.autolog(log_models=False)
with mlflow.start_run(run_name="hgb-autolog") as run:
HistGradientBoostingRegressor(max_iter=200, learning_rate=0.05,
random_state=SEED).fit(X_train, y_train)
auto = mlflow.get_run(run.info.run_id).data
print(len(auto.params), "params, e.g.", {k: auto.params[k] for k in ("learning_rate", "max_iter")})
print(sorted(auto.metrics))
mlflow.sklearn.autolog(disable=True)
21 params, e.g. {'learning_rate': '0.05', 'max_iter': '200'}
['training_mean_absolute_error', 'training_mean_squared_error', 'training_r2_score', 'training_root_mean_squared_error', 'training_score']
Autolog captured all 21 constructor parameters, including the defaults you did not set, which is exactly what you need when a library changes a default between versions. Note what it did not capture: the metrics are training metrics, which say little about generalisation. With log_post_training_metrics=True (the default), calling a sklearn.metrics function on the model's predictions inside the run also logs that score. Parameters come back as strings, so convert them before reuse. log_models=False keeps this run light; the final model is logged explicitly later, with a signature and input example.
A search with dozens of configurations clutters the run list. Nested runs group them under one parent, which holds the search-level information and the result.
grid = [{"max_iter": m, "learning_rate": lr, "max_leaf_nodes": leaves}
for m in (100, 300) for lr in (0.03, 0.1) for leaves in (7, 31)]
with mlflow.start_run(run_name="hgb-grid") as parent:
mlflow.log_param("grid_size", len(grid))
for cfg in grid:
with mlflow.start_run(run_name=f"hgb-{cfg['max_iter']}-{cfg['learning_rate']}-{cfg['max_leaf_nodes']}",
nested=True):
m = HistGradientBoostingRegressor(random_state=SEED, **cfg).fit(X_train, y_train)
mlflow.log_params(cfg)
mlflow.log_metric("test_rmse", root_mean_squared_error(y_test, m.predict(X_test)))
Each child gets the tag mlflow.parentRunId, which the UI uses to collapse the group and which you can filter on from code. For searches with scikit-learn's GridSearchCV, autologging creates the parent and child runs itself; max_tuning_runs limits how many children it logs (5 by default).
mlflow.search_runs returns a pandas DataFrame with one row per run and columns params.*, metrics.* and tags.*. The filter syntax is a small SQL-like language over those fields.
children = mlflow.search_runs(
experiment_names=["myproject-diabetes"],
filter_string=f"tags.mlflow.parentRunId = '{parent.info.run_id}'",
order_by=["metrics.test_rmse ASC"],
)
cols = ["params.max_iter", "params.learning_rate", "params.max_leaf_nodes", "metrics.test_rmse"]
print(children[cols].head(4).round(2).to_string(index=False))
best = children.iloc[0]
with mlflow.start_run(run_id=parent.info.run_id):
mlflow.log_metric("best_test_rmse", best["metrics.test_rmse"])
mlflow.set_tag("best_child", best["run_id"])
params.max_iter params.learning_rate params.max_leaf_nodes metrics.test_rmse
100 0.03 7 52.88
100 0.03 31 53.95
300 0.03 7 54.94
100 0.1 7 55.98
The smallest, most regularised configuration wins on this small dataset. Some filter details that save time:
params.max_iter = '100'. Metric comparisons are numeric: metrics.test_rmse < 55.tags.`mlflow.parentRunId` also works.AND; there is no OR, so run two searches and concatenate.output_format="list" to get Run objects instead of a DataFrame.Writing the best result back to the parent with start_run(run_id=...) means the parent run alone answers "what did this search find?".
A caveat on this example: the configurations are compared on the test set, and the same test set is then used to report the final model. In a real project, select on a validation split or cross-validation, and touch the test set once.
A logged model is more than a pickle. It bundles the serialized estimator, a signature describing the expected inputs and outputs, an input example, and the environment needed to load it. In MLflow 3, models are first-class LoggedModel entities with their own ID, and log_model takes a name.
best_cfg = {"max_iter": int(best["params.max_iter"]),
"learning_rate": float(best["params.learning_rate"]),
"max_leaf_nodes": int(best["params.max_leaf_nodes"])}
with mlflow.start_run(run_name="hgb-final") as run:
final = HistGradientBoostingRegressor(random_state=SEED, **best_cfg).fit(X_train, y_train)
mlflow.log_params(best_cfg)
mlflow.set_tags(run_tags())
mlflow.log_input(train_ds, context="training")
mlflow.log_metric("test_rmse", root_mean_squared_error(y_test, final.predict(X_test)))
signature = infer_signature(X_train, final.predict(X_train))
info = mlflow.sklearn.log_model(
final,
name="model",
signature=signature,
input_example=X_train.head(3),
registered_model_name="myproject-regressor",
skops_trusted_types=[
"sklearn.ensemble._hist_gradient_boosting.predictor.TreePredictor"],
)
print(info.model_uri, "version", info.registered_model_version)
print(signature)
models:/m-dcb59fd9a7b849d19c1f5dd77bf96935 version 1
inputs:
['age': double (required), 'sex': double (required), 'bmi': double (required), ...]
outputs:
[Tensor('float64', (-1,))]
params:
None
Two details are specific to recent versions. First, the model URI has the form models:/m-<id> and refers to the logged model directly, not to a path inside a run. Second, outside managed platforms mlflow.sklearn.log_model now serializes with skops instead of pickle. Skops refuses to load types it does not consider safe, and MLflow verifies that the saved model loads back. For HistGradientBoostingRegressor this fails with UntrustedTypesFoundException unless you name the internal TreePredictor type in skops_trusted_types, as above. Only trust types for models you produced yourself. You can still choose serialization_format="cloudpickle", but pickle-based formats execute code on load, so never load them from an untrusted store.
registered_model_name also creates a version in the model registry in the same call.
local = mlflow.artifacts.download_artifacts(info.model_uri)
print(sorted(os.listdir(local)))
print(open(os.path.join(local, "requirements.txt")).read())
['MLmodel', 'conda.yaml', 'input_example.json', 'model.skops', 'python_env.yaml', 'requirements.txt', 'serving_input_example.json']
mlflow==3.18.0
numpy==2.5.5
pandas==3.1.2
scikit-learn==1.9.1
scipy==1.18.1
skops==0.16.0
MLflow inferred the requirements from the libraries the model actually uses and pinned them to the installed versions. MLmodel describes the flavors and signature; python_env.yaml records the Python version. This is enough to rebuild a serving environment for the model, but it is not a lock of your whole training environment, which the section on pinning covers.
The registry gives models stable names and numbered versions. Older MLflow versions used fixed stages (Staging, Production); these are deprecated in favour of aliases, which are free-form, mutable pointers to a version. An alias such as champion is what serving code loads, so promotion and rollback are a single metadata change with no redeploy.
client = MlflowClient()
client.set_registered_model_alias("myproject-regressor", "champion", info.registered_model_version)
mv = client.get_model_version_by_alias("myproject-regressor", "champion")
print("champion ->", mv.version, mv.run_id == run.info.run_id)
champion = mlflow.pyfunc.load_model("models:/myproject-regressor@champion")
print(champion.predict(X_test.head(3)).round(1))
champion -> 1 True
[154.4 172. 147.3]
The URI models:/myproject-regressor@champion resolves the alias at load time. To promote a new candidate, register it as version 2, evaluate it, and move the alias with the same set_registered_model_alias call. To roll back, point the alias at version 1 again. Each version keeps its run_id, so from the serving alias you can walk back to the run, its parameters, data digest and git commit. Use separate aliases such as challenger for shadow or A/B evaluation, and delete_registered_model_alias to retire them.
The alias is only useful if you can trace it. The model version stores the ID of the run that produced it, and that run holds everything logged earlier:
source = client.get_run(mv.run_id)
print(source.info.run_name, source.data.params)
print({k: source.data.tags[k] for k in ("git_sha", "data_sha", "sklearn")})
print([(d.dataset.name, d.dataset.digest) for d in source.inputs.dataset_inputs])
hgb-final {'max_iter': '100', 'learning_rate': '0.03', 'max_leaf_nodes': '7'}
{'git_sha': 'unknown', 'data_sha': '27f9225ff65b00a1', 'sklearn': '1.9.1'}
[('diabetes-train', '4f06e4fb')]
Starting from the name serving code uses, you get the parameters, the code version, the full-data hash, the library version and the digest of the exact training split. Reproducing the model means checking out that commit, installing the locked environment, verifying both hashes against your data, and rerunning with the logged parameters. If any of these is missing, you find out now rather than during an incident. A useful habit is to make this lookup part of the promotion step: refuse to move champion to a version whose run lacks a clean git commit or a data digest.
Loading through mlflow.pyfunc gives a uniform predict interface that enforces the signature:
try:
champion.predict(X_test.head(3).drop(columns=["bmi"]))
except Exception as exc:
print(type(exc).__name__, "...", str(exc).split("Error: ")[-1])
MlflowException ... Model is missing inputs ['bmi'].
A missing column fails loudly instead of silently producing predictions from shifted features, which is the kind of bug that otherwise surfaces weeks later as a metric drop.
The model's requirements.txt covers inference. Training needs the full dependency tree pinned, committed next to the code, and its hash or the git commit recorded in the run. Two common approaches:
# uv project: pyproject.toml declares ranges, uv.lock pins every package
uv init --name myproject --python 3.13
uv add "mlflow>=3.18,<4" "scikit-learn>=1.9,<2"
uv sync --locked # install exactly what uv.lock says; fails if it is stale
# pip-style: compile a hashed lock from top-level requirements
uv pip compile requirements.in --python-version 3.13 --generate-hashes -o requirements.lock
pip install --require-hashes -r requirements.lock
In the test project, uv add resolved 93 packages into uv.lock. Keep loose ranges in pyproject.toml or requirements.in so upgrades are deliberate, and let the lock file carry the exact versions. Rebuild the lock on a schedule, run the training pipeline, and compare the metrics with the previous champion: if they move, you know whether the cause was code, data or dependencies. Hashes protect against a package being replaced on the index. For full isolation of system libraries, build a container image from the lock file and record the image digest as a tag.
Every source of randomness needs an explicit seed: the train/test split, the model, any sampling or augmentation. Passing random_state to each scikit-learn object is more reliable than relying on global state, but seeding the global generators catches libraries that use them.
import random
def seed_everything(seed: int) -> None:
random.seed(seed)
np.random.seed(seed) # legacy global RNG, still used by some libraries
# PYTHONHASHSEED only takes effect for new processes (workers, subprocesses)
os.environ["PYTHONHASHSEED"] = str(seed)
def train_once(seed):
seed_everything(seed)
m = RandomForestRegressor(n_estimators=100, random_state=seed, n_jobs=-1).fit(X_train, y_train)
return root_mean_squared_error(y_test, m.predict(X_test))
print([round(train_once(SEED), 6) for _ in range(2)], round(train_once(7), 6))
[54.864493, 54.864493] 54.020419
Two runs with seed 42 agree to six decimals, even with n_jobs=-1; a different seed moves RMSE by 0.84. That gap is a useful number in itself: differences between configurations smaller than the seed-to-seed variation are noise. For important comparisons, train with several seeds and log the mean and standard deviation.
Bitwise reproducibility has limits. Multithreaded reductions, GPU kernels and different BLAS builds can change floating-point summation order, so results may differ in the last digits across machines even with identical seeds and lock files. Record the platform in tags (as the manual run did with the Python and scikit-learn versions) and define reproducibility as "within tolerance" in your tests.
A local SQLite file is fine for one person. A team needs a shared tracking server, and that server holds models, dataset references and often credentials to the artifact store. The defaults are local-only for good reason; when you change them:
127.0.0.1 or an internal interface, with a reverse proxy that terminates TLS in front of it.MLFLOW_AUTH_ADMIN_PASSWORD (or admin_password in the config file named by MLFLOW_AUTH_CONFIG_PATH) before the first start, and set default_permission to NO_PERMISSIONS or READ deliberately. For single sign-on, put an authenticating proxy in front.--allowed-hosts and --cors-allowed-origins to your real host names, and never use --disable-security-middleware on a shared server.MLFLOW_TRACKING_USERNAME and MLFLOW_TRACKING_PASSWORD from a secrets manager, never in code or notebooks.export MLFLOW_AUTH_ADMIN_PASSWORD='...' # from a secrets manager
mlflow server --app-name basic-auth \
--host 127.0.0.1 --port 5000 \
--backend-store-uri postgresql://mlflow@db.internal.example.com/mlflow \
--artifacts-destination /srv/mlflow-artifacts \
--allowed-hosts mlflow.example.com
Treat loading a model from a shared registry like running code from it, because with pickle-based formats it is. Restrict who can register models, and prefer skops serialization where it works.
mlflow.search_runs in code, not by reading the UI.champion; promote and roll back by moving the alias.--locked or --require-hashes, and record the lock hash or image digest.search_runs, and move the alias only if it wins by more than the seed variance.Found a mistake in this tutorial? Let us know and we will fix it.