Sub topic 2
Experiments and Runs: The Core Model
This chapter assumes you can write basic Python, including context managers, and that you have trained a scikit-learn model before. It also assumes you have a Databricks notebook attached to compute. Every other chapter in this tutorial builds on the model described here, so it is worth getting precise.
The two containers
MLflow Tracking organizes everything into two levels.
- A run is one execution of your training code. It holds the record of that execution: the settings you used, the numbers you measured, and the files you produced.
- An experiment is a named group of runs that belong to the same problem. All attempts to classify iris flowers, for example, go in one experiment.
An experiment does not train anything. It is a folder-like container that lets you list, compare, and search its runs together.
What a run stores
A run stores four kinds of information. Each has a different shape and purpose, and choosing the wrong one is a common source of messy experiments.
| Kind | What it holds | Example | Can it change? |
|---|---|---|---|
| Parameter | An input setting, stored as a string | `C = 1.0` | One value per key. Logging a different value for the same key raises an error. |
| Metric | A number measured during or after training | `accuracy = 0.93` | Can be logged many times, with a step number, to form a history. |
| Tag | A label for organizing and filtering | `stage = exploration` | Can be overwritten. |
| Artifact | A file or directory | A plot, a CSV, a serialized model | Written once per path. |
Parameters describe what you chose. Metrics describe what you got. Tags describe how you want to find the run later. Artifacts hold anything that does not fit in a single value.
Every run also gets a unique run ID, a 32-character hexadecimal string. The run ID is the stable handle you use to find a run, load its model, or register it later.
Creating a run
You create a run with mlflow.start_run(), almost always as a context manager. The with block guarantees the run is closed even if your code raises an exception.
import mlflow
mlflow.set_experiment("/Users/<your-email>/iris-tracking")
with mlflow.start_run(run_name="baseline") as run:
mlflow.log_param("C", 1.0)
mlflow.log_metric("accuracy", 0.93)
mlflow.set_tag("stage", "exploration")
print(run.info.run_id)Replace <your-email> with the email you use to sign in to the workspace. The code does the following:
set_experimentselects the experiment. If it does not exist, MLflow creates it.start_runopens a new run inside that experiment and gives it the display namebaseline.- The three logging calls attach a parameter, a metric, and a tag to the active run.
- On leaving the
withblock, the run is ended and its status becomesFINISHED.
run.info.run_id is the ID. Copy it from the output if you want to refer to this run later.
Run names are not identifiers
run_name is a human-readable label. Two runs can share the same name, and MLflow will not complain. Only the run ID is unique. If you need to find a run later by name, treat it as a search filter that may return several results.
The run lifecycle
A run moves through a small set of states.
When you use with mlflow.start_run(), the status is set for you. If an exception leaves the block, the run is marked FAILED, and everything logged before the failure is kept. That is useful: a crashed training job still shows its parameters and the metrics it reached.
The active run
MLflow keeps track of one active run per thread. The logging functions, such as mlflow.log_param, write to that active run. They do not take a run as an argument.
This design is convenient but leads to several edge cases.
- Logging with no active run. Calling
mlflow.log_paramoutside anywithblock does not fail on most setups. MLflow starts a run for you implicitly. That run stays open until you callmlflow.end_run()or the process ends, so later calls land in the same run. This surprises people in notebooks, where cells run at different times. - Starting a second run while one is active. Calling
mlflow.start_run()inside an active run raises an exception, unless you passnested=True. Nested runs are covered in a later chapter. - Leaked runs in notebooks. If a cell fails halfway through code that called
start_run()without awithblock, the run stays open. The nextstart_run()then fails with a message saying a run is already active. Callingmlflow.end_run()clears it. Usingwithavoids the problem.
You can check the current state at any time:
import mlflow
active = mlflow.active_run()
print(active.info.run_id if active else "no active run")Parameters are immutable per key
Within a single run, a parameter key can be set only once. Logging the same key with the same value again is allowed. Logging it with a different value raises an MlflowException.
import mlflow
with mlflow.start_run():
mlflow.log_param("C", 1.0)
mlflow.log_param("C", 1.0) # same value: accepted
try:
mlflow.log_param("C", 2.0) # different value: rejected
except mlflow.exceptions.MlflowException as err:
print("Rejected:", err.message[:60])This rule protects the meaning of a parameter. It records the setting the run was started with, so it should not drift. If a value truly changes during execution, it is a measurement. Log it as a metric instead.
Because parameters are stored as strings, 1.0 and "1.0" are the same value. Search filters on parameters therefore compare strings, a point that matters in the chapter on querying runs.
Metrics are time series
A metric is not a single value. Each call to mlflow.log_metric adds a data point with a step and a timestamp. If you log the same key repeatedly with increasing steps, MLflow stores the whole history, and the UI draws it as a line chart.
import mlflow
with mlflow.start_run(run_name="loss-curve"):
for step in range(5):
mlflow.log_metric("loss", 1.0 / (step + 1), step=step)When you later ask for "the metric" of a run, for example in a search filter or a comparison table, MLflow returns the latest value logged for that key. Keep this in mind when you log a metric every epoch. The latest value is the last epoch, not the best one. If you want the best value, log it under a separate key such as best_val_loss.
How the pieces map to a project
A reasonable way to use these concepts for a real project:
- Create one experiment per problem, such as one for churn prediction.
- Create one run per training attempt, whether a small tweak or a full retrain.
- Log every setting that influences the result as a parameter.
- Log every number you will want to compare as a metric.
- Use tags for facts about the attempt, such as the dataset version, the author, or the stage of work.
- Save files you will want later as artifacts.
Putting unrelated problems into one experiment makes comparisons meaningless, because their metrics are not on the same scale. Splitting one problem across many experiments makes comparison impossible, because the UI compares runs within an experiment.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Changing param values is not allowed` | The same parameter key was logged with a different value in one run | Use a new run, or log the changing value as a metric |
| `Run with UUID ... is already active` | An earlier run was never ended | Call `mlflow.end_run()`, and use `with` from now on |
| Metrics from several cells end up in one run | An implicit run was started and never closed | Wrap each attempt in its own `with mlflow.start_run()` |
| Runs appear in an unexpected experiment | `set_experiment` was not called, so the default experiment was used | Call `mlflow.set_experiment` before the first run |
| Comparison shows the last value, not the best | Metrics return their latest logged value | Log the best value under its own key |
Exercises
Exercise
A training loop logs mlflow.log_metric("val_loss", loss, step=epoch) for 20 epochs. Validation loss was lowest at epoch 12. When you filter runs with metrics.val_loss, which value does MLflow compare, and how do you make the best value searchable?
Show answer
MLflow compares the latest logged value, which is the one from epoch 20. To make the best value searchable, track the minimum in your code and log it once under a separate key, for example mlflow.log_metric("best_val_loss", best), after the loop.
Exercise
Inside one run, you call mlflow.log_param("max_iter", 100) and later mlflow.log_param("max_iter", 200). What happens, and what are two ways to fix the design?
Show answer
The second call raises an MlflowException, because a parameter key cannot change value within a run. One fix is to start a separate run for each value of max_iter. The other is to log the changing value as a metric if it is a measurement, such as the number of iterations actually used.