Lesson 2 of 2 Automated ML and Hyperparameter Tuning

Hyperparameter Tuning with Sweep Jobs

This lesson explains how sweep jobs search a hyperparameter space, how sampling algorithms and early termination policies differ, and how objectives and limits are set.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the parts of a sweep job.
  • Compare grid, random and Bayesian sampling.
  • Compare Bandit, median stopping and truncation selection policies.
  • Explain why the primary metric must match the logged name.

What a sweep job is

Hyperparameters are settings chosen before training, such as the learning rate, the number of trees or the dropout rate, that the training algorithm does not learn. A sweep job finds good values by running a command job many times as trials, each with different hyperparameter values, and comparing a metric that the script logs.

A sweep job has five parts: the trial command job, the search space, the sampling algorithm, the objective, and limits, with an optional early termination policy. In the Python SDK, a command job whose inputs use search space expressions becomes a sweep through its sweep() method.

Search spaces

Each tuned input gets an expression that describes its possible values. Discrete expressions list or step through values; continuous expressions draw from a distribution.

ExpressionValuesTypical use
Choice(values=[16, 32, 64])One of a listBatch size, optimizer, number of layers
Uniform(min_value=0.0, max_value=0.5)Evenly distributedDropout rate
LogUniform(min_value=-6, max_value=-1)exp() of a uniform value, spread across orders of magnitudeLearning rate
Normal(mu=0, sigma=1)Normally distributedValues centred on a known good setting
QUniform(min_value=50, max_value=500, q=50)Uniform, rounded to steps of qNumber of estimators
from azure.ai.ml.sweep import Choice, LogUniform, BanditPolicy

job_for_sweep = train_job(
    learning_rate=LogUniform(min_value=-6, max_value=-1),
    n_estimators=Choice(values=[100, 200, 400]),
)
sweep_job = job_for_sweep.sweep(
    compute="cpu-cluster", sampling_algorithm="random",
    primary_metric="val_auc", goal="Maximize",
)
sweep_job.set_limits(max_total_trials=40, max_concurrent_trials=4, timeout=7200)
sweep_job.early_termination = BanditPolicy(slack_factor=0.1, evaluation_interval=1, delay_evaluation=5)

Sampling algorithms

The sampling algorithm decides which combinations are tried. The choice depends mainly on the size of the search space and the budget.

Grid
How it choosesEvery combination
Supported expressionsChoice only
Early terminationSupported
SuitsSmall, discrete spaces
Choose when You must try every combination
Random
How it choosesValues at random (optionally Sobol sequences)
Supported expressionsAll
Early terminationSupported
SuitsMost searches; a good default
Choose when A broad search with early termination
Bayesian
How it choosesBased on the results of earlier trials
Supported expressionsChoice, Uniform and QUniform
Early terminationNot supported
SuitsExpensive trials and a small budget
Choose when Each trial is costly and runs can be sequential

Bayesian sampling learns from completed trials, so it works best when trials run mostly one after another; with high concurrency, it has fewer results to learn from. Microsoft recommends a maximum number of trials of at least 20 times the number of tuned hyperparameters for Bayesian sampling.

Objective and limits

The objective is the primary_metric and the goal, Maximize or Minimize. The training script must log the metric with exactly that name, for example mlflow.log_metric("val_auc", auc); a mismatch leaves every trial without a score.

Limits bound the cost: max_total_trials and max_concurrent_trials (each from 1 to 1,000), timeout for the whole sweep and trial_timeout for each trial, in seconds. Concurrency should match the cluster's maximum nodes; a higher value only queues trials.

Early termination policies

An early termination policy cancels trials that are unlikely to beat the best one, which saves compute for promising trials. Policies are evaluated every evaluation_interval times the metric is logged, starting after delay_evaluation intervals so that trials are not judged too early.

  • Bandit policy: cancels a trial whose metric is worse than the best trial's by more than a slack_factor (a ratio) or slack_amount (an absolute value). It is the most aggressive and saves the most compute.
  • Median stopping policy: cancels a trial whose best metric is worse than the median of the running averages of all trials. It is a conservative choice.
  • Truncation selection policy: at each interval, cancels a given truncation_percentage (1 to 99) of the lowest-performing trials.

Log during training

Early termination can act only on metrics logged during training. A script that logs its metric once at the end gives the policy nothing to evaluate, so log the validation metric each epoch or iteration.

Worked example

Tuning on a budget

A team tunes four hyperparameters of a neural network, two of them continuous. Each trial takes about 25 minutes on one GPU node, the cluster has 8 nodes, and the budget allows about 80 trials. They want the best model they can find while wasting as little compute as possible on poor trials.

Use random sampling with continuous expressions such as LogUniform for the learning rate, max_total_trials=80 and max_concurrent_trials=8, and a Bandit policy with a delay of a few epochs. The training script must log the validation metric every epoch so the policy can cancel poor trials early, and the primary metric name must match it.

Grid sampling cannot use continuous expressions and would need discretized values. Bayesian sampling cannot use early termination and learns less with eight trials running at once. Running all trials to completion without a policy would spend the full 25 minutes on clearly poor trials.

Check yourself

A Bayesian sweep is configured with a Bandit early termination policy. What happens?

Show answer

Bayesian sampling does not support early termination policies, so the configuration is not valid. Use random sampling with Bandit to stop poor trials early, or Bayesian sampling without a policy.

Exam Tips

Remember for the exam

  • A sweep job runs trials of a command job over a search space.
  • Grid supports only Choice; Bayesian does not support early termination.
  • The primary metric must match the logged metric name exactly.
  • Bandit, median stopping and truncation selection cancel weak trials; log metrics during training.