Maggy Distributed Hyper Parameter Optimization with Tensorflow example

maggy on Databricks - MNIST Example

Created: 01/02/2021

This notebook illustrates the usage of the maggy framework for asynchronous hyperparameter optimization on the famous MNIST 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.5.

This notebook has been tested with the Databricks Runtime Version 7.6 ML, TensorFlow 2.3.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.

import pyspark


    <p><b>SparkSession - hive</b></p>


Spark UI

Databricks Shell

Make sure you have the right tensorflow version.

import tensorflow as tf
if tf.__version__ != '2.3.1':
  !pip install tensorflow==2.3.1

2. Searchspace definition

We want to conduct random search for the MNIST 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.python.keras.datasets import mnist
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
    from tensorflow.keras.callbacks import TensorBoard
    from maggy import tensorboard

    log_dir = tensorboard.logdir()
    batch_size = 512
    num_classes = 10
    epochs = 1

    # Input image dimensions
    img_rows, img_cols = 28, 28
    train_filenames = ["TourData/mnist/train/train.tfrecords"]
    validation_filenames = ["TourData/mnist/validation/validation.tfrecords"]
    (x_train, y_train), (x_test, y_test) = mnist.load_data()
    # Scale images to the [0, 1] range
    x_train = x_train.astype("float32") / 255
    x_test = x_test.astype("float32") / 255
    # Make sure images have shape (28, 28, 1)
    x_train = np.expand_dims(x_train, -1)
    x_test = np.expand_dims(x_test, -1)
    print("x_train shape:", x_train.shape)
    print(x_train.shape[0], "train samples")
    print(x_test.shape[0], "test samples")
    num_train = x_train.shape[0]
    num_val = x_test.shape[0]

    # convert class vectors to binary class matrices
    y_train = keras.utils.to_categorical(y_train, num_classes)
    y_test = keras.utils.to_categorical(y_test, num_classes)
    # Create an iterator over the dataset
    def data_input(filenames, batch_size=128, shuffle=False, repeat=None):

        def parser(serialized_example):
            """Parses a single tf.Example into image and label tensors."""
            features =
                    'image_raw':[], tf.string),
                    'label':[], tf.int64),
            image =['image_raw'], tf.uint8)
            image.set_shape([28 * 28])

            # Normalize the values of the image from the range [0, 255] to [-0.5, 0.5]
            image = tf.cast(image, tf.float32) / 255 - 0.5
            label = tf.cast(features['label'], tf.int32)
            # Reshape the tensor
            image = tf.reshape(image, [img_rows, img_cols, 1])
            # Create a one hot array for your labels
            label = tf.one_hot(label, num_classes)
            return image, label

        # Import MNIST data
        dataset =
        num_samples = sum(1 for _ in dataset)

        # Map the parser over dataset, and batch results by up to batch_size
        dataset =
        if shuffle:
            dataset = dataset.shuffle(buffer_size=128)
        dataset = dataset.batch(batch_size)
        dataset = dataset.repeat(repeat)
        return dataset, num_samples
    input_shape = (28, 28, 1)

    model = Sequential()
    model.add(Conv2D(32, kernel_size=(kernel, kernel),
    model.add(Conv2D(64, (kernel, kernel), activation='relu'))
    model.add(MaxPooling2D(pool_size=(pool, pool)))
    model.add(Dense(128, activation='relu'))
    model.add(Dense(num_classes, activation='softmax'))

    opt = keras.optimizers.Adadelta(1.0)

    # 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]
, y_train,
              steps_per_epoch = num_train//batch_size,
              callbacks=callbacks, # add callback
    score = model.evaluate(x_test, y_test, steps=num_val//batch_size, 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)

You are running Maggy on Databricks. Started Maggy Experiment: MNIST, app-20210225103041-0000, run 1

—— RandomSearch Results —— direction(max) BEST combination {"kernel": 7, "pool": 4, "dropout": 0.07650065874317517} – metric 0.9725000262260437 WORST combination {"kernel": 8, "pool": 7, "dropout": 0.033706837495202924} – metric 0.9567999839782715 AVERAGE metric – 0.9657133340835571 EARLY STOPPED Trials – 0 Total job time 0 hours, 10 minutes, 9 seconds

Finished Experiment

To observe the progress, you can check the sterr of the spark executors.

Each experiment will create a folder at the path ‘/dbfs/maggy_log/‘.

import os 

Out[13]: ['app-20210223105721-0000', 'app-20210224090409-0000', 'app-20210224090834-0000', 'app-20210224112520-0000', 'app-20210225103041-0000']