Sub topic 10
Grouping tuning trials with nested runs
This chapter assumes you can create runs with mlflow.start_run, log parameters and metrics, and train a scikit-learn model on a train/test split. A hyperparameter search creates many runs. If each trial is a top-level run, the experiment list fills with rows that belong together but look unrelated. Nested runs fix this by putting the trials under one parent run.
The parent and child model
A nested run is a run whose mlflow.parentRunId tag points at another run. The parent represents the whole search. Each child represents one trial. In the experiment UI, the parent shows an expander arrow, and the children appear beneath it.
Creating nested runs
Open the parent with start_run. Inside it, open each child with nested=True.
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
with mlflow.start_run(run_name="sweep") as parent:
for c in [0.01, 0.1, 1.0, 10.0]:
with mlflow.start_run(run_name=f"C={c}", nested=True):
m = LogisticRegression(C=c, max_iter=200).fit(X_train, y_train)
mlflow.log_param("C", c)
mlflow.log_metric("test_accuracy", m.score(X_test, y_test))Each with block ends its run when the block exits. The child ends at the end of each loop pass, and the parent ends after the loop. Logging calls always go to the innermost active run. A log_metric call placed inside the parent block but outside the child block goes to the parent.
Logging to the parent
The parent is useful for facts about the whole search. Typical examples are the search space, the number of trials, and the best result. You can log these after the loop, while the parent is still active.
with mlflow.start_run(run_name="sweep-with-summary") as parent:
best_acc, best_c = 0.0, None
for c in [0.01, 0.1, 1.0, 10.0]:
with mlflow.start_run(run_name=f"C={c}", nested=True):
m = LogisticRegression(C=c, max_iter=200).fit(X_train, y_train)
acc = m.score(X_test, y_test)
mlflow.log_param("C", c)
mlflow.log_metric("test_accuracy", acc)
if acc > best_acc:
best_acc, best_c = acc, c
mlflow.log_param("n_trials", 4)
mlflow.log_param("best_C", best_c)
mlflow.log_metric("best_test_accuracy", best_acc)With these values on the parent, you can compare whole sweeps against each other without opening the children.
Querying children
search_runs returns child runs as ordinary rows. To get only the children of one sweep, filter on the parent tag.
children = mlflow.search_runs(
filter_string=f"tags.mlflow.parentRunId = '{parent.info.run_id}'",
order_by=["metrics.test_accuracy DESC"],
)
print(children[["run_id", "params.C", "metrics.test_accuracy"]])Parameters come back as strings in the DataFrame, so convert params.C with astype(float) before doing numeric work.
Common errors
- Forgetting
nested=True. Starting a second run while one is active raises an exception saying the run is already active. Addnested=Trueto the inner call. - Using
nested=Truewith no active parent. MLflow does not complain. The run is created as a normal top-level run. Check that your inner call really is inside thewithblock of the parent. - Logging a parameter twice with different values. Within one run, MLflow rejects a changed value for the same parameter key. Log trial values in the child, not in the parent.
- Reading metrics from the wrong run. When you register or load a model, use the child's run ID, not the parent's, if the model was logged inside the child.
Exercise
You run a sweep with a parent run and four child runs. In the parent block, after the loop, you call mlflow.logmetric("besttestaccuracy", 0.97). Which run receives the metric, and how would you list only the four children with searchruns?
Show answer
The parent run receives it, because the loop's child runs have already ended and the parent is the innermost active run. To list the children, call mlflow.searchruns with filterstring="tags.mlflow.parentRunId = '<parent run id>'", using parent.info.run_id for the ID.