Sub topic 10
Nested runs for hyperparameter search
This chapter assumes you can start a tracking server, create an experiment, and log parameters and metrics inside a with mlflow.start_run() block. It also assumes you know how to train a scikit-learn model and split data into train and test sets. If any of that is unfamiliar, review the chapters on experiments, runs and logging first.
Why a search needs structure
A hyperparameter search trains the same model many times with different settings. If every trial is a top-level run, the experiment list fills with dozens of near-identical rows. Nothing in the list says which runs belong to the same search. Two searches on the same day become hard to tell apart.
MLflow solves this with nested runs. A nested run is a child run that records a parent run's ID in a tag. The parent stands for the whole search. Each child stands for one trial. The UI groups children under the parent, and the API lets you query them as a set.
Creating parent and child runs
Pass nested=True to mlflow.start_run() while another run is active. MLflow then makes the new run a child of the active run.
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, test_size=0.2, random_state=42)
mlflow.set_experiment("iris-search")
with mlflow.start_run(run_name="c-sweep"):
for C in [0.01, 0.1, 1.0, 10.0]:
with mlflow.start_run(run_name=f"C={C}", nested=True):
model = LogisticRegression(C=C, max_iter=200).fit(X_train, y_train)
mlflow.log_param("C", C)
mlflow.log_metric("test_accuracy", model.score(X_test, y_test))Here is what happens when this script runs:
- The outer
start_runcreates the parent runc-sweepand makes it the active run. - Each inner
start_run(nested=True)creates a child and pushes it onto MLflow's run stack. The child is now the active run. log_paramandlog_metricwrite to the child, because the child is active.- When the inner
withblock exits, the child ends and the parent becomes active again. - When the outer block exits, the parent ends.
The script calls set_experiment but not set_tracking_uri. Without a URI, MLflow writes to a local ./mlruns directory, or to whatever MLFLOW_TRACKING_URI names. In a team setup, set the URI explicitly as in earlier chapters.
What MLflow stores for the link
The parent-child link is not a separate table. MLflow sets the system tag mlflow.parentRunId on each child, with the parent's run ID as its value. This has two consequences.
- You can find the children of any parent with an ordinary tag filter.
- The link is a plain tag, so a child can be moved or detached only by editing tags. Normally you never do this.
Nesting rules
- Without
nested=True, callingstart_runwhile a run is active raises an exception. MLflow protects you from accidentally leaving a run open. - Nesting can go deeper than two levels. A child can start its own children. Most searches need only two levels.
- Parent and children share one experiment. A child cannot live in a different experiment from its parent.
Logging at the right level
Decide what belongs to the parent and what belongs to each child. A clean split keeps the UI readable and the queries simple.
| Item | Log it on | Reason |
|---|---|---|
| Hyperparameter values for one trial | Child | Each trial has its own values |
| Metric for one trial | Child | You compare trials by this value |
| Search space definition (ranges, grid) | Parent | It describes the whole search |
| Dataset version and split seed | Parent | All trials share it |
| Best trial's metric and parameters | Parent | A summary you can read without opening children |
| Tag such as `stage` or `team` | Parent, and children if you filter by it | Child runs do not inherit tags |
The last row is a common surprise. Children do not inherit the parent's parameters or custom tags. If you filter on tags.team = 'vision' and tagged only the parent, the children will not match. Tag the runs you intend to search for.
Recording the best trial on the parent
A parent run with no metrics shows empty columns in the UI. A useful pattern is to track the best result while the loop runs, then log it on the parent after the loop finishes.
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, test_size=0.2, random_state=42)
search_space = [0.01, 0.1, 1.0, 10.0]
mlflow.set_experiment("iris-search")
with mlflow.start_run(run_name="c-sweep-with-summary") as parent:
mlflow.set_tag("stage", "search")
mlflow.log_param("search_space_C", search_space)
mlflow.log_param("split_seed", 42)
best_acc = -1.0
best_C = None
for C in search_space:
with mlflow.start_run(run_name=f"C={C}", nested=True):
model = LogisticRegression(C=C, max_iter=200).fit(X_train, y_train)
acc = model.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_metric("best_test_accuracy", best_acc)
mlflow.log_param("best_C", best_C)
print("parent run id:", parent.info.run_id)The as parent clause gives you the run object, so you can read parent.info.run_id and use it later in a query.
A note on log_param with a list: MLflow stores parameter values as strings, so the list is saved as the text [0.01, 0.1, 1.0, 10.0]. Parameter values have a length limit, so very large search spaces belong in an artifact instead. mlflow.log_dict(config, "search_space.json") works well for that.
Finding the children of a parent
Once a search finishes, you will want its trials as a table. Filter on the parent tag.
import mlflow
parent_id = "REPLACE_WITH_PARENT_RUN_ID"
children = mlflow.search_runs(
experiment_names=["iris-search"],
filter_string=f"tags.mlflow.parentRunId = '{parent_id}'",
order_by=["metrics.test_accuracy DESC"],
)
print(children[["run_id", "tags.mlflow.runName", "params.C", "metrics.test_accuracy"]])Replace the placeholder with the ID printed by the previous script. Because the tag name contains a dot, the filter works without quoting in this form: MLflow reads tags.mlflow.parentRunId as the tag key mlflow.parentRunId. If a key contained spaces or other special characters, you would wrap it in backticks.
search_runs returns every matching run, parents and children together, unless you filter. A query such as metrics.test_accuracy > 0.9 can return both. To keep only top-level runs, filter out runs that have a parent. Many teams do this by reading the tags.mlflow.parentRunId column from the returned DataFrame and keeping the rows where it is empty.
Reading nested runs in the UI
In the experiment table, parent runs show an expand arrow next to the name. Click it to reveal the children. Selecting several children and pressing Compare opens the parallel coordinates and scatter views from the previous chapter, which suit hyperparameter sweeps well: each line is a trial, and the metric axis shows which setting values lead to good scores.
If you do not see grouping, check two things. First, the UI must be set to group runs by hierarchy; older versions of the table show a flat list. Second, the children must carry a valid mlflow.parentRunId. A child created without nested=True has no such tag and appears as an independent top-level run.
Failure modes and edge cases
A crash leaves runs open
If the script raises an exception inside a with block, MLflow ends that run with status FAILED and re-raises the exception. The parent block also exits, so the parent ends as FAILED too. Children that finished before the crash stay FINISHED. This is useful: you can see exactly which trials completed.
If you call mlflow.start_run() without a with block and the process is killed, the run stays in RUNNING state forever. Use the context manager so that cleanup is automatic.
Parallel trials need explicit parent IDs
The active run stack in MLflow is stored per thread. When a search library runs trials in separate threads or processes, the worker does not see the parent as active. A call to start_run(nested=True) in a worker then fails or creates a run with no parent.
The fix is to pass the parent's ID directly with the parent_run_id argument of mlflow.start_run, or to set the tag yourself.
import mlflow
from concurrent.futures import ThreadPoolExecutor
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, test_size=0.2, random_state=42)
mlflow.set_experiment("iris-parallel")
def run_trial(C, parent_id):
with mlflow.start_run(run_name=f"C={C}", parent_run_id=parent_id):
model = LogisticRegression(C=C, max_iter=200).fit(X_train, y_train)
mlflow.log_param("C", C)
mlflow.log_metric("test_accuracy", model.score(X_test, y_test))
with mlflow.start_run(run_name="parallel-sweep") as parent:
parent_id = parent.info.run_id
with ThreadPoolExecutor(max_workers=2) as pool:
for C in [0.01, 0.1, 1.0, 10.0]:
pool.submit(run_trial, C, parent_id)The parent_run_id argument is available in recent MLflow releases. Check your installed version if the call raises an unexpected-argument error. In older releases, start the child run and then call mlflow.set_tag("mlflow.parentRunId", parent_id).
Be careful with threads: a thread that raises inside pool.submit does not stop the parent block. The error is held in the returned future until you read it. Collect the futures and call .result() on each if you want failures to surface.
Many children make a large parent
A search with thousands of trials creates thousands of runs. The experiment list still loads, but search_runs returns results in pages. Set max_results deliberately and sort on the metric so that the best trials arrive first.
Do not log the same metric name on both levels without a plan
If the parent logs test_accuracy as a summary and each child also logs test_accuracy, a query on metrics.test_accuracy matches both. Name the summary distinctly, as in best_test_accuracy, so that a filter returns only what you expect.
Search libraries and autologging
Autologging interacts with nesting. For scikit-learn, the tuning classes GridSearchCV and RandomizedSearchCV are supported by mlflow.sklearn.autolog(). When you call fit on one of them, MLflow logs a parent run for the search and child runs for the parameter combinations. You get the parent-child layout without writing the loop. The details of what each child records depend on the MLflow version and on the max_tuning_runs option, which caps how many children are logged. Check the autologging documentation for your version if the counts look off.
A manual loop as shown above gives you full control over names, tags and artifacts. Autologging is faster to set up. Choose the manual loop when you need custom summaries on the parent or when your search is not a scikit-learn tuner.
Decision criteria
- Use nested runs when one search produces more than a handful of trials and you want to group, compare and query them together.
- Use separate top-level runs when trials are unrelated experiments that happen to use the same model.
- Use a distinct experiment per project and nested runs per search inside it. Do not create one experiment per search.
- For parallel work, pass
parent_run_idrather than relying on the active run.
Summary of the working model
A nested run is an ordinary run with a mlflow.parentRunId tag. The parent describes the search and records the best result. Each child records one trial. In serial code, nested=True handles the link for you. In parallel code, pass the parent's ID yourself. Query children with a tag filter, and name summary metrics differently from per-trial metrics.
Exercise
You run a search where the parent run is tagged team = 'vision', and each child logs test_accuracy. You query tags.team = 'vision' and metrics.test_accuracy > 0.9 and get no rows, even though several trials scored above 0.9. What is the most likely cause, and how do you fix the query without changing the code that produced the runs?
Show answer
The children do not inherit the parent's tags, so they have no team tag, and the parent has no test_accuracy metric. No single run satisfies both conditions. Query the children through the parent relationship instead: first find the parent with tags.team = 'vision', read its run ID, then search with tags.mlflow.parentRunId = '<that ID>' and metrics.test_accuracy > 0.9. For future runs, also set the team tag on each child.
Exercise
A script uses a ThreadPoolExecutor and calls mlflow.start_run(nested=True) inside each worker function. The children appear in the experiment as top-level runs. Why, and what is the fix?
Show answer
MLflow tracks the active run per thread, so a worker thread does not see the parent started in the main thread, and the child gets no mlflow.parentRunId tag. Pass the parent's run ID to each worker and call mlflow.start_run(parent_run_id=parent_id). On older releases without that argument, start the run and set the mlflow.parentRunId tag with mlflow.set_tag.