.. _sec_custom_advancedhpo:
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
-----------------
.. code:: python
# 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
.. code:: python
mx.__version__
.. parsed-literal::
:class: output
'1.7.0'
You can also check the version of AutoGluon and the specific commit and
check that it matches what you want.
.. code:: python
import autogluon.core.version
ag.version.__version__
.. parsed-literal::
:class: output
'0.3.0b20210827'
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
.. code:: python
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
.. code:: python
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)
n_classes
.. parsed-literal::
:class: output
100%|██████████| 704/704 [00:00<00:00, 61391.12KB/s]
100%|██████████| 2521/2521 [00:00<00:00, 41913.94KB/s]
3KB [00:00, 4128.25KB/s]
8KB [00:00, 7674.85KB/s]
15KB [00:00, 12932.08KB/s]
2998KB [00:00, 21941.93KB/s]
881KB [00:00, 66225.46KB/s]
3KB [00:00, 3871.67KB/s]
.. parsed-literal::
:class: output
26
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
.. code:: python
@ag.args(n_units_1=ag.space.Int(lower=16, upper=128),
n_units_2=ag.space.Int(lower=16, upper=128),
dropout_1=ag.space.Real(lower=0, upper=.75),
dropout_2=ag.space.Real(lower=0, upper=.75),
learning_rate=ag.space.Real(lower=1e-6, upper=1, log=True),
batch_size=ag.space.Int(lower=8, upper=128),
scale_1=ag.space.Real(lower=0.001, upper=10, log=True),
scale_2=ag.space.Real(lower=0.001, upper=10, log=True),
epochs=9)
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',
weight_initializer=mx.initializer.Uniform(scale=scale_1)))
# Dropout
net.add(gluon.nn.Dropout(dropout_1))
# Layer 2
net.add(nn.Dense(n_units_2, activation='relu',
weight_initializer=mx.initializer.Uniform(scale=scale_2)))
# Dropout
net.add(gluon.nn.Dropout(dropout_2))
# Output
net.add(nn.Dense(n_classes))
net.initialize(ctx=ctx)
trainer = gluon.Trainer(net.collect_params(), 'adam',
{'learning_rate': learning_rate})
for epoch in range(args.epochs):
ts_epoch = time.time()
train_iter = mx.io.NDArrayIter(
data={'data': X_train},
label={'label': y_train},
batch_size=batch_size,
shuffle=True)
valid_iter = mx.io.NDArrayIter(
data={'data': X_valid},
label={'label': y_valid},
batch_size=batch_size,
shuffle=False)
metric = mx.metric.Accuracy()
loss = gluon.loss.SoftmaxCrossEntropyLoss()
for batch in train_iter:
data = batch.data[0].as_in_context(ctx)
label = batch.label[0].as_in_context(ctx)
with autograd.record():
output = net(data)
L = loss(output, label)
L.backward()
trainer.step(data.shape[0])
metric.update([label], [output])
name, train_acc = metric.get()
metric = mx.metric.Accuracy()
for batch in valid_iter:
data = batch.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
reporter(
epoch=epoch + 1,
objective=float(val_acc),
eval_time=eval_time,
time_step=ts_now,
elapsed_time=elapsed_time)
**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.
.. code:: python
SCHEDULER = "hbs"
SEARCHER = "bayesopt"
.. code:: python
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,
runtime_fn=compute_runtime,
error_fn=compute_error):
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),
error=error_fn(task_df),
target_epoch=task_df["epoch"].iloc[-1])
task_dfs.append(task_df)
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)
.. code:: python
search_options = {
'num_init_random': 2,
'debug_log': True}
if SCHEDULER == 'fifo':
myscheduler = ag.scheduler.FIFOScheduler(
run_mlp_openml,
resource=resources,
searcher=SEARCHER,
search_options=search_options,
time_out=120,
time_attr=RESOURCE_ATTR_NAME,
reward_attr=REWARD_ATTR_NAME)
else:
# 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_mlp_openml,
resource=resources,
searcher=SEARCHER,
search_options=search_options,
time_out=120,
time_attr=RESOURCE_ATTR_NAME,
reward_attr=REWARD_ATTR_NAME,
type=sch_type,
grace_period=1,
reduction_factor=3,
brackets=1)
# run tasks
myscheduler.run()
myscheduler.join_jobs()
results_df = process_training_history(
myscheduler.training_history.copy(),
start_timestamp=myscheduler._start_time)
.. parsed-literal::
:class: output
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
'stop_jobs_after_time_out=False'
/var/lib/jenkins/workspace/workspace/autogluon-tutorial-course-v3/venv/lib/python3.7/site-packages/distributed/worker.py:3871: UserWarning: Large object of size 1.24 MiB detected in task graph:
(0, , { ... 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)
.. parsed-literal::
:class: output
Epoch 1 ; Time: 0.477731 ; Training: accuracy=0.260079 ; Validation: accuracy=0.531250
Epoch 2 ; Time: 0.914744 ; Training: accuracy=0.496365 ; Validation: accuracy=0.655247
Epoch 3 ; Time: 1.438264 ; Training: accuracy=0.559650 ; Validation: accuracy=0.694686
Epoch 4 ; Time: 1.863681 ; Training: accuracy=0.588896 ; Validation: accuracy=0.711063
Epoch 5 ; Time: 2.278390 ; Training: accuracy=0.609385 ; Validation: accuracy=0.726939
Epoch 6 ; Time: 2.700639 ; Training: accuracy=0.628139 ; Validation: accuracy=0.745321
Epoch 7 ; Time: 3.123221 ; Training: accuracy=0.641193 ; Validation: accuracy=0.750501
Epoch 8 ; Time: 3.536600 ; Training: accuracy=0.653751 ; Validation: accuracy=0.763202
Epoch 9 ; Time: 3.971062 ; Training: accuracy=0.665482 ; Validation: accuracy=0.766043
Epoch 1 ; Time: 0.293328 ; Training: accuracy=0.036966 ; Validation: accuracy=0.042051
Epoch 1 ; Time: 3.262407 ; Training: accuracy=0.313682 ; Validation: accuracy=0.577273
Epoch 2 ; Time: 6.727944 ; Training: accuracy=0.472637 ; Validation: accuracy=0.655219
Epoch 3 ; Time: 10.150773 ; Training: accuracy=0.525539 ; Validation: accuracy=0.688552
Epoch 1 ; Time: 0.346154 ; Training: accuracy=0.284234 ; Validation: accuracy=0.333720
Epoch 1 ; Time: 4.345959 ; Training: accuracy=0.045922 ; Validation: accuracy=0.035162
Epoch 1 ; Time: 3.599658 ; Training: accuracy=0.342921 ; Validation: accuracy=0.593203
Epoch 2 ; Time: 7.163071 ; Training: accuracy=0.442556 ; Validation: accuracy=0.649899
Epoch 3 ; Time: 10.710269 ; Training: accuracy=0.471237 ; Validation: accuracy=0.681528
Epoch 1 ; Time: 3.594476 ; Training: accuracy=0.199436 ; Validation: accuracy=0.508412
Epoch 1 ; Time: 0.473815 ; Training: accuracy=0.294035 ; Validation: accuracy=0.659457
Epoch 2 ; Time: 0.885876 ; Training: accuracy=0.400000 ; Validation: accuracy=0.680751
Epoch 3 ; Time: 1.285258 ; Training: accuracy=0.424275 ; Validation: accuracy=0.698357
Epoch 4 ; Time: 1.684036 ; Training: accuracy=0.440597 ; Validation: accuracy=0.708417
Epoch 5 ; Time: 2.132258 ; Training: accuracy=0.450621 ; Validation: accuracy=0.710597
Epoch 6 ; Time: 2.582457 ; Training: accuracy=0.449379 ; Validation: accuracy=0.709759
Epoch 7 ; Time: 3.023877 ; Training: accuracy=0.456669 ; Validation: accuracy=0.715627
Epoch 8 ; Time: 3.525568 ; Training: accuracy=0.463629 ; Validation: accuracy=0.713615
Epoch 9 ; Time: 3.974200 ; Training: accuracy=0.463795 ; Validation: accuracy=0.719484
Epoch 1 ; Time: 0.336666 ; Training: accuracy=0.473428 ; Validation: accuracy=0.670726
Epoch 2 ; Time: 0.618808 ; Training: accuracy=0.699727 ; Validation: accuracy=0.737114
Epoch 3 ; Time: 0.885155 ; Training: accuracy=0.738078 ; Validation: accuracy=0.766305
Epoch 4 ; Time: 1.152507 ; Training: accuracy=0.757831 ; Validation: accuracy=0.781151
Epoch 5 ; Time: 1.414817 ; Training: accuracy=0.778411 ; Validation: accuracy=0.789158
Epoch 6 ; Time: 1.676002 ; Training: accuracy=0.781056 ; Validation: accuracy=0.800500
Epoch 7 ; Time: 1.950284 ; Training: accuracy=0.788412 ; Validation: accuracy=0.806005
Epoch 8 ; Time: 2.211399 ; Training: accuracy=0.795190 ; Validation: accuracy=0.812844
Epoch 9 ; Time: 2.476729 ; Training: accuracy=0.802546 ; Validation: accuracy=0.813511
Epoch 1 ; Time: 0.769078 ; Training: accuracy=0.041380 ; Validation: accuracy=0.038481
Epoch 1 ; Time: 0.418786 ; Training: accuracy=0.058244 ; Validation: accuracy=0.100840
Epoch 1 ; Time: 0.341380 ; Training: accuracy=0.091512 ; Validation: accuracy=0.172248
Epoch 1 ; Time: 1.110397 ; Training: accuracy=0.351708 ; Validation: accuracy=0.585870
Epoch 2 ; Time: 2.156562 ; Training: accuracy=0.554874 ; Validation: accuracy=0.687300
Epoch 3 ; Time: 3.224946 ; Training: accuracy=0.616379 ; Validation: accuracy=0.726997
Epoch 4 ; Time: 4.306466 ; Training: accuracy=0.646883 ; Validation: accuracy=0.753743
Epoch 5 ; Time: 5.383441 ; Training: accuracy=0.673491 ; Validation: accuracy=0.764340
Epoch 6 ; Time: 6.557937 ; Training: accuracy=0.688992 ; Validation: accuracy=0.787384
Epoch 7 ; Time: 7.656638 ; Training: accuracy=0.705156 ; Validation: accuracy=0.795290
Epoch 8 ; Time: 8.777302 ; Training: accuracy=0.716015 ; Validation: accuracy=0.803196
Epoch 9 ; Time: 9.873135 ; Training: accuracy=0.729775 ; Validation: accuracy=0.817662
Epoch 1 ; Time: 0.293024 ; Training: accuracy=0.034046 ; Validation: accuracy=0.041390
Epoch 1 ; Time: 0.452226 ; Training: accuracy=0.149266 ; Validation: accuracy=0.425415
Epoch 1 ; Time: 0.461075 ; Training: accuracy=0.387649 ; Validation: accuracy=0.651606
Epoch 2 ; Time: 0.878314 ; Training: accuracy=0.494461 ; Validation: accuracy=0.710676
Epoch 3 ; Time: 1.278276 ; Training: accuracy=0.516452 ; Validation: accuracy=0.701640
Epoch 1 ; Time: 0.365272 ; Training: accuracy=0.338131 ; Validation: accuracy=0.634073
Epoch 2 ; Time: 0.719622 ; Training: accuracy=0.516543 ; Validation: accuracy=0.699765
Epoch 3 ; Time: 1.028254 ; Training: accuracy=0.572705 ; Validation: accuracy=0.726142
Epoch 4 ; Time: 1.342257 ; Training: accuracy=0.601075 ; Validation: accuracy=0.745464
Epoch 5 ; Time: 1.666820 ; Training: accuracy=0.624069 ; Validation: accuracy=0.758401
Epoch 6 ; Time: 1.992454 ; Training: accuracy=0.640529 ; Validation: accuracy=0.773522
Epoch 7 ; Time: 2.317924 ; Training: accuracy=0.654756 ; Validation: accuracy=0.784106
Epoch 8 ; Time: 2.691767 ; Training: accuracy=0.665178 ; Validation: accuracy=0.793851
Epoch 9 ; Time: 3.018941 ; Training: accuracy=0.673615 ; Validation: accuracy=0.804435
Epoch 1 ; Time: 1.151736 ; Training: accuracy=0.574470 ; Validation: accuracy=0.740591
Epoch 2 ; Time: 2.389769 ; Training: accuracy=0.768555 ; Validation: accuracy=0.806788
Epoch 3 ; Time: 3.587379 ; Training: accuracy=0.822896 ; Validation: accuracy=0.843078
Epoch 4 ; Time: 4.799266 ; Training: accuracy=0.851972 ; Validation: accuracy=0.858031
Epoch 5 ; Time: 6.010549 ; Training: accuracy=0.876740 ; Validation: accuracy=0.866431
Epoch 6 ; Time: 7.334442 ; Training: accuracy=0.891319 ; Validation: accuracy=0.880208
Epoch 7 ; Time: 8.535698 ; Training: accuracy=0.905235 ; Validation: accuracy=0.899362
Epoch 8 ; Time: 9.825008 ; Training: accuracy=0.915590 ; Validation: accuracy=0.908602
Epoch 9 ; Time: 11.015872 ; Training: accuracy=0.924205 ; Validation: accuracy=0.908770
Epoch 1 ; Time: 0.277816 ; Training: accuracy=0.440990 ; Validation: accuracy=0.643333
Epoch 2 ; Time: 0.507194 ; Training: accuracy=0.701691 ; Validation: accuracy=0.745833
Epoch 3 ; Time: 0.723724 ; Training: accuracy=0.769567 ; Validation: accuracy=0.796167
Epoch 4 ; Time: 0.940259 ; Training: accuracy=0.810887 ; Validation: accuracy=0.824667
Epoch 5 ; Time: 1.156878 ; Training: accuracy=0.837938 ; Validation: accuracy=0.841667
Epoch 6 ; Time: 1.392211 ; Training: accuracy=0.859052 ; Validation: accuracy=0.846167
Epoch 7 ; Time: 1.627312 ; Training: accuracy=0.870433 ; Validation: accuracy=0.868167
Epoch 8 ; Time: 1.868994 ; Training: accuracy=0.886763 ; Validation: accuracy=0.878333
Epoch 9 ; Time: 2.162138 ; Training: accuracy=0.898557 ; Validation: accuracy=0.882833
Epoch 1 ; Time: 3.610552 ; Training: accuracy=0.492871 ; Validation: accuracy=0.675808
Epoch 2 ; Time: 7.067141 ; Training: accuracy=0.655836 ; Validation: accuracy=0.722914
Epoch 3 ; Time: 10.528140 ; Training: accuracy=0.696452 ; Validation: accuracy=0.772207
Epoch 4 ; Time: 14.019114 ; Training: accuracy=0.727868 ; Validation: accuracy=0.793237
Epoch 5 ; Time: 17.427324 ; Training: accuracy=0.750249 ; Validation: accuracy=0.807032
Epoch 6 ; Time: 20.987491 ; Training: accuracy=0.764009 ; Validation: accuracy=0.825538
Epoch 7 ; Time: 24.378841 ; Training: accuracy=0.779924 ; Validation: accuracy=0.833277
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.
.. code:: python
results_df.head()
.. raw:: html
|
bracket |
elapsed_time |
epoch |
error |
eval_time |
objective |
runtime |
target_epoch |
task_id |
terminated |
time_step |
best |
0 |
0 |
0.480405 |
1 |
0.468750 |
0.475277 |
0.531250 |
0.849408 |
9 |
0 |
NaN |
1.630102e+09 |
0.468750 |
1 |
0 |
0.916463 |
2 |
0.344753 |
0.428144 |
0.655247 |
1.285465 |
9 |
0 |
NaN |
1.630102e+09 |
0.344753 |
2 |
0 |
1.439972 |
3 |
0.305314 |
0.521574 |
0.694686 |
1.808974 |
9 |
0 |
NaN |
1.630102e+09 |
0.305314 |
3 |
0 |
1.865399 |
4 |
0.288937 |
0.421332 |
0.711063 |
2.234402 |
9 |
0 |
NaN |
1.630102e+09 |
0.288937 |
4 |
0 |
2.279886 |
5 |
0.273061 |
0.412596 |
0.726939 |
2.648888 |
9 |
0 |
NaN |
1.630102e+09 |
0.273061 |
.. code:: python
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.xticks(fontsize=12)
plt.xlim(0, 120)
plt.ylim(0, 0.5)
plt.yticks(fontsize=12)
plt.xlabel("Runtime [s]", fontsize=14)
plt.ylabel("Objective", fontsize=14)
.. parsed-literal::
:class: output
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 :ref:`sec_customstorch`). 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.