Sub topic 12
Conventions for shared, reproducible tracking
This chapter assumes you can log parameters, metrics, tags and artifacts inside a run. It also assumes you have used search_runs and know what the tracking server, backend store and artifact store do. Those tools work for one person without any rules. A team needs agreements about names, tags, what to record and where data lives. Without them, the tracking server fills with runs that nobody can find or reproduce.
What goes wrong without conventions
Teams that share a tracking server tend to hit the same problems:
- Experiments named
test,test2andfinal-final, so nobody knows which one holds the real results. - Runs that log
test_accuracyin one script andaccin another, so comparisons in the UI and insearch_runssilently miss runs. - Runs that record hyperparameters but not the data version or code version. The numbers can't be reproduced a month later.
- A local SQLite file on one laptop that nobody else can query.
The fixes are conventions, plus a small shared helper that applies them so people don't have to remember them.
Naming experiments and runs
An experiment groups runs that answer one question and can be compared fairly. Compare runs only when they use the same metric definition and the same evaluation data.
A workable pattern:
- Experiment names use
project/task, lowercase and hyphenated, for examplechurn/baseline-modelsoriris/hyperparameter-search. The slash is only a naming convention. MLflow treats the whole string as one name. - Run names describe what differs in this run, for example
logreg-c1orrf-depth8. MLflow also generates a unique run ID, so run names don't need to be unique. - Metric names are fixed per project. Pick
test_accuracy,val_lossand so on, and write them in the README. Prefix by dataset split (train_,val_,test_) so a metric never leaves the reader guessing which data it came from.
Experiment names are unique per tracking server. mlflow.set_experiment creates the experiment if it doesn't exist, so a typo creates a new experiment instead of raising an error. To avoid this, let one config file or environment variable supply the name. MLflow reads MLFLOW_EXPERIMENT_NAME if you don't call set_experiment.
Point everyone at one server
Hard-coding mlflow.set_tracking_uri("http://127.0.0.1:5000") in scripts means that the script behaves differently on each machine. Prefer an environment variable:
export MLFLOW_TRACKING_URI=http://mlflow.internal.example.com:5000
export MLFLOW_EXPERIMENT_NAME=iris/baseline-modelsWith these set, scripts need no tracking URI call at all. The same script then logs to a local server on a laptop, a shared server in CI, or a staging server, depending on the environment.
For a shared server, change the setup from the earlier local example in two ways:
- Use a database server such as PostgreSQL or MySQL as the backend store. SQLite handles one writer at a time and lives in a single file, so it is a poor fit once several people or jobs log concurrently.
- Put artifacts in shared object storage such as S3, Azure Blob Storage or Google Cloud Storage, not in a local directory.
mlflow server \
--backend-store-uri postgresql://mlflow:[email protected]:5432/mlflow \
--default-artifact-root s3://example-mlflow-artifacts/ \
--host 0.0.0.0 --port 5000Replace the password and hosts with your own, and read credentials from a secret store, not from a command line that ends up in shell history. The server needs access to the database. Clients that upload artifacts directly to S3 also need storage credentials. Alternatively, run the server with proxied artifact access (--serve-artifacts with --artifacts-destination) so clients upload through the server and don't need storage credentials.
The artifact location of an experiment is fixed when the experiment is created. Changing --default-artifact-root later affects only new experiments. If you need a special location for one project, set it explicitly when you create the experiment.
Record what is needed to reproduce a run
A run is reproducible if someone else can rebuild its inputs and rerun it. Parameters alone rarely suffice. Record these four things on every run:
| What | Where to record it | Why |
|---|---|---|
| Hyperparameters and seeds | `log_param` | The configuration of the model. |
| Code version | tag (git commit) | The same parameters on different code give different results. |
| Data version | tag or param (path, snapshot ID or content hash) | A changed dataset invalidates every comparison. |
| Environment | the logged model's requirements, or a logged lock file | Library versions change results. |
When you start a run from inside a git repository, MLflow records the commit on its own as the system tag mlflow.source.git.commit, along with mlflow.source.name and mlflow.user. This detection depends on running inside a git checkout with git available. A run launched from a notebook or a container without .git will lack it. Setting your own explicit tag protects against that, and it also lets you flag uncommitted changes.
Params and tags also behave differently, and you should plan for that:
- A param is write-once per run. Logging the same key again with a different value raises an
MlflowException. This is useful, because it prevents a run from reporting two contradictory configurations. - A tag can be overwritten with
set_tag. Use tags for facts that may need correction, such asstatusorreviewed_by. - A metric can be logged many times. Use
stepfor history.
A shared helper that applies the conventions
Put the conventions in one function that everyone imports. This version tags the git commit, flags a dirty working tree, hashes the training data, and logs all parameters in one call.
import hashlib
import subprocess
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
def git_state():
"""Return (commit, is_dirty), or ("unknown", "unknown") outside a git repo."""
try:
commit = subprocess.check_output(
["git", "rev-parse", "HEAD"], stderr=subprocess.DEVNULL, text=True
).strip()
dirty = subprocess.check_output(
["git", "status", "--porcelain"], stderr=subprocess.DEVNULL, text=True
).strip()
return commit, str(bool(dirty)).lower()
except (subprocess.CalledProcessError, FileNotFoundError):
return "unknown", "unknown"
def data_hash(array):
return hashlib.sha256(array.tobytes()).hexdigest()[:16]
def start_tracked_run(run_name, params, data, stage="experiment"):
commit, dirty = git_state()
tags = {
"stage": stage,
"git_commit": commit,
"git_dirty": dirty,
"data_hash": data_hash(data),
}
run = mlflow.start_run(run_name=run_name, tags=tags)
mlflow.log_params(params)
return run
if __name__ == "__main__":
mlflow.set_tracking_uri("sqlite:///mlflow.db")
mlflow.set_experiment("iris/baseline-models")
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
params = {"C": 1.0, "max_iter": 200, "split_seed": 42}
with start_tracked_run("logreg-c1", params, X_train, stage="baseline"):
model = LogisticRegression(C=params["C"], max_iter=params["max_iter"])
model.fit(X_train, y_train)
mlflow.log_metric("test_accuracy", model.score(X_test, y_test))This example uses a local SQLite store so it runs without a server. In a team setting, drop the set_tracking_uri call and rely on MLFLOW_TRACKING_URI. Two choices in the helper are worth noting:
- The hash covers only
X_train, so it identifies the training features and not the labels. A fuller version would hash both. For large datasets, hash a file or a snapshot ID, because hashing a multi-gigabyte array on every run is slow. - The helper returns the run object from
mlflow.start_run, which works as a context manager, so awithblock still ends the run and marks it finished or failed.
Use tags as a controlled vocabulary
Tags are free-form strings, so agree on a small set of keys and values. A tag the team spells three ways is three tags.
stage:baseline,experiment,candidate,production-retrain.owner: a team or person who is responsible for the run, in addition to the automaticmlflow.user.data_hashordata_version: which data the run used.ticket: an issue-tracker ID that explains why the run exists.
Then queries become reliable, using the same search_runs syntax as before:
import mlflow
mlflow.set_tracking_uri("sqlite:///mlflow.db")
runs = mlflow.search_runs(
experiment_names=["iris/baseline-models"],
filter_string="tags.stage = 'baseline' and tags.git_dirty = 'false'",
order_by=["metrics.test_accuracy DESC"],
)
print(runs[["run_id", "tags.git_commit", "tags.data_hash", "metrics.test_accuracy"]])Filtering on git_dirty = 'false' keeps results that you can trace to a committed state of the code. Two runs are comparable when their data_hash values match and their evaluation metric is the same.
Keep hyperparameter sweeps tidy
Use one parent run per sweep and one nested child per trial, as covered in the chapter on nested runs. Put the sweep-wide facts (data hash, git commit, search space) on the parent and the trial-specific facts (parameters, metrics) on the children. Keep the choice of the best trial explicit: log it as a metric or tag on the parent, so readers need not infer it from the UI.
Retention and cleanup
Deleting an experiment or a run in the UI is a soft delete. MLflow marks it deleted, and the data stays in the backend and artifact stores. The mlflow gc command removes deleted runs permanently. Agree on who may run it, because it is not reversible. A common policy is to delete scratch runs freely, keep every run behind a registered model version, and never garbage-collect runs that a registry version points to.
Registry conventions
Aliases such as champion work best when the team agrees on a short list of them and on who may move them. The model registry records which run produced each version, so the tags above (commit, data hash) are what let you trace a deployed model back to its code and data. Moving an alias is a deliberate action that needs a reviewer in many teams. Because the alias is just a pointer, moving it back is also the rollback.
Putting it together
Checklist for a new project
- Choose the experiment name and the fixed set of metric names, and write them in the project README.
- Set
MLFLOW_TRACKING_URIin each environment instead of hard-coding it. - Use a database backend and shared object storage once more than one person logs runs.
- Wrap run creation in a helper that records the git commit, a dirty flag, the data version and the seeds.
- Define the allowed tag keys and values for
stageandowner. - Decide who may delete runs, run
mlflow gc, and move registry aliases.
Exercise
Two runs in the same experiment both show test_accuracy 0.93, but the team lead says you can't call them equal. Name three things you would check on each run to decide whether the comparison is fair.
Show answer
Check that the datahash tags match (same training data), that the gitcommit tags show the same code or that the differences are known (and git_dirty is false), and that the metric was computed on the same evaluation split with the same definition, for example the same split seed. Matching library versions and random seeds are also valid answers.
Exercise
A script calls mlflow.logparam("C", 1.0) at the start of a run and, after a code change, mlflow.logparam("C", 10.0) later in the same run. What happens, and which call would you use instead if the value is a status that may change?
Show answer
The second logparam call raises an MlflowException, because a param can't be changed once logged in a run. For a value that may change, use mlflow.settag, since tags can be overwritten.
Exercise
Your team's experiments all log to a SQLite file on one person's laptop. Name two changes to make the setup suitable for sharing and say why each is needed.
Show answer
Move the backend store to a database server such as PostgreSQL, because SQLite is one file that handles concurrent writers poorly and isn't reachable by other machines. Move the artifact root to shared object storage such as S3, because artifacts in a local directory aren't accessible to teammates or CI jobs. Setting MLFLOWTRACKINGURI in each environment then points everyone at the same server.