skip to content

In MLflow, how do you log a nightly sweep's gradient-boosting trials as nested runs and then find the best trial from code?

level: middleimportance: must knowfreq 22%

answer

  1. one parent, many children
  2. nested=True inside the parent block
  3. tags.mlflow.parentRunId filter
  4. order_by on the ranking metric
  5. latest value, not best value

basics

~10 s

Open a parent with mlflow.start_run, open each trial inside it with mlflow.start_run(nested=True), then call mlflow.search_runs filtered on tags.mlflow.parentRunId and ordered by the validation metric. Search ranks each run by that metric's latest logged value.

solid answer

~40 s

The sweep runs inside `with mlflow.start_run(run_name="sweep-2026-10-05") as parent:` and each configuration inside `with mlflow.start_run(nested=True):`, where it logs its params and validation score. Without `nested=True`, the inner `start_run` raises because a run is already active. Each child gets the system tag `mlflow.parentRunId`, so `mlflow.search_runs(filter_string=f"tags.mlflow.parentRunId = '{parent.info.run_id}'", order_by=["metrics.val_rmse ASC"], max_results=1)` returns the winner as a one-row DataFrame. Two traps: search compares each run's **latest** value of a metric, not its best, so log the score you rank on as its own metric; and the active-run stack is per thread and reset in subprocesses, so parallel workers must pass `parent_run_id=parent.info.run_id` or they create top-level runs.

code

python · 19 lines
python
import mlflow

mlflow.set_experiment("store-demand")
configs = [{"max_depth": d, "learning_rate": lr} for d in (4, 6, 8) for lr in (0.03, 0.1)]

with mlflow.start_run(run_name="sweep-2026-10-05") as parent:
    for cfg in configs:
        with mlflow.start_run(nested=True):
            mlflow.log_params(cfg)
            val_rmse = train_and_validate(cfg)  # your training code
            mlflow.log_metric("val_rmse", val_rmse)

    best = mlflow.search_runs(
        filter_string=f"tags.mlflow.parentRunId = '{parent.info.run_id}'",
        order_by=["metrics.val_rmse ASC"],
        max_results=1,
    )
    mlflow.log_metric("best_val_rmse", best["metrics.val_rmse"].iloc[0])
    mlflow.set_tag("best_run_id", best["run_id"].iloc[0])

go deeper

for a junior

Recall the pattern: a parent run for the sweep, nested=True for each trial inside it, and a search filtered on the parent ID to list the trials.

for a middle

Explain the active-run stack, the mlflow.parentRunId tag, the search filter and order_by syntax, and why a metric's latest point is what gets ranked.

for a senior

Show the failure modes of a real sweep: orphaned trials from thread or process workers, rankings on a last value instead of a best one, and resuming a crashed trial by run ID.

for a principal

Weigh how a team structures sweeps so results stay queryable across nights and projects: naming, where the ranking metric is defined, and what is recorded back on the parent.

## The shape: one parent run, one child per trial A nightly sweep of a few dozen gradient-boosting configurations for a store-demand forecaster produces a few dozen MLflow **runs**. Logged flat, they mix with every other run in the experiment and nothing says which ones belong to tonight's sweep. MLflow's answer is **nested runs**: one **parent run** for the sweep, and one **child run** per configuration, linked by a system tag. How the search picks its next configuration is a separate question; this one is about recording the trials and reading them back. ## Opening the runs - The parent is an ordinary run: `with mlflow.start_run(run_name="sweep-2026-10-05") as parent:`. It can hold sweep-level params such as the search space's name. - Each trial opens with `mlflow.start_run(nested=True)` inside that block. MLflow keeps a **stack of active runs**; with `nested=True` the new run is pushed on top and tagged `mlflow.parentRunId` with the ID of the run below it. - Without `nested=True`, a second `start_run` while a run is active raises: "Run with UUID … is already active. To start a new run, first end the current run with mlflow.end_run(). To start a nested run, call start_run with nested=True". - `start_run(parent_run_id=...)` names the parent explicitly. In a thread that already has an active run, the call also needs `nested=True`, and the ID must match that run or MLflow raises. ### Parallel trials need the explicit parent The active-run stack is **thread-local**, and it is **reset in a subprocess**. A worker thread or a `multiprocessing` worker starts with an empty stack, so `start_run(nested=True)` there finds no parent: no error, no `mlflow.parentRunId` tag, just a top-level run in the active experiment. Pass `parent_run_id=parent.info.run_id` to each worker and open the child with it. A spawned process starts a fresh interpreter, so set the experiment there too; MLflow's own multiprocessing example also sets the tracking URI inside each worker. ## Finding the best trial with search_runs `mlflow.search_runs` returns a pandas DataFrame by default (or a list of `Run` objects with `output_format="list"`), with one column per param, metric and tag: `params.max_depth`, `metrics.val_rmse`, `tags.mlflow.runName`. - `filter_string="tags.mlflow.parentRunId = '<id>'"` keeps only tonight's children. - `order_by=["metrics.val_rmse ASC"]` sorts them. The direction is optional and **ascending is the default**; without `order_by` at all, results come newest first by `start_time`. - `max_results=1` returns only the winner. The default cap is 100,000 rows. - `experiment_ids` or `experiment_names` scopes the search; with neither, the active experiment is searched. - `run_view_type` defaults to active runs only, so trials deleted from the UI drop out of the ranking. - In the DataFrame, `params.*` columns hold strings, as stored; cast them before sorting or plotting them as numbers. - Metrics take numeric comparators (`metrics.val_rmse < 11.5`); params and tags are strings and take `=`, `!=`, `LIKE` and `ILIKE`. ## What the ranking actually compares | What a trial logged | What `metrics.val_rmse` holds in search | |---|---| | One `log_metric("val_rmse", v)` after training | That value | | `val_rmse` at steps 0–199, minimum at step 140 | The step-199 value, the **latest** point | | `val_rmse` per step plus `best_val_rmse` once | `metrics.best_val_rmse` holds the minimum | The stored summary for each metric key is its latest point — the highest step, then the most recent timestamp — and ordering uses that summary. A trial whose error rose after its best round is ranked on the worse number. Log the value you mean to compare as its own metric, or log the final evaluation once at the end. Some autologging integrations add their own entry for the best iteration when early stopping is on; check what your library's integration writes before relying on it. ## A checklist for a sweep that reads back cleanly 1. Set the tracking URI and `mlflow.set_experiment("store-demand")` before the parent opens. 2. Open the parent with a dated `run_name` and log sweep-level settings on it. 3. Open each trial with `nested=True`, or with `parent_run_id=` in workers. 4. Log each trial's params once and its ranking metric explicitly. 5. After the loop, query the children with the parent-ID filter and `order_by`. 6. Record the result on the parent — for example `best_val_rmse` and a `best_run_id` tag. Whether that best trial should be promoted, and what a comparison must hold to be fair, are questions for the promotion process; MLflow's part is making the comparison one query.

  • The sweep's trials run in a ThreadPoolExecutor and appear as top-level runs. Why, and what is the fix?
    MLflow's active-run stack is thread-local, so a worker thread starts with no active run and `start_run(nested=True)` has no parent to attach to — it silently creates a top-level run. Pass the parent's ID into each worker and open the child with `mlflow.start_run(parent_run_id=parent_id)`. The same applies to subprocesses, where the stack is reset as well.
  • How do you record the winning configuration on the parent run itself?
    After the loop, log a metric such as `best_val_rmse` on the parent and a tag such as `best_run_id`, or log the best params with `log_params` — as long as the parent has not already logged those keys with other values, since params are write-once per run. The children keep the full detail.
  • A trial's job crashed and is restarted. Can it continue the same MLflow run?
    Yes: `mlflow.start_run(run_id=...)`, or the `MLFLOW_RUN_ID` environment variable, resumes an existing run and sets its status back to running instead of creating a new one. New metric points append to the history, and params already logged cannot change value.

  • Calling start_run inside another run automatically makes the new run a child
  • search_runs ranks each trial by the best value it ever logged for a metric
  • Worker threads inherit the parent run, so nested=True is enough in a thread pool
  • order_by sorts descending by default, so the highest metric comes first
  • MLFLOW_RUN_ID tells a new run which parent to nest under