Sub topic 10
Grouping tuning trials with nested runs
This chapter assumes you can already create a run with mlflow.start_run, log parameters and metrics, and set an experiment. It also assumes you have a scikit-learn model and a train/test split. If any of that is unfamiliar, review the chapters on experiments and runs and on logging basics first.
The problem: a flat list of trials
A hyperparameter search trains the same model many times with different settings. If every trial is a top-level run, a 40-trial search adds 40 rows to the experiment table. These rows sit next to your baseline, your feature experiments, and last week's work. You then can't tell which runs belong to which search without reading run names.
A nested run fixes this. It is a run started while another run is active, and MLflow records the outer run as its parent. The parent stands for the whole search. The children stand for the individual trials. The experiment UI shows the children under the parent, so the table stays readable.
How nesting works
MLflow keeps a stack of active runs for the current thread. When you call mlflow.start_run(nested=True) while a run is active, MLflow does three things:
- It creates a new run in the same experiment.
- It sets the tag
mlflow.parentRunIdon the new run to the active run's ID. - It pushes the new run onto the stack, so
mlflow.log_paramand similar calls now go to the child.
When the child's with block exits, the child is ended and popped. Logging calls then go to the parent again.
Nesting is only a grouping. A child is a complete run with its own parameters, metrics, tags, artifacts, and models. It has its own ID and appears in mlflow.search_runs like any other run.
A complete tuning example
The next script runs a four-value search over the regularization strength C of a logistic regression. It splits off a validation set for choosing the best trial, so the test set is used only once, for the winner.
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
mlflow.set_experiment("/Users/<your-email>/iris-tracking")
X, y = load_iris(return_X_y=True)
X_rest, X_test, y_rest, y_test = train_test_split(X, y, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X_rest, y_rest, random_state=42)
search_space = [0.01, 0.1, 1.0, 10.0]
with mlflow.start_run(run_name="sweep") as parent:
mlflow.set_tag("stage", "tuning")
mlflow.log_param("search_space", str(search_space))
best_c, best_val = None, -1.0
for c in search_space:
with mlflow.start_run(run_name=f"C={c}", nested=True):
m = LogisticRegression(C=c, max_iter=200).fit(X_train, y_train)
val_acc = m.score(X_val, y_val)
mlflow.log_param("C", c)
mlflow.log_metric("val_accuracy", val_acc)
if val_acc > best_val:
best_c, best_val = c, val_acc
# Back in the parent: refit the winner and report on the test set.
best = LogisticRegression(C=best_c, max_iter=200).fit(X_rest, y_rest)
mlflow.log_param("best_C", best_c)
mlflow.log_metric("best_val_accuracy", best_val)
mlflow.log_metric("test_accuracy", best.score(X_test, y_test))
print("parent run id:", parent.info.run_id)Three points about this script matter in practice:
- The
nested=Trueargument is required for every child. The code logsbest_Cand the summary metrics after the loop. At that point the child blocks have exited, so the calls go to the parent. - The parent holds the summary and the children hold the detail. A reader who opens the parent sees the outcome. A reader who expands it sees how you got there.
- The parent's
Cparameter is deliberately absent. The parent has asearch_spaceand abest_Cinstead, so a column namedCin the table means a single trial's value.
Common errors
Forgetting nested=True
Starting a run while another is active, without nested=True, raises an exception. The message says that the run is already active and tells you to end it or start a nested run. The usual cause is an earlier cell that called mlflow.start_run() without a with block and never ended it. In a notebook, call mlflow.end_run() to clear the stale run, and prefer the with form so this cannot happen.
Logging to the wrong run
Logging calls go to the run on top of the stack. If you log a summary inside the loop body but outside the child's with block, it goes to the parent and overwrites the previous value each iteration. Metrics keep a history per step, but a parameter can be set only once. Logging best_C repeatedly with different values in the same run raises an error.
Autologging inside the loop
Autologging, such as mlflow.sklearn.autolog(), logs into the active run if one exists. Inside a nested block, each fit call logs its parameters and training metrics to that child. This is usually what you want. If you leave out the child with block, autologging attaches to the parent, or creates its own top-level run if none is active. The outcome is a pile of unrelated runs, or one parent holding the last trial's parameters. Always open the child explicitly.
Parallel trials
The active-run stack belongs to a thread. If you run trials in worker threads, or with a library that uses its own processes, the worker does not see the parent as active. In that case, pass the parent's ID yourself. Recent MLflow 2.x releases accept parent_run_id in mlflow.start_run. Check the version installed on your compute before relying on it. The sequence is: start the parent, read parent.info.run_id, hand that string to each worker, and have each worker start its child with that ID. If your MLflow version lacks this argument, set the tag mlflow.parentRunId yourself on a new run, or use a tuning library that has its own MLflow integration.
Finding the children later
In the Databricks experiment UI, a parent run shows an expand arrow in the runs table. Expanding it reveals the children. You can sort the children by a metric, select several, and use the compare view as you would with any runs.
Programmatically, the link is the mlflow.parentRunId tag. This lets you fetch all trials of a search with a filter:
import mlflow
children = mlflow.search_runs(
experiment_names=["/Users/<your-email>/iris-tracking"],
filter_string=f"tags.mlflow.parentRunId = '{parent.info.run_id}'",
order_by=["metrics.val_accuracy DESC"],
)
print(children[["run_id", "params.C", "metrics.val_accuracy"]])Note the types. search_runs returns parameters as strings, because MLflow stores parameter values as text. Here params.C holds "0.01", not the float 0.01. Convert with astype(float) before you compute on it.
To fetch only top-level runs, filter out the children:
top_level = mlflow.search_runs(
experiment_names=["/Users/<your-email>/iris-tracking"],
filter_string="tags.mlflow.parentRunId IS NULL",
)This is useful for dashboards or comparisons that should see one row per search, not one row per trial.
Design choices
- What goes on the parent. Log the search configuration (space, strategy, number of trials, random seed), the best parameters, and the final test metric. Don't copy every child's metric into the parent.
- Where the model goes. Log a model for every child only if you may want any of them later. For large searches this uses much artifact storage. A common choice is to log models only for the final refit, on the parent, and keep the children light.
- Naming. Put the varying value in the child's
run_name, as inC=0.1. It makes the table readable without adding columns. - Depth. Nesting can go more than one level, for example a parent for a project, a child per model family, and a grandchild per trial. Two levels are enough for most work. Deeper trees make the UI harder to scan.
- Selection data. Pick the winner using validation data and report on test data once, as the example does. If you pick by test accuracy, the reported number is optimistic.
Exercise
A teammate's tuning loop calls mlflow.start_run(run_name=f"C={c}") inside a for loop, all inside with mlflow.start_run(run_name="sweep"). It fails on the first trial. What is wrong, and what do you change so the search appears as one group in the UI?
Show answer
The inner call is missing nested=True. A run is already active (the parent), so MLflow refuses to start another top-level run. Change the inner call to mlflow.start_run(run_name=f"C={c}", nested=True) and keep it in a with block so each child ends when its trial finishes. MLflow then tags each child with mlflow.parentRunId and the UI shows the trials under the "sweep" run.
Exercise
Write a search_runs call that returns only the child runs of a parent whose ID is in the variable pid, best val_accuracy first. Why does params.C come back as a string?
Show answer
mlflow.search_runs(experiment_names=[name], filter_string=f"tags.mlflow.parentRunId = '{pid}'", order_by=["metrics.val_accuracy DESC"]). MLflow stores parameter values as strings, so params.C is text and needs astype(float) before numeric work.