Sub topic 3
Experiments and runs
An experiment groups related attempts, and a run is one attempt. This chapter covers how MLflow models both, how a run moves through its lifecycle, and the errors you are most likely to hit.
This chapter assumes you have these prerequisites:
- Basic Python, including
withblocks. - A tracking server running at
http://127.0.0.1:5000, as started in the architecture chapter. - Enough scikit-learn to train and score a model.
The two core objects
MLflow Tracking stores everything under two levels.
- An experiment is a named container for runs that address the same problem. Examples are
iris-baselineandchurn-feature-ablation. Each experiment has a numeric ID, which the server assigns as a string such as"1", a unique name, an artifact location, and a lifecycle stage (activeordeleted). - A run is one execution of your training code. It belongs to exactly one experiment. It has a 32-character hexadecimal run ID, a status, start and end timestamps, and the data you log: parameters, metrics, tags and artifacts.
The relationship is one-to-many. One experiment holds many runs, and each run holds many parameters, metrics, tags and artifacts.
| Field | Where it lives | Meaning |
|---|---|---|
| `run_id` | `run.info` | Unique identifier, used to fetch or resume a run |
| `experiment_id` | `run.info` | The experiment that owns the run |
| `status` | `run.info` | `RUNNING`, `FINISHED`, `FAILED`, `KILLED` or `SCHEDULED` |
| `start_time`, `end_time` | `run.info` | Milliseconds since the Unix epoch |
| `artifact_uri` | `run.info` | Where this run's files are stored |
| `params`, `metrics`, `tags` | `run.data` | Everything you and MLflow logged |
The split between info and data shows up in code. Identity and lifecycle are in run.info. The logged values are in run.data.
Choosing and creating experiments
Every run needs an experiment. If you never choose one, MLflow uses the experiment named Default, which has ID 0. Use it only for throwaway tests, because it mixes unrelated work.
The usual way to choose an experiment is mlflow.set_experiment. It creates the experiment if the name does not exist yet, then makes it the target for later runs in this process.
import mlflow
mlflow.set_tracking_uri("http://127.0.0.1:5000")
experiment = mlflow.set_experiment("iris-baseline")
print(experiment.experiment_id, experiment.name, experiment.artifact_location)You can also set the experiment without code changes. Set MLFLOW_EXPERIMENT_NAME (or MLFLOW_TRACKING_URI for the server) in the environment. This is useful when the same script runs in several settings.
Creating an experiment explicitly
set_experiment gives you no say over tags or the artifact location. When you need either, create the experiment with MlflowClient first.
import mlflow
from mlflow import MlflowClient
mlflow.set_tracking_uri("http://127.0.0.1:5000")
client = MlflowClient()
name = "iris-ablation"
existing = client.get_experiment_by_name(name)
if existing is None:
experiment_id = client.create_experiment(
name,
tags={"team": "ml-platform", "project": "iris"},
)
else:
experiment_id = existing.experiment_id
experiment = client.get_experiment(experiment_id)
print(experiment.name, experiment.lifecycle_stage, experiment.tags)create_experiment raises an error if the name is taken, so the code above checks first. You can pass artifact_location to store this experiment's files somewhere other than the server default. The location is fixed at creation time. You cannot change it afterward, so decide before you create the experiment.
Deleting experiments
client.delete_experiment(experiment_id) is a soft delete. The experiment moves to the deleted lifecycle stage and disappears from the default UI view. Its runs and files stay on disk. client.restore_experiment(experiment_id) brings it back.
A deleted experiment still holds its name. If you call set_experiment or create_experiment with that name, MLflow raises an error instead of reusing it. Restore the experiment, or permanently remove deleted items on the server with mlflow gc.
The run lifecycle
A run starts when you call mlflow.start_run() and ends when you leave the with block or call mlflow.end_run(). The with form is the one to use, because it ends the run even when your code fails.
The next script starts a run, reads its identity while it is active, then reads the stored record after it ends.
import mlflow
from mlflow import MlflowClient
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-baseline")
client = MlflowClient()
with mlflow.start_run(run_name="inspect-me") as run:
mlflow.log_param("C", 1.0)
print("run id: ", run.info.run_id)
print("experiment id: ", run.info.experiment_id)
print("artifact uri: ", run.info.artifact_uri)
print("active run id: ", mlflow.active_run().info.run_id)
stored = client.get_run(run.info.run_id)
print("status:", stored.info.status)
print("duration ms:", stored.info.end_time - stored.info.start_time)
print("params:", stored.data.params)
print("run name tag:", stored.data.tags["mlflow.runName"])The script shows three points.
run.infoinside the block is a snapshot taken at start. Its status still readsRUNNINGif you print it. To see the final status, fetch the run again withclient.get_run.mlflow.active_run()returns the current run, orNoneoutside a run.- The run name is stored as the tag
mlflow.runName. Othermlflow.*tags, such asmlflow.userandmlflow.source.name, are set for you. When the script lives in a Git repository, MLflow also recordsmlflow.source.git.commit. These system tags give you who ran what, and from which code, without extra effort.
What happens on failure
If an exception leaves the with block, MLflow marks the run FAILED and re-raises the exception. The partial data stays. This is useful for debugging, since you can see the parameters and the last metrics from before the crash.
import mlflow
from mlflow import MlflowClient
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-baseline")
try:
with mlflow.start_run(run_name="will-fail") as run:
mlflow.log_param("C", 1.0)
mlflow.log_metric("train_loss", 0.9, step=0)
raise ValueError("bad input data")
except ValueError:
pass
stored = MlflowClient().get_run(run.info.run_id)
print(stored.info.status) # FAILED
print(stored.data.metrics) # {'train_loss': 0.9}A process that is killed from outside, for example by the operating system or a lost SSH session, never runs its cleanup code. That run stays in RUNNING forever. If you see old runs with that status, the process died without ending them. You can close one by hand with MlflowClient().set_terminated(run_id, status="KILLED").
To mark a run as killed from inside your code, call mlflow.end_run(status="KILLED").
Resuming a run
Pass an existing ID to start_run and MLflow reopens that run instead of creating a new one. This fits long jobs that checkpoint and restart, because the metrics from both attempts end up on one run.
import mlflow
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-baseline")
with mlflow.start_run(run_name="resumable") as first:
mlflow.log_metric("train_loss", 0.9, step=0)
run_id = first.info.run_id
with mlflow.start_run(run_id=run_id):
mlflow.log_metric("train_loss", 0.6, step=1)After the second block the run holds two points of train_loss, at steps 0 and 1. Its status goes back to RUNNING while resumed, then to FINISHED.
Parameters are write-once
Within one run, a parameter key can be written only once with a given value. Logging the same key with the same value again is harmless. Logging a different value raises an MlflowException.
import mlflow
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-baseline")
with mlflow.start_run():
mlflow.log_param("C", 1.0)
mlflow.log_param("C", 1.0) # same value: accepted
mlflow.log_param("C", 2.0) # different value: raises MlflowExceptionThis rule keeps a run an honest record of one configuration. If you want to try C=2.0, start a new run. If you hit this error in a loop, you probably forgot to open a fresh run per iteration. Metrics and tags are different. A metric can be logged many times, and set_tag overwrites an earlier value.
Common errors
These problems come up often when people first work with runs.
- A run is already active. Calling
start_runwhile another run is open raises an error such asRun with UUID ... is already active. Close the first run, or passnested=Trueto make the new run a child. Nested runs get their own chapter later. - Logging outside a run.
mlflow.log_paramwith no active run starts one for you and leaves it open. The run staysRUNNINGuntil the process exits. This is easy to cause by accident in notebooks, where a cell can start a run and a later cell fails before it ends. Always wrap logging inwith mlflow.start_run():. - Runs land in
Default. If you forgetset_experiment, the run goes to experiment0. You cannot move a run to another experiment afterward, so rerun it in the right place. - Wrong server. Without
set_tracking_uri, MLflow writes to a local./mlrunsfolder, not your server. If your runs are missing from the UI, check which URI the script used. SettingMLFLOW_TRACKING_URIin the environment avoids repeating it in every script. - Name clash with a deleted experiment. As described above, a soft-deleted experiment still owns its name.
- Changing a parameter value. See the previous section. Start a new run instead.
How to organize experiments
Grouping decisions pay off once you have hundreds of runs. A workable rule is to make one experiment per question you are trying to answer. Keep runs in the same experiment when you want to compare their metrics side by side. That means they should share the same evaluation data and the same metric definitions.
- Put runs that use different datasets or different metrics in separate experiments. Their numbers cannot be compared fairly.
- Do not create one experiment per run. You lose the comparison view, which works within an experiment.
- Do not put every project into
Default. Searching and cleaning up become hard.
A later chapter on team practices returns to naming conventions and tags. For now, remember that an experiment is the unit of comparison and a run is the unit of reproducibility.
Exercise
A training script crashes with an unhandled exception inside with mlflow.start_run():. What status does the run have afterward, and is the data logged before the crash kept?
Show answer
The status is FAILED. MLflow ends the run when the exception leaves the with block, then re-raises the exception. Parameters, metrics and tags logged before the crash are kept.
Exercise
Inside one run you call mlflow.log_param("max_depth", 3) and later mlflow.log_param("max_depth", 5). What happens, and what should you do to try both values?
Show answer
The second call raises an MlflowException, because a parameter key in a run can only be written once with one value. To try both values, start a separate run for each value, for example one with mlflow.start_run(): block per value.
Exercise
You run a script without calling mlflow.set_experiment, and the run appears in the UI under an experiment named Default. Can you move that run to iris-baseline? What do you do instead?
Show answer
No, MLflow has no operation that moves a run to another experiment. Call mlflow.set_experiment("iris-baseline") before start_run and run the script again.