Sub topic 10
Nested Runs for Hyperparameter Search
This chapter assumes you know Python context managers, scikit-learn model training, train/test splits, and MLflow experiments, runs, parameters, and metrics. You will organize a small hyperparameter search so that one parent run contains one child run for each trial.
Why use nested runs?
A hyperparameter is a model setting chosen before training, such as a logistic regression model's C value or a random forest's number of trees. A hyperparameter search trains several models with different settings and compares their results.
Without nested runs, every trial appears as an unrelated run in the MLflow UI. You can still compare metrics, but the relationship between the search and its trials is lost.
A nested run gives the search a parent run and gives each trial a child run:
The parent can record search-level information, such as the search method or dataset version. Each child records the settings and results for one model.
Create a parent run and child trials
Set nested=True when starting a child run inside an active parent run. MLflow then records the parent-child relationship.
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-search")
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
)
c_values = [0.01, 0.1, 1.0, 10.0]
with mlflow.start_run(run_name="c-sweep") as parent_run:
mlflow.set_tag("search_type", "manual_grid")
mlflow.log_param("trial_count", len(c_values))
for c_value in c_values:
with mlflow.start_run(
run_name=f"C={c_value}",
nested=True,
):
model = LogisticRegression(
C=c_value,
max_iter=200,
)
model.fit(X_train, y_train)
accuracy = model.score(X_test, y_test)
mlflow.log_param("C", c_value)
mlflow.log_metric("test_accuracy", accuracy)
print("Parent run:", parent_run.info.run_id)The outer start_run creates the parent. The inner start_run creates a child because nested=True is set. Each child has its own parameter and metric values.
The parent run does not automatically receive the children's metrics. If you want a summary on the parent, calculate it after the loop and log it there.
# Example summary inside the parent run
mlflow.log_param("selection_metric", "test_accuracy")For a real search, avoid choosing a model from the test set repeatedly. Use a validation split or cross-validation during selection, then evaluate the chosen model once on a final untouched test set.
Understand the run hierarchy
MLflow stores the parent relationship as metadata on the child run. The UI can use that relationship to display trials together. You can also identify the relationship when querying runs.
| Run type | Typical contents | Purpose |
|---|---|---|
| Parent run | Search method, dataset information, trial count | Describes one search |
| Child run | Hyperparameters, validation metrics, model artifact | Describes one trial |
| Selected child | Best trial's settings and results | Identifies the candidate to promote |
A common mistake is to start each trial without nested=True. In that case, MLflow may reject the new run because another run is active, or the trial may not be grouped as intended if the active-run behavior is changed elsewhere.
Another mistake is logging the same parameter name with different meanings. Keep parameter names consistent across all child runs, such as C, max_iter, and random_state. Consistent names make filtering and comparison reliable.
Find the best child run
After the search, query the child runs and sort them by the metric you care about.
import mlflow
runs = mlflow.search_runs(
experiment_names=["iris-search"],
filter_string="tags.mlflow.parentRunId IS NOT NULL",
order_by=["metrics.test_accuracy DESC"],
max_results=5,
)
columns = [
"run_id",
"tags.mlflow.parentRunId",
"params.C",
"metrics.test_accuracy",
]
print(runs[columns])The tags.mlflow.parentRunId tag identifies child runs. Sorting in descending order puts the highest accuracy first. In a production workflow, also filter by dataset version, code version, and the metric's evaluation split so that incomparable trials do not compete.
Exercise
What does nested=True do when starting a run inside an active parent run?
Show answer
It records the new run as a child of the active parent, allowing MLflow to group the hyperparameter trials under one search.