Distributed Hyperparameter Optimization on local machine

maggy - IRIS Example

Created: 24/04/2019

This notebook illustrates the usage of the maggy framework for asynchronous hyperparameter optimization on the famous Iris dataset.

In this specific example we are using random search over three parameters and we are deploying the median early stopping rule in order to make use of the asynchrony of the framework. The Median Stopping Rule implements the simple strategy of stopping a trial if its performance falls below the median of other trials at similar points in time.

We are using Keras for this example. This notebook works with any Spark cluster given that you are using maggy 0.1. In future versions we will add functionality that relies on Hopsworks.

This notebook has been tested with TensorFlow 2.4.1 and Spark 3.0.1.
Requires Python 3.6 or higher.

1. Spark Session

Make sure you have a running Spark Session/Context available. On Hopsworks just execute a simple command to start the spark application.

import pyspark
sp = pyspark.sql.SparkSession.builder \
    .master("local") \
    .appName("f-mnist-maggy") \
    .config("spark.dynamicAllocation.enabled", "true") \
    .config("spark.executor.cores", 4) \
    "spark.dynamicAllocation.minExecutors","1") \
    .config("spark.dynamicAllocation.maxExecutors","5") \

2. Searchspace definition

We want to conduct random search for the Iris example on three hyperparameters: Kernel size, pooling size and dropout rate. Hence, we have two continuous integer valued parameters and one double valued parameter.

from maggy import Searchspace

# The searchspace can be instantiated with parameters
sp = Searchspace(kernel=('INTEGER', [2, 8]), pool=('INTEGER', [2, 8]))

# Or additional parameters can be added one by one
sp.add('dropout', ('DOUBLE', [0.01, 0.99]))
Hyperparameter added: kernel
Hyperparameter added: pool
Hyperparameter added: dropout

3. Model training definition

The programming model is that you wrap the code containing the model training inside a wrapper function. Inside that wrapper function provide all imports and parts that make up your experiment.

There are several requirements for this wrapper function:

  1. The function should take the hyperparameters as arguments, plus one additional parameter reporter which is needed for reporting the current metric to the experiment driver.
  2. The function should return the metric that you want to optimize for. This should coincide with the metric being reported in the Keras callback (see next point).
  3. In order to leverage on the early stopping capabilities of maggy, you need to make use of the maggy reporter API. By including the reporter in your training loop, you are telling maggy which metric to report back to the experiment driver for optimization and to check for early stopping. It is as easy as adding reporter.broadcast(metric=YOUR_METRIC) for example at the end of your epoch or batch training step and adding a reporter argument to your function signature. If you are not writing your own training loop you can use the pre-written Keras callbacks:
    • KerasBatchEnd
    • KerasEpochEnd
      (Please see documentation for a detailed explanation.)

We are going to use the KerasBatchEnd callback to report back the accuracy after each batch. However, note that in the BatchEnd callback we have only access to training accuracy since validation after each batch would be too expensive.

from maggy import experiment
from maggy.callbacks import KerasBatchEnd

Definition of the training wrapper function: (maggy specific parts are highlighted with comments and correspond to the three points described above.)

### maggy: hyperparameters as arguments and including the reporter
def training_function(kernel, pool, dropout, reporter):
    import numpy as np
    import tensorflow as tf
    from tensorflow import keras
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
    from tensorflow.keras.callbacks import TensorBoard
    from tensorflow.keras.optimizers import RMSprop
    from tensorflow.keras.utils import to_categorical 
    from maggy import tensorboard
    from sklearn import datasets
    from sklearn.model_selection import train_test_split

    log_dir = tensorboard.logdir()

    # Import Iris data
    iris = datasets.load_iris()
    X = iris.data[:, :2]  # we only take the first two features.
    y = iris.target

    model = Sequential()


    # Setup TensorBoard
    tb_callback = TensorBoard(        
        profile_batch=0,  # workaround for issue #2084
    ### maggy: REPORTER API through keras callback
    callbacks = [KerasBatchEnd(reporter, metric='accuracy'), tb_callback]

    x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    y_train = to_categorical(y_train)
    y_test = to_categorical(y_test)
    score = model.evaluate(x_test, y_test, verbose=1)
    # Using print in the wrapper function will print underneath the Jupyter Cell with a 
    # prefix to indicate which prints come from the same executor
    print('Test loss:', score[0])
    print('Test accuracy:', score[1])
    ### maggy: return the metric to be optimized, test accuracy in this case
    return score[1]

4. Launching the experiment

Finally, we are ready to launch the maggy experiment. There are a variety of parameters to specify, some of which are optional: 1. train_fn: your previously specified training wrapper function 2. searchspace: the searchspace object 3. optimizer: the optimization algorithm to be used (only ‘randomsearch’ available at the moment) 4. direction: maximize or minimize the specified metric 5. num_trials: number of different parameter combinations to be evaluated 6. name: an experiment name 7. hb_interval: Time in seconds between the heartbeat messages with the metric to the experiment driver. A sensible value is not much smaller than the frequency in which your training loop updates the metric. So using the KerasBatchEnd reporter callback, it does not make sense having a much smaller interval than the amount of time a batch takes to be processed. 8. es_interval: Interval in seconds, specifying how often the currently running trials should be checked for early stopping. Should be bigger than the hb_interval. 9. es_min: Minimum number of trials to be finished before starting to check for early stopping. For example, the median stopping rule implements the simple strategy of stopping a trial if its performance falls below the median of finished trials at similar points in time. We only want to start comparing to the median once there are several trials finished.

from maggy.experiment_config import OptimizationConfig

config = OptimizationConfig(num_trials=4,

result = experiment.lagom(train_fn=training_function, config=config)
Started Maggy Experiment: hp_tuning_test, local-1614678752937, run 2

------ RandomSearch Results ------ direction(max) 
BEST combination {"kernel": 3, "pool": 6, "dropout": 0.388353358021858} -- metric 0.7
WORST combination {"kernel": 8, "pool": 8, "dropout": 0.11248860558867116} -- metric 0.6333333
AVERAGE metric -- 0.6666666716337204
Total job time 0 hours, 0 minutes, 33 seconds

Finished Experiment

To observe the progress, you can check the log of the jupyter notebook’s server. The log will be saved in ‘path-to-work-directory/experiments-log/’. TensorBoard support is added in the coming version.