跳到正文

第 9 课 · Autologging and Comparison

Nested Runs and Hyperparameter Tuning

Group tuning trials with MLflow parent and child runs, track every trial of a search, mark the best one and enable system metrics logging when needed.

A hyperparameter search tries many settings. If every trial is a separate top-level run, your experiment becomes crowded. Nested runs group trials under one parent, so the search reads as one unit.

Parent and child runs

Start a parent run, then start children inside it with nested=True:

Python
import mlflow

with mlflow.start_run(run_name="depth-search") as parent:
    results = []
    for depth in [2, 4, 8, 16]:
        with mlflow.start_run(run_name=f"depth-{depth}", nested=True):
            mlflow.log_param("max_depth", depth)
            score = train_and_validate(depth)       # your function
            mlflow.log_metric("val_f1", score)
            results.append((score, depth))

    best_score, best_depth = max(results)
    mlflow.log_param("best_max_depth", best_depth)
    mlflow.log_metric("best_val_f1", best_score)

Child runs get a tag named mlflow.parentRunId that points to the parent. You can search for the children with it:

Python
mlflow.search_runs(
    filter_string=f"tags.mlflow.parentRunId = '{parent.info.run_id}'"
)

What to log where

Level Log
Parent Search space, data version, strategy, best result
Child Exact settings of the trial, its metrics, its seed

Put the search space on the parent. Without it, you cannot tell later what was not tried.

This stand-in runs a random search. The scoring function is invented, with a peak near depth 7 and learning rate 0.1.

Python Stand-in: a parent run with child trials

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The learning rate is sampled on a log scale. The step from 0.001 to 0.01 usually matters much more than the step from 0.501 to 0.51, so a log scale gives small rates a fair share of trials.

Tuning libraries and parallel trials

Tuning libraries such as Optuna can call your training function for each trial. Wrap each trial in a nested run and log its settings. If trials run in parallel processes or threads, the active run may not carry over to each worker. In that case, pass the parent run ID to the workers and set the parent explicitly, following the documentation for your MLflow version.

System metrics

Slow trials may be waiting on hardware. MLflow can log CPU, memory and GPU usage. It needs the psutil package, plus a GPU library such as nvidia-ml-py for NVIDIA cards. Enable it for one run, or globally:

Python
with mlflow.start_run(log_system_metrics=True):
    train()

mlflow.enable_system_metrics_logging()   # for later runs

You can also set MLFLOW_ENABLE_SYSTEM_METRICS_LOGGING=true.

Checkpoints

Long training jobs save checkpoints. In MLflow 3 you can log models at different steps, link metrics to a specific logged model, and search logged models to find a good checkpoint. Read the "Tracking Models" documentation before building this, because the details depend on your training library.

A search can overfit the validation set, especially with many trials and little data. The best of 500 trials often looks better than it really is. Confirm the winner on data that the search never saw.

Handle failing trials

In a long search, some trials will fail: a setting may use too much memory or produce invalid values. If one error stops the whole search, you lose time. Catch the error inside the child run, record it, and continue:

Python
with mlflow.start_run(nested=True):
    mlflow.log_param("max_depth", depth)
    try:
        score = train_and_validate(depth)
        mlflow.log_metric("val_f1", score)
    except ValueError as error:
        mlflow.set_tag("trial_error", str(error)[:200])

Only catch errors that you expect. A bare except can hide real bugs, such as a typo in your code, and make every trial "fail" quietly. If you catch an error, the run may end normally, so add a tag to mark it, and filter on that tag when you analyze. Be careful not to copy sensitive data into error messages.

Decide on a budget before you start: a number of trials, a time limit or a cost limit. A good plan is:

  1. Run a small random search across wide ranges.
  2. Look at which regions give good scores.
  3. Run a narrower second search there.
  4. Stop when more trials stop improving the best score in a meaningful way.

Random search is often more efficient than a full grid when only a few settings matter, because it tries more distinct values for each setting.

Read the results as a whole

Do not look only at the best trial. Plot the score against each setting. If the best values sit at the edge of your range, the range may be too small. If many different settings reach a similar score, the model is not very sensitive, and a simple choice is fine. If scores jump around wildly between near-identical settings, your validation estimate may be too noisy, and more data or cross-validation would help more than more trials.

Cross-validation

With cross-validation, each trial has several scores, one per fold. Log the mean and the spread as metrics, for example cv_f1_mean and cv_f1_std. You can also log each fold as a step. Always keep the same folds for all trials, so differences come from settings, not from luck in the split.

Choosing what to tune

Not every setting deserves a search. Start with the few that usually change results the most for your type of model, and leave the others at their defaults. Read the documentation of your training library to learn what each setting does. Searching ten settings at once spreads your trials thinly, and it makes the results harder to interpret. After the first round, you can add one more setting if there is a clear reason.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. How do you start a child run inside a parent run?

    The nested=True argument creates a child of the active run.
  2. 2. Which item belongs on the parent run?

    The parent describes the whole search and its outcome.
  3. 3. Why sample a learning rate on a log scale?

    Rates vary over orders of magnitude, so uniform sampling would rarely try tiny values.

Summary

  • Nested runs group tuning trials under one parent.
  • Record the search space on the parent and exact settings on children.
  • System metrics help explain slow runs.
  • Confirm a tuned winner on fresh data.

Next: The MLflow Model Format

你的学习进度保存在此浏览器中,无需账号。