|
| 1 | +# Lint as: python3 |
| 2 | +# Copyright 2020 Google LLC. All Rights Reserved. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +"""Integration tests for Distributing Cloud Tuner.""" |
| 16 | + |
| 17 | +import contextlib |
| 18 | +import io |
| 19 | +import os |
| 20 | +import re |
| 21 | +import kerastuner |
| 22 | +import tensorflow as tf |
| 23 | +from tensorflow import keras |
| 24 | +from tensorflow_cloud.tuner import optimizer_client |
| 25 | +from tensorflow_cloud.tuner.tuner import DistributingCloudTuner |
| 26 | + |
| 27 | +# If input dataset is created outside tuner.search(), |
| 28 | +# it requires eager execution even in TF 1.x. |
| 29 | +if tf.version.VERSION.split(".")[0] == "1": |
| 30 | + tf.compat.v1.enable_eager_execution() |
| 31 | + |
| 32 | +# The project id to use to run tests. |
| 33 | +_PROJECT_ID = os.environ["PROJECT_ID"] |
| 34 | + |
| 35 | +# The GCP region in which the end-to-end test is run. |
| 36 | +_REGION = os.environ["REGION"] |
| 37 | + |
| 38 | +# Study ID for testing |
| 39 | +_STUDY_ID_BASE = "dct_{}".format((os.environ["BUILD_ID"]).replace("-", "_")) |
| 40 | + |
| 41 | +# The base docker image to use for the remote environment. |
| 42 | +_DOCKER_IMAGE = os.environ["DOCKER_IMAGE"] |
| 43 | + |
| 44 | +# The staging bucket to use to copy the model and data for the remote run. |
| 45 | +_REMOTE_DIR = os.path.join("gs://", os.environ["TEST_BUCKET"], _STUDY_ID_BASE) |
| 46 | + |
| 47 | +# The search space for hyperparameters |
| 48 | +_HPS = kerastuner.engine.hyperparameters.HyperParameters() |
| 49 | +_HPS.Float("learning_rate", min_value=1e-4, max_value=1e-2, sampling="log") |
| 50 | +_HPS.Int("num_layers", 2, 10) |
| 51 | + |
| 52 | + |
| 53 | +def _load_data(dir_path=None): |
| 54 | + """Loads and prepares data.""" |
| 55 | + |
| 56 | + mnist_file_path = None |
| 57 | + if dir_path: |
| 58 | + mnist_file_path = os.path.join(dir_path, "mnist.npz") |
| 59 | + |
| 60 | + (x, y), (val_x, val_y) = keras.datasets.mnist.load_data(mnist_file_path) |
| 61 | + x = x.astype("float32") / 255.0 |
| 62 | + val_x = val_x.astype("float32") / 255.0 |
| 63 | + |
| 64 | + return ((x[:10000], y[:10000]), (val_x, val_y)) |
| 65 | + |
| 66 | + |
| 67 | +def _build_model(hparams): |
| 68 | + # Note that CloudTuner does not support adding hyperparameters in |
| 69 | + # the model building function. Instead, the search space is configured |
| 70 | + # by passing a hyperparameters argument when instantiating (constructing) |
| 71 | + # the tuner. |
| 72 | + model = keras.Sequential() |
| 73 | + model.add(keras.layers.Flatten(input_shape=(28, 28))) |
| 74 | + |
| 75 | + # Build the model with number of layers from the hyperparameters |
| 76 | + for _ in range(hparams.get("num_layers")): |
| 77 | + model.add(keras.layers.Dense(units=64, activation="relu")) |
| 78 | + model.add(keras.layers.Dense(10, activation="softmax")) |
| 79 | + |
| 80 | + # Compile the model with learning rate from the hyperparameters |
| 81 | + model.compile( |
| 82 | + optimizer=keras.optimizers.Adam(lr=hparams.get("learning_rate")), |
| 83 | + loss="sparse_categorical_crossentropy", |
| 84 | + metrics=["acc"], |
| 85 | + ) |
| 86 | + return model |
| 87 | + |
| 88 | + |
| 89 | +class _DistributingCloudTunerIntegrationTestBase(tf.test.TestCase): |
| 90 | + |
| 91 | + def setUp(self): |
| 92 | + super(_DistributingCloudTunerIntegrationTestBase, self).setUp() |
| 93 | + self._study_id = None |
| 94 | + |
| 95 | + def _assert_output(self, fn, regex_str): |
| 96 | + stdout = io.StringIO() |
| 97 | + with contextlib.redirect_stdout(stdout): |
| 98 | + fn() |
| 99 | + output = stdout.getvalue() |
| 100 | + self.assertRegex(output, re.compile(regex_str, re.DOTALL)) |
| 101 | + |
| 102 | + def _assert_results_summary(self, fn): |
| 103 | + self._assert_output( |
| 104 | + fn, ".*Results summary.*Trial summary.*Hyperparameters.*") |
| 105 | + |
| 106 | + def _delete_dir(self, path) -> None: |
| 107 | + """Deletes a directory if exists.""" |
| 108 | + if tf.io.gfile.isdir(path): |
| 109 | + tf.io.gfile.rmtree(path) |
| 110 | + |
| 111 | + def tearDown(self): |
| 112 | + super(_DistributingCloudTunerIntegrationTestBase, self).tearDown() |
| 113 | + |
| 114 | + # Delete the study used in the test, if present |
| 115 | + if self._study_id: |
| 116 | + service = optimizer_client.create_or_load_study( |
| 117 | + _PROJECT_ID, _REGION, self._study_id, None) |
| 118 | + service.delete_study() |
| 119 | + |
| 120 | + tf.keras.backend.clear_session() |
| 121 | + |
| 122 | + # Delete log files, saved_models and other training assets |
| 123 | + self._delete_dir(_REMOTE_DIR) |
| 124 | + |
| 125 | + |
| 126 | +class DistributingCloudTunerIntegrationTest( |
| 127 | + _DistributingCloudTunerIntegrationTestBase): |
| 128 | + |
| 129 | + def setUp(self): |
| 130 | + super(DistributingCloudTunerIntegrationTest, self).setUp() |
| 131 | + (self._x, self._y), (self._val_x, self._val_y) = _load_data( |
| 132 | + self.get_temp_dir()) |
| 133 | + |
| 134 | + def testCloudTunerHyperparameters(self): |
| 135 | + """Test case to configure Distributing Tuner with HyperParameters.""" |
| 136 | + study_id = "{}_hyperparameters".format(_STUDY_ID_BASE) |
| 137 | + self._study_id = study_id |
| 138 | + |
| 139 | + tuner = DistributingCloudTuner( |
| 140 | + _build_model, |
| 141 | + project_id=_PROJECT_ID, |
| 142 | + region=_REGION, |
| 143 | + objective="acc", |
| 144 | + hyperparameters=_HPS, |
| 145 | + max_trials=2, |
| 146 | + study_id=study_id, |
| 147 | + directory=_REMOTE_DIR, |
| 148 | + container_uri=_DOCKER_IMAGE |
| 149 | + ) |
| 150 | + |
| 151 | + tuner.search( |
| 152 | + x=self._x, |
| 153 | + y=self._y, |
| 154 | + epochs=2, |
| 155 | + validation_data=(self._val_x, self._val_y), |
| 156 | + ) |
| 157 | + |
| 158 | + self._assert_results_summary(tuner.results_summary) |
| 159 | + |
| 160 | +if __name__ == "__main__": |
| 161 | + tf.test.main() |
0 commit comments