Getting started with Advanced HPO Algorithms

This tutorial provides a complete example of how to use AutoGluon’s state-of-the-art hyperparameter optimization (HPO) algorithms to tune a basic Multi-Layer Perceptron (MLP) model, which is the most basic type of neural network.

Loading libraries

# Basic utils for folder manipulations etc
import time
import multiprocessing # to count the number of CPUs available

# External tools to load and process data
import numpy as np
import pandas as pd

# MXNet (NeuralNets)
import mxnet as mx
from mxnet import gluon, autograd
from mxnet.gluon import nn

# AutoGluon and HPO tools
import autogluon.core as ag
from autogluon.mxnet.utils import load_and_split_openml_data

Check the version of MxNet, you should be fine with version >= 1.5


You can also check the version of AutoGluon and the specific commit and check that it matches what you want.

import autogluon.core.version

Hyperparameter Optimization of a 2-layer MLP

Setting up the context

Here we declare a few “environment variables” setting the context for what we’re doing

OPENML_TASK_ID = 6                # describes the problem we will tackle
RATIO_TRAIN_VALID = 0.33          # split of the training data used for validation
RESOURCE_ATTR_NAME = 'epoch'      # how do we measure resources   (will become clearer further)
REWARD_ATTR_NAME = 'objective'    # how do we measure performance (will become clearer further)

NUM_CPUS = multiprocessing.cpu_count()

Preparing the data

We will use a multi-way classification task from OpenML. Data preparation includes:

  • Missing values are imputed, using the ‘mean’ strategy of sklearn.impute.SimpleImputer

  • Split training set into training and validation

  • Standardize inputs to mean 0, variance 1

X_train, X_valid, y_train, y_valid, n_classes = load_and_split_openml_data(
    OPENML_TASK_ID, RATIO_TRAIN_VALID, download_from_openml=False)
100%|██████████| 704/704 [00:00<00:00, 63578.80KB/s]
100%|██████████| 2521/2521 [00:00<00:00, 24483.57KB/s]
3KB [00:00, 3251.40KB/s]
8KB [00:00, 9412.18KB/s]
15KB [00:00, 16405.36KB/s]
2998KB [00:00, 44408.31KB/s]
881KB [00:00, 64005.78KB/s]
3KB [00:00, 2746.16KB/s]

The problem has 26 classes.

Declaring a model specifying a hyperparameter space with AutoGluon

Two layer MLP where we optimize over:

  • the number of units on the first layer

  • the number of units on the second layer

  • the dropout rate after each layer

  • the learning rate

  • the scaling

  • the @ag.args decorator allows us to specify the space we will optimize over, this matches the ConfigSpace syntax

The body of the function run_mlp_openml is pretty simple:

  • it reads the hyperparameters given via the decorator

  • it defines a 2 layer MLP with dropout

  • it declares a trainer with the ‘adam’ loss function and a provided learning rate

  • it trains the NN with a number of epochs (most of that is boilerplate code from mxnet)

  • the reporter at the end is used to keep track of training history in the hyperparameter optimization

Note: The number of epochs and the hyperparameter space are reduced to make for a shorter experiment

@ag.args(, upper=128),, upper=128),, upper=.75),, upper=.75),, upper=1, log=True),, upper=128),, upper=10, log=True),, upper=10, log=True),
def run_mlp_openml(args, reporter, **kwargs):
    # Time stamp for elapsed_time
    ts_start = time.time()
    # Unwrap hyperparameters
    n_units_1 = args.n_units_1
    n_units_2 = args.n_units_2
    dropout_1 = args.dropout_1
    dropout_2 = args.dropout_2
    scale_1 = args.scale_1
    scale_2 = args.scale_2
    batch_size = args.batch_size
    learning_rate = args.learning_rate

    ctx = mx.cpu()
    net = nn.Sequential()
    with net.name_scope():
        # Layer 1
        net.add(nn.Dense(n_units_1, activation='relu',
        # Dropout
        # Layer 2
        net.add(nn.Dense(n_units_2, activation='relu',
        # Dropout
        # Output

    trainer = gluon.Trainer(net.collect_params(), 'adam',
                            {'learning_rate': learning_rate})

    for epoch in range(args.epochs):
        ts_epoch = time.time()

        train_iter =
                        data={'data': X_train},
                        label={'label': y_train},
        valid_iter =
                        data={'data': X_valid},
                        label={'label': y_valid},

        metric = mx.metric.Accuracy()
        loss = gluon.loss.SoftmaxCrossEntropyLoss()

        for batch in train_iter:
            data =[0].as_in_context(ctx)
            label = batch.label[0].as_in_context(ctx)
            with autograd.record():
                output = net(data)
                L = loss(output, label)
            metric.update([label], [output])

        name, train_acc = metric.get()

        metric = mx.metric.Accuracy()
        for batch in valid_iter:
            data =[0].as_in_context(ctx)
            label = batch.label[0].as_in_context(ctx)
            output = net(data)
            metric.update([label], [output])

        name, val_acc = metric.get()

        print('Epoch %d ; Time: %f ; Training: %s=%f ; Validation: %s=%f' % (
            epoch + 1, time.time() - ts_start, name, train_acc, name, val_acc))

        ts_now = time.time()
        eval_time = ts_now - ts_epoch
        elapsed_time = ts_now - ts_start

        # The resource reported back (as 'epoch') is the number of epochs
        # done, starting at 1
            epoch=epoch + 1,

Note: The annotation epochs=9 specifies the maximum number of epochs for training. It becomes available as args.epochs. Importantly, it is also processed by HyperbandScheduler below in order to set its max_t attribute.

Recommendation: Whenever writing training code to be passed as train_fn to a scheduler, if this training code reports a resource (or time) attribute, the corresponding maximum resource value should be included in train_fn.args:

  • If the resource attribute (time_attr of scheduler) in train_fn is epoch, make sure to include epochs=XYZ in the annotation. This allows the scheduler to read max_t from train_fn.args.epochs. This case corresponds to our example here.

  • If the resource attribute is something else than epoch, you can also include the annotation max_t=XYZ, which allows the scheduler to read max_t from train_fn.args.max_t.

Annotating the training function by the correct value for max_t simplifies scheduler creation (since max_t does not have to be passed), and avoids inconsistencies between train_fn and the scheduler.

Running the Hyperparameter Optimization

You can use the following schedulers:

  • FIFO (fifo)

  • Hyperband (either the stopping (hbs) or promotion (hbp) variant)

And the following searchers:

  • Random search (random)

  • Gaussian process based Bayesian optimization (bayesopt)

  • SkOpt Bayesian optimization (skopt; only with FIFO scheduler)

Note that the method known as (asynchronous) Hyperband is using random search. Combining Hyperband scheduling with the bayesopt searcher uses a novel method called asynchronous BOHB.

Pick the combination you’re interested in (doing the full experiment takes around 120 seconds, see the time_out parameter), running everything with multiple runs can take a fair bit of time. In real life, you will want to choose a larger time_out in order to obtain good performance.

SEARCHER = "bayesopt"
def compute_error(df):
    return 1.0 - df["objective"]

def compute_runtime(df, start_timestamp):
        return df["time_step"] - start_timestamp

def process_training_history(task_dicts, start_timestamp,
    task_dfs = []
    for task_id in task_dicts:
        task_df = pd.DataFrame(task_dicts[task_id])
        task_df = task_df.assign(task_id=task_id,
                                 runtime=runtime_fn(task_df, start_timestamp),

    result = pd.concat(task_dfs, axis="index", ignore_index=True, sort=True)
    # re-order by runtime
    result = result.sort_values(by="runtime")
    # calculate incumbent best -- the cumulative minimum of the error.
    result = result.assign(best=result["error"].cummin())
    return result

resources = dict(num_cpus=NUM_CPUS, num_gpus=0)
search_options = {
    'num_init_random': 2,
    'debug_log': True}
if SCHEDULER == 'fifo':
    myscheduler = ag.scheduler.FIFOScheduler(

    # This setup uses rung levels at 1, 3, 9 epochs. We just use a single
    # bracket, so this is in fact successive halving (Hyperband would use
    # more than 1 bracket).
    # Also note that since we do not use the max_t argument of
    # HyperbandScheduler, this value is obtained from train_fn.args.epochs.
    sch_type = 'stopping' if SCHEDULER == 'hbs' else 'promotion'
    myscheduler = ag.scheduler.HyperbandScheduler(

# run tasks

results_df = process_training_history(
The meaning of 'time_out' has changed. Previously, jobs started before
'time_out' were allowed to continue until stopped by other means. Now,
we stop jobs once 'time_out' is passed (at the next metric reporting).
If you like to keep the old behaviour, use
/var/lib/jenkins/workspace/workspace/autogluon-tutorial-course-v3/venv/lib/python3.7/site-packages/distributed/ UserWarning: Large object of size 1.24 MiB detected in task graph:
  (0, <function run_mlp_openml at 0x7f10884c0170>, { ... sReporter}, [])
Consider scattering large objects ahead of time
with client.scatter to reduce scheduler burden and
keep data on workers

    future = client.submit(func, big_data)    # bad

    big_future = client.scatter(big_data)     # good
    future = client.submit(func, big_future)  # good
  % (format_bytes(len(b)), s)
Epoch 1 ; Time: 0.659745 ; Training: accuracy=0.260079 ; Validation: accuracy=0.531250
Epoch 2 ; Time: 1.082026 ; Training: accuracy=0.496365 ; Validation: accuracy=0.655247
Epoch 3 ; Time: 1.594198 ; Training: accuracy=0.559650 ; Validation: accuracy=0.694686
Epoch 4 ; Time: 2.025090 ; Training: accuracy=0.588896 ; Validation: accuracy=0.711063
Epoch 5 ; Time: 2.444036 ; Training: accuracy=0.609385 ; Validation: accuracy=0.726939
Epoch 6 ; Time: 2.868432 ; Training: accuracy=0.628139 ; Validation: accuracy=0.745321
Epoch 7 ; Time: 3.290338 ; Training: accuracy=0.641193 ; Validation: accuracy=0.750501
Epoch 8 ; Time: 3.715794 ; Training: accuracy=0.653751 ; Validation: accuracy=0.763202
Epoch 9 ; Time: 4.148949 ; Training: accuracy=0.665482 ; Validation: accuracy=0.766043
Epoch 1 ; Time: 0.413161 ; Training: accuracy=0.050338 ; Validation: accuracy=0.064141
Epoch 1 ; Time: 1.208505 ; Training: accuracy=0.533416 ; Validation: accuracy=0.680168
Epoch 2 ; Time: 2.361844 ; Training: accuracy=0.644555 ; Validation: accuracy=0.730252
Epoch 3 ; Time: 3.518911 ; Training: accuracy=0.667412 ; Validation: accuracy=0.736471
Epoch 4 ; Time: 4.655218 ; Training: accuracy=0.681325 ; Validation: accuracy=0.745378
Epoch 5 ; Time: 5.793087 ; Training: accuracy=0.671056 ; Validation: accuracy=0.728908
Epoch 6 ; Time: 6.932834 ; Training: accuracy=0.684803 ; Validation: accuracy=0.747563
Epoch 7 ; Time: 8.065494 ; Training: accuracy=0.687371 ; Validation: accuracy=0.757815
Epoch 8 ; Time: 9.209537 ; Training: accuracy=0.687453 ; Validation: accuracy=0.746555
Epoch 9 ; Time: 10.368382 ; Training: accuracy=0.686957 ; Validation: accuracy=0.723866
Epoch 1 ; Time: 0.350170 ; Training: accuracy=0.037506 ; Validation: accuracy=0.039899
Epoch 1 ; Time: 2.976478 ; Training: accuracy=0.062023 ; Validation: accuracy=0.115488
Epoch 1 ; Time: 0.345574 ; Training: accuracy=0.261678 ; Validation: accuracy=0.559674
Epoch 2 ; Time: 0.576678 ; Training: accuracy=0.448109 ; Validation: accuracy=0.659076
Epoch 3 ; Time: 0.803481 ; Training: accuracy=0.495724 ; Validation: accuracy=0.677194
Epoch 1 ; Time: 3.828359 ; Training: accuracy=0.037135 ; Validation: accuracy=0.037180
Epoch 1 ; Time: 0.491019 ; Training: accuracy=0.039576 ; Validation: accuracy=0.040067
Epoch 1 ; Time: 0.824341 ; Training: accuracy=0.051365 ; Validation: accuracy=0.139769
Epoch 1 ; Time: 0.301557 ; Training: accuracy=0.316033 ; Validation: accuracy=0.531570
Epoch 2 ; Time: 0.549056 ; Training: accuracy=0.381157 ; Validation: accuracy=0.584463
Epoch 3 ; Time: 0.792750 ; Training: accuracy=0.391157 ; Validation: accuracy=0.579504
Epoch 1 ; Time: 0.355904 ; Training: accuracy=0.347103 ; Validation: accuracy=0.632653
Epoch 2 ; Time: 0.658411 ; Training: accuracy=0.471034 ; Validation: accuracy=0.683004
Epoch 3 ; Time: 1.049740 ; Training: accuracy=0.491442 ; Validation: accuracy=0.673469
Epoch 1 ; Time: 0.334972 ; Training: accuracy=0.231908 ; Validation: accuracy=0.523627
Epoch 1 ; Time: 0.335238 ; Training: accuracy=0.434700 ; Validation: accuracy=0.643442
Epoch 2 ; Time: 0.618277 ; Training: accuracy=0.562816 ; Validation: accuracy=0.720635
Epoch 3 ; Time: 0.894867 ; Training: accuracy=0.603892 ; Validation: accuracy=0.725647
Epoch 4 ; Time: 1.170868 ; Training: accuracy=0.619959 ; Validation: accuracy=0.731830
Epoch 5 ; Time: 1.452020 ; Training: accuracy=0.623023 ; Validation: accuracy=0.716959
Epoch 6 ; Time: 1.757405 ; Training: accuracy=0.623602 ; Validation: accuracy=0.739181
Epoch 7 ; Time: 2.034144 ; Training: accuracy=0.627412 ; Validation: accuracy=0.736842
Epoch 8 ; Time: 2.333258 ; Training: accuracy=0.640580 ; Validation: accuracy=0.743024
Epoch 9 ; Time: 2.618080 ; Training: accuracy=0.635114 ; Validation: accuracy=0.741019
Epoch 1 ; Time: 0.318830 ; Training: accuracy=0.336052 ; Validation: accuracy=0.586050
Epoch 2 ; Time: 0.568264 ; Training: accuracy=0.435327 ; Validation: accuracy=0.621681
Epoch 3 ; Time: 0.819461 ; Training: accuracy=0.477179 ; Validation: accuracy=0.665882
Epoch 1 ; Time: 3.715787 ; Training: accuracy=0.426973 ; Validation: accuracy=0.671938
Epoch 2 ; Time: 7.284246 ; Training: accuracy=0.517490 ; Validation: accuracy=0.716184
Epoch 3 ; Time: 10.943729 ; Training: accuracy=0.545756 ; Validation: accuracy=0.720727
Epoch 4 ; Time: 14.542693 ; Training: accuracy=0.553879 ; Validation: accuracy=0.714334
Epoch 5 ; Time: 18.143092 ; Training: accuracy=0.559019 ; Validation: accuracy=0.721063
Epoch 6 ; Time: 21.759300 ; Training: accuracy=0.563412 ; Validation: accuracy=0.735700
Epoch 7 ; Time: 25.326221 ; Training: accuracy=0.572779 ; Validation: accuracy=0.738728
Epoch 8 ; Time: 28.919801 ; Training: accuracy=0.577918 ; Validation: accuracy=0.725774
Epoch 9 ; Time: 32.594293 ; Training: accuracy=0.584881 ; Validation: accuracy=0.718035
Epoch 1 ; Time: 3.503960 ; Training: accuracy=0.553879 ; Validation: accuracy=0.735532
Epoch 2 ; Time: 7.137950 ; Training: accuracy=0.730686 ; Validation: accuracy=0.783984
Epoch 3 ; Time: 10.648081 ; Training: accuracy=0.782493 ; Validation: accuracy=0.826211
Epoch 4 ; Time: 14.128411 ; Training: accuracy=0.815318 ; Validation: accuracy=0.836306
Epoch 5 ; Time: 17.626489 ; Training: accuracy=0.833140 ; Validation: accuracy=0.869448
Epoch 6 ; Time: 21.190138 ; Training: accuracy=0.839523 ; Validation: accuracy=0.882234
Epoch 7 ; Time: 24.711153 ; Training: accuracy=0.856515 ; Validation: accuracy=0.895525
Epoch 8 ; Time: 28.183480 ; Training: accuracy=0.864473 ; Validation: accuracy=0.894179
Epoch 9 ; Time: 31.766320 ; Training: accuracy=0.866877 ; Validation: accuracy=0.904441
Epoch 1 ; Time: 0.381098 ; Training: accuracy=0.255639 ; Validation: accuracy=0.602731
Epoch 2 ; Time: 0.709107 ; Training: accuracy=0.359002 ; Validation: accuracy=0.643190
Epoch 3 ; Time: 1.031474 ; Training: accuracy=0.390977 ; Validation: accuracy=0.664169
Epoch 1 ; Time: 1.212482 ; Training: accuracy=0.417805 ; Validation: accuracy=0.651765
Epoch 2 ; Time: 2.463755 ; Training: accuracy=0.625342 ; Validation: accuracy=0.722353

Analysing the results

The training history is stored in the results_df, the main fields are the runtime and 'best' (the objective).

Note: You will get slightly different curves for different pairs of scheduler/searcher, the time_out here is a bit too short to really see the difference in a significant way (it would be better to set it to >1000s). Generally speaking though, hyperband stopping / promotion + model will tend to significantly outperform other combinations given enough time.

bracket elapsed_time epoch error eval_time objective runtime target_epoch task_id terminated time_step best
0 0 0.662234 1 0.468750 0.657310 0.531250 1.482529 9 0 NaN 1.631931e+09 0.468750
1 0 1.083791 2 0.344753 0.417407 0.655247 1.904086 9 0 NaN 1.631931e+09 0.344753
2 0 1.595934 3 0.305314 0.509834 0.694686 2.416229 9 0 NaN 1.631931e+09 0.305314
3 0 2.026804 4 0.288937 0.428488 0.711063 2.847099 9 0 NaN 1.631931e+09 0.288937
4 0 2.445597 5 0.273061 0.417022 0.726939 3.265892 9 0 NaN 1.631931e+09 0.273061
import matplotlib.pyplot as plt

plt.figure(figsize=(12, 8))

runtime = results_df['runtime'].values
objective = results_df['best'].values

plt.plot(runtime, objective, lw=2)
plt.xlim(0, 120)
plt.ylim(0, 0.5)
plt.xlabel("Runtime [s]", fontsize=14)
plt.ylabel("Objective", fontsize=14)
Text(0, 0.5, 'Objective')

Diving Deeper

Now, you are ready to try HPO on your own machine learning models (if you use PyTorch, have a look at Tune PyTorch Model on MNIST). While AutoGluon comes with well-chosen defaults, it can pay off to tune it to your specific needs. Here are some tips which may come useful.

Logging the Search Progress

First, it is a good idea in general to switch on debug_log, which outputs useful information about the search progress. This is already done in the example above.

The outputs show which configurations are chosen, stopped, or promoted. For BO and BOHB, a range of information is displayed for every get_config decision. This log output is very useful in order to figure out what is going on during the search.

Configuring HyperbandScheduler

The most important knobs to turn with HyperbandScheduler are max_t, grace_period, reduction_factor, brackets, and type. The first three determine the rung levels at which stopping or promotion decisions are being made.

  • The maximum resource level max_t (usually, resource equates to epochs, so max_t is the maximum number of training epochs) is typically hardcoded in train_fn passed to the scheduler (this is run_mlp_openml in the example above). As already noted above, the value is best fixed in the ag.args decorator as epochs=XYZ, it can then be accessed as args.epochs in the train_fn code. If this is done, you do not have to pass max_t when creating the scheduler.

  • grace_period and reduction_factor determine the rung levels, which are grace_period, grace_period * reduction_factor, grace_period * (reduction_factor ** 2), etc. All rung levels must be less or equal than max_t. It is recommended to make max_t equal to the largest rung level. For example, if grace_period = 1, reduction_factor = 3, it is in general recommended to use max_t = 9, max_t = 27, or max_t = 81. Choosing a max_t value “off the grid” works against the successive halving principle that the total resources spent in a rung should be roughly equal between rungs. If in the example above, you set max_t = 10, about a third of configurations reaching 9 epochs are allowed to proceed, but only for one more epoch.

  • With reduction_factor, you tune the extent to which successive halving filtering is applied. The larger this integer, the fewer configurations make it to higher number of epochs. Values 2, 3, 4 are commonly used.

  • Finally, grace_period should be set to the smallest resource (number of epochs) for which you expect any meaningful differentiation between configurations. While grace_period = 1 should always be explored, it may be too low for any meaningful stopping decisions to be made at the first rung.

  • brackets sets the maximum number of brackets in Hyperband (make sure to study the Hyperband paper or follow-ups for details). For brackets = 1, you are running successive halving (single bracket). Higher brackets have larger effective grace_period values (so runs are not stopped until later), yet are also chosen with less probability. We recommend to always consider successive halving (brackets = 1) in a comparison.

  • Finally, with type (values stopping, promotion) you are choosing different ways of extending successive halving scheduling to the asynchronous case. The method for the default stopping is simpler and seems to perform well, but promotion is more careful promoting configurations to higher resource levels, which can work better in some cases.

Asynchronous BOHB

Finally, here are some ideas for tuning asynchronous BOHB, apart from tuning its HyperbandScheduling component. You need to pass these options in search_options.

  • We support a range of different surrogate models over the criterion functions across resource levels. All of them are jointly dependent Gaussian process models, meaning that data collected at all resource levels are modelled together. The surrogate model is selected by gp_resource_kernel, values are matern52, matern52-res-warp, exp-decay-sum, exp-decay-combined, exp-decay-delta1. These are variants of either a joint Matern 5/2 kernel over configuration and resource, or the exponential decay model. Details about the latter can be found here.

  • Fitting a Gaussian process surrogate model to data encurs a cost which scales cubically with the number of datapoints. When applied to expensive deep learning workloads, even multi-fidelity asynchronous BOHB is rarely running up more than 100 observations or so (across all rung levels and brackets), and the GP computations are subdominant. However, if you apply it to cheaper train_fn and find yourself beyond 2000 total evaluations, the cost of GP fitting can become painful. In such a situation, you can explore the options opt_skip_period and opt_skip_num_max_resource. The basic idea is as follows. By far the most expensive part of a get_config call (picking the next configuration) is the refitting of the GP model to past data (this entails re-optimizing hyperparameters of the surrogate model itself). The options allow you to skip this expensive step for most get_config calls, after some initial period. Check the docstrings for details about these options. If you find yourself in such a situation and gain experience with these skipping features, make sure to contact the AutoGluon developers – we would love to learn about your use case.