test_builtin_tuners.py 19 KB
Newer Older
liuzhe-lz's avatar
liuzhe-lz committed
1
2
3
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

4
import glob
Deshui Yu's avatar
Deshui Yu committed
5
import json
6
7
import logging
import os
8
import random
9
10
import shutil
import sys
RayMeng8's avatar
RayMeng8 committed
11
from collections import deque
Deshui Yu's avatar
Deshui Yu committed
12
13
from unittest import TestCase, main

14
15
16
17
18
19
from nni.batch_tuner.batch_tuner import BatchTuner
from nni.evolution_tuner.evolution_tuner import EvolutionTuner
from nni.gp_tuner.gp_tuner import GPTuner
from nni.gridsearch_tuner.gridsearch_tuner import GridSearchTuner
from nni.hyperopt_tuner.hyperopt_tuner import HyperoptTuner
from nni.metis_tuner.metis_tuner import MetisTuner
RayMeng8's avatar
RayMeng8 committed
20
21
from nni.msg_dispatcher import _pack_parameter, MsgDispatcher
from nni.pbt_tuner.pbt_tuner import PBTTuner
22
from nni.regularized_evolution_tuner.regularized_evolution_tuner import RegularizedEvolutionTuner
23

24
25
26
27
28
try:
    from nni.smac_tuner.smac_tuner import SMACTuner
except ImportError:
    assert sys.platform == "win32"
from nni.tuner import Tuner
Deshui Yu's avatar
Deshui Yu committed
29

RayMeng8's avatar
RayMeng8 committed
30

31
32
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('test_tuner')
Deshui Yu's avatar
Deshui Yu committed
33
34


35
class BuiltinTunersTestCase(TestCase):
36
37
38
39
40
41
    """
    Targeted at testing functions of built-in tuners, including
        - [ ] load_checkpoint
        - [ ] save_checkpoint
        - [X] update_search_space
        - [X] generate_multiple_parameters
42
        - [X] import_data
43
        - [ ] trial_end
44
        - [x] receive_trial_result
45
46
    """

47
48
49
50
51
    def setUp(self):
        self.test_round = 3
        self.params_each_round = 50
        self.exhaustive = False

RayMeng8's avatar
RayMeng8 committed
52
53
54
55
56
    def send_trial_callback(self, param_queue):
        def receive(*args):
            param_queue.append(tuple(args))
        return receive

57
58
59
60
    def send_trial_result(self, tuner, parameter_id, parameters, metrics):
        tuner.receive_trial_result(parameter_id, parameters, metrics)
        tuner.trial_end(parameter_id, True)

61
62
    def search_space_test_one(self, tuner_factory, search_space, nas=False):
        # nas: whether the test checks classic nas tuner
63
64
65
66
        tuner = tuner_factory()
        self.assertIsInstance(tuner, Tuner)
        tuner.update_search_space(search_space)

67
        for i in range(self.test_round):
RayMeng8's avatar
RayMeng8 committed
68
            queue = deque()
69
            parameters = tuner.generate_multiple_parameters(list(range(i * self.params_each_round,
RayMeng8's avatar
RayMeng8 committed
70
71
                                                                       (i + 1) * self.params_each_round)),
                                                            st_callback=self.send_trial_callback(queue))
72
            logger.debug(parameters)
73
74
75
            check_range = lambda parameters, search_space: self.nas_check_range(parameters, search_space) \
                                                           if nas else self.check_range(parameters, search_space)
            check_range(parameters, search_space)
76
            for k in range(min(len(parameters), self.params_each_round)):
77
                self.send_trial_result(tuner, self.params_each_round * i + k, parameters[k], random.uniform(-100, 100))
RayMeng8's avatar
RayMeng8 committed
78
79
            while queue:
                id_, params = queue.popleft()
80
                check_range([params], search_space)
81
                self.send_trial_result(tuner, id_, params, random.uniform(-100, 100))
82
83
            if not parameters and not self.exhaustive:
                raise ValueError("No parameters generated")
84
85
86
87
88
89
90

    def check_range(self, generated_params, search_space):
        EPS = 1E-6
        for param in generated_params:
            if self._testMethodName == "test_batch":
                param = {list(search_space.keys())[0]: param}
            for k, v in param.items():
RayMeng8's avatar
RayMeng8 committed
91
92
93
                if k == "load_checkpoint_dir" or k == "save_checkpoint_dir":
                    self.assertIsInstance(v, str)
                    continue
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
                if k.startswith("_mutable_layer"):
                    _, block, layer, choice = k.split("/")
                    cand = search_space[block]["_value"][layer].get(choice)
                    # cand could be None, e.g., optional_inputs_chosen_state
                    if choice == "layer_choice":
                        self.assertIn(v, cand)
                    if choice == "optional_input_size":
                        if isinstance(cand, int):
                            self.assertEqual(v, cand)
                        else:
                            self.assertGreaterEqual(v, cand[0])
                            self.assertLessEqual(v, cand[1])
                    if choice == "optional_inputs":
                        pass  # ignore for now
                    continue
                item = search_space[k]
                if item["_type"] == "choice":
                    self.assertIn(v, item["_value"])
                if item["_type"] == "randint":
                    self.assertIsInstance(v, int)
                if item["_type"] == "uniform":
                    self.assertIsInstance(v, float)
                if item["_type"] in ("randint", "uniform", "quniform", "loguniform", "qloguniform"):
                    self.assertGreaterEqual(v, item["_value"][0])
                    self.assertLessEqual(v, item["_value"][1])
                if item["_type"].startswith("q"):
                    multiple = v / item["_value"][2]
                    print(k, v, multiple, item)
                    if item["_value"][0] + EPS < v < item["_value"][1] - EPS:
                        self.assertAlmostEqual(int(round(multiple)), multiple)
                if item["_type"] in ("qlognormal", "lognormal"):
                    self.assertGreaterEqual(v, 0)
                if item["_type"] == "mutable_layer":
                    for layer_name in item["_value"].keys():
                        self.assertIn(v[layer_name]["chosen_layer"], item["layer_choice"])

130
131
132
133
134
135
136
137
138
139
140
141
142
    def nas_check_range(self, generated_params, search_space):
        for params in generated_params:
            for k in params:
                v = params[k]
                items = search_space[k]
                if items['_type'] == 'layer_choice':
                    self.assertIn(v['_value'], items['_value'])
                elif items['_type'] == 'input_choice':
                    for choice in v['_value']:
                        self.assertIn(choice, items['_value']['candidates'])
                else:
                    raise KeyError

143
144
    def search_space_test_all(self, tuner_factory, supported_types=None, ignore_types=None, fail_types=None):
        # Three types: 1. supported; 2. ignore; 3. fail.
145
146
147
148
149
150
151
152
153
154
155
        # NOTE(yuge): ignore types
        # Supported types are listed in the table. They are meant to be supported and should be correct.
        # Other than those, all the rest are "unsupported", which are expected to produce ridiculous results
        # or throw some exceptions. However, there are certain types I can't check. For example, generate
        # "normal" using GP Tuner returns successfully and results are fine if we check the range (-inf to +inf),
        # but they make no sense: it's not a normal distribution. So they are ignored in tests for now.
        with open(os.path.join(os.path.dirname(__file__), "assets/search_space.json"), "r") as fp:
            search_space_all = json.load(fp)
        if supported_types is None:
            supported_types = ["choice", "randint", "uniform", "quniform", "loguniform", "qloguniform",
                               "normal", "qnormal", "lognormal", "qlognormal"]
156
157
158
159
        if fail_types is None:
            fail_types = []
        if ignore_types is None:
            ignore_types = []
160
161
162
        full_supported_search_space = dict()
        for single in search_space_all:
            space = search_space_all[single]
163
            if any(single.startswith(t) for t in ignore_types):
164
                continue
165
            expected_fail = not any(single.startswith(t) for t in supported_types) or \
RayMeng8's avatar
RayMeng8 committed
166
167
                any(single.startswith(t) for t in fail_types) or \
                "fail" in single  # name contains fail (fail on all)
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
            single_search_space = {single: space}
            if not expected_fail:
                # supports this key
                self.search_space_test_one(tuner_factory, single_search_space)
                full_supported_search_space.update(single_search_space)
            else:
                # unsupported key
                with self.assertRaises(Exception, msg="Testing {}".format(single)) as cm:
                    self.search_space_test_one(tuner_factory, single_search_space)
                logger.info("%s %s %s", tuner_factory, single, cm.exception)
        if not any(t in self._testMethodName for t in ["batch", "grid_search"]):
            # grid search fails for too many combinations
            logger.info("Full supported search space: %s", full_supported_search_space)
            self.search_space_test_one(tuner_factory, full_supported_search_space)

183
184
185
186
187
188
189
190
191
192
193
194
195
196
    def nas_search_space_test_all(self, tuner_factory):
        # Since classic tuner should support only LayerChoice and InputChoice,
        # ignore type and fail type are dismissed here. 
        with open(os.path.join(os.path.dirname(__file__), "assets/classic_nas_search_space.json"), "r") as fp:
            search_space_all = json.load(fp)
        full_supported_search_space = dict()
        for single in search_space_all:
            space = search_space_all[single]
            single_search_space = {single: space}
            self.search_space_test_one(tuner_factory, single_search_space, nas=True)
            full_supported_search_space.update(single_search_space)
        logger.info("Full supported search space: %s", full_supported_search_space)
        self.search_space_test_one(tuner_factory, full_supported_search_space, nas=True)

QuanluZhang's avatar
QuanluZhang committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
    def import_data_test_for_pbt(self):
        """
        test1: import data with complete epoch
        test2: import data with incomplete epoch
        """
        search_space = {
            "choice_str": {
                "_type": "choice",
                "_value": ["cat", "dog", "elephant", "cow", "sheep", "panda"]
            }
        }
        all_checkpoint_dir = os.path.expanduser("~/nni/checkpoint/test/")
        population_size = 4
        # ===import data at the beginning===
        tuner = PBTTuner(
            all_checkpoint_dir=all_checkpoint_dir,
            population_size=population_size
        )
        self.assertIsInstance(tuner, Tuner)
        tuner.update_search_space(search_space)
        save_dirs = [os.path.join(all_checkpoint_dir, str(i), str(0)) for i in range(population_size)]
        # create save checkpoint directory
        for save_dir in save_dirs:
            os.makedirs(save_dir, exist_ok=True)
        # for simplicity, omit "load_checkpoint_dir"
        data = [{"parameter": {"choice_str": "cat", "save_checkpoint_dir": save_dirs[0]}, "value": 1.1},
                {"parameter": {"choice_str": "dog", "save_checkpoint_dir": save_dirs[1]}, "value": {"default": 1.2, "tmp": 2}},
                {"parameter": {"choice_str": "cat", "save_checkpoint_dir": save_dirs[2]}, "value": 11},
                {"parameter": {"choice_str": "cat", "save_checkpoint_dir": save_dirs[3]}, "value": 7}]
        epoch = tuner.import_data(data)
        self.assertEqual(epoch, 1)
        logger.info("Imported data successfully at the beginning")
        shutil.rmtree(all_checkpoint_dir)
        # ===import another data at the beginning, test the case when there is an incompleted epoch===
        tuner = PBTTuner(
            all_checkpoint_dir=all_checkpoint_dir,
            population_size=population_size
        )
        self.assertIsInstance(tuner, Tuner)
        tuner.update_search_space(search_space)
        for i in range(population_size - 1):
            save_dirs.append(os.path.join(all_checkpoint_dir, str(i), str(1)))
        for save_dir in save_dirs:
            os.makedirs(save_dir, exist_ok=True)
        data = [{"parameter": {"choice_str": "cat", "save_checkpoint_dir": save_dirs[0]}, "value": 1.1},
                {"parameter": {"choice_str": "dog", "save_checkpoint_dir": save_dirs[1]}, "value": {"default": 1.2, "tmp": 2}},
                {"parameter": {"choice_str": "cat", "save_checkpoint_dir": save_dirs[2]}, "value": 11},
                {"parameter": {"choice_str": "cat", "save_checkpoint_dir": save_dirs[3]}, "value": 7},
                {"parameter": {"choice_str": "cat", "save_checkpoint_dir": save_dirs[4]}, "value": 1.1},
                {"parameter": {"choice_str": "dog", "save_checkpoint_dir": save_dirs[5]}, "value": {"default": 1.2, "tmp": 2}},
                {"parameter": {"choice_str": "cat", "save_checkpoint_dir": save_dirs[6]}, "value": 11}]
        epoch = tuner.import_data(data)
        self.assertEqual(epoch, 1)
        logger.info("Imported data successfully at the beginning with incomplete epoch")
        shutil.rmtree(all_checkpoint_dir)

253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
    def import_data_test(self, tuner_factory, stype="choice_str"):
        """
        import data at the beginning with number value and dict value
        import data in the middle also with number value and dict value, and duplicate data record
        generate parameters after data import

        Parameters
        ----------
        tuner_factory : lambda
            a lambda for instantiate a tuner
        stype : str
            the value type of hp choice, support "choice_str" and "choice_num"
        """
        if stype == "choice_str":
            search_space = {
                "choice_str": {
                    "_type": "choice",
                    "_value": ["cat", "dog", "elephant", "cow", "sheep", "panda"]
                }
            }
        elif stype == "choice_num":
            search_space = {
                "choice_num": {
                    "_type": "choice",
                    "_value": [10, 20, 30, 40, 50, 60]
                }
            }
        else:
            raise RuntimeError("Unexpected stype")
        tuner = tuner_factory()
        self.assertIsInstance(tuner, Tuner)
        tuner.update_search_space(search_space)
        # import data at the beginning
        if stype == "choice_str":
            data = [{"parameter": {"choice_str": "cat"}, "value": 1.1},
                    {"parameter": {"choice_str": "dog"}, "value": {"default": 1.2, "tmp": 2}}]
        else:
            data = [{"parameter": {"choice_num": 20}, "value": 1.1},
                    {"parameter": {"choice_num": 60}, "value": {"default": 1.2, "tmp": 2}}]
        tuner.import_data(data)
        logger.info("Imported data successfully at the beginning")
        # generate parameters
        parameters = tuner.generate_multiple_parameters(list(range(3)))
        for i in range(3):
            tuner.receive_trial_result(i, parameters[i], random.uniform(-100, 100))
        # import data in the middle
        if stype == "choice_str":
            data = [{"parameter": {"choice_str": "cat"}, "value": 1.1},
                    {"parameter": {"choice_str": "dog"}, "value": {"default": 1.2, "tmp": 2}},
                    {"parameter": {"choice_str": "cow"}, "value": 1.3}]
        else:
            data = [{"parameter": {"choice_num": 20}, "value": 1.1},
                    {"parameter": {"choice_num": 60}, "value": {"default": 1.2, "tmp": 2}},
                    {"parameter": {"choice_num": 50}, "value": 1.3}]
        tuner.import_data(data)
        logger.info("Imported data successfully in the middle")
        # generate parameters again
        parameters = tuner.generate_multiple_parameters([3])
        tuner.receive_trial_result(3, parameters[0], random.uniform(-100, 100))

313
    def test_grid_search(self):
314
        self.exhaustive = True
315
316
        tuner_fn = lambda: GridSearchTuner()
        self.search_space_test_all(tuner_fn,
317
                                   supported_types=["choice", "randint", "quniform"])
318
        self.import_data_test(tuner_fn)
319
320

    def test_tpe(self):
321
322
        tuner_fn = lambda: HyperoptTuner("tpe")
        self.search_space_test_all(tuner_fn,
323
324
                                   ignore_types=["uniform_equal", "qloguniform_equal", "loguniform_equal", "quniform_clip_2"])
        # NOTE: types are ignored because `tpe.py line 465, in adaptive_parzen_normal assert prior_sigma > 0`
325
        self.import_data_test(tuner_fn)
326
327

    def test_random_search(self):
328
329
330
        tuner_fn = lambda: HyperoptTuner("random_search")
        self.search_space_test_all(tuner_fn)
        self.import_data_test(tuner_fn)
331
332

    def test_anneal(self):
333
334
335
        tuner_fn = lambda: HyperoptTuner("anneal")
        self.search_space_test_all(tuner_fn)
        self.import_data_test(tuner_fn)
336
337
338
339

    def test_smac(self):
        if sys.platform == "win32":
            return  # smac doesn't work on windows
340
341
        tuner_fn = lambda: SMACTuner()
        self.search_space_test_all(tuner_fn,
342
                                   supported_types=["choice", "randint", "uniform", "quniform", "loguniform"])
343
        self.import_data_test(tuner_fn)
344
345

    def test_batch(self):
346
        self.exhaustive = True
347
348
        tuner_fn = lambda: BatchTuner()
        self.search_space_test_all(tuner_fn,
349
                                   supported_types=["choice"])
350
        self.import_data_test(tuner_fn)
351
352
353

    def test_evolution(self):
        # Needs enough population size, otherwise it will throw a runtime error
354
355
356
        tuner_fn = lambda: EvolutionTuner(population_size=100)
        self.search_space_test_all(tuner_fn)
        self.import_data_test(tuner_fn)
357
358

    def test_gp(self):
359
        self.test_round = 1  # NOTE: GP tuner got hanged for multiple testing round
360
361
        tuner_fn = lambda: GPTuner()
        self.search_space_test_all(tuner_fn,
362
363
                                   supported_types=["choice", "randint", "uniform", "quniform", "loguniform",
                                                    "qloguniform"],
364
365
                                   ignore_types=["normal", "lognormal", "qnormal", "qlognormal"],
                                   fail_types=["choice_str", "choice_mixed"])
366
        self.import_data_test(tuner_fn, "choice_num")
367
368

    def test_metis(self):
369
        self.test_round = 1  # NOTE: Metis tuner got hanged for multiple testing round
370
371
        tuner_fn = lambda: MetisTuner()
        self.search_space_test_all(tuner_fn,
372
373
                                   supported_types=["choice", "randint", "uniform", "quniform"],
                                   fail_types=["choice_str", "choice_mixed"])
374
        self.import_data_test(tuner_fn, "choice_num")
375
376
377
378
379
380
381

    def test_networkmorphism(self):
        pass

    def test_ppo(self):
        pass

RayMeng8's avatar
RayMeng8 committed
382
383
384
385
386
387
388
389
390
    def test_pbt(self):
        self.search_space_test_all(lambda: PBTTuner(
            all_checkpoint_dir=os.path.expanduser("~/nni/checkpoint/test/"),
            population_size=12
        ))
        self.search_space_test_all(lambda: PBTTuner(
            all_checkpoint_dir=os.path.expanduser("~/nni/checkpoint/test/"),
            population_size=100
        ))
QuanluZhang's avatar
QuanluZhang committed
391
        self.import_data_test_for_pbt()
RayMeng8's avatar
RayMeng8 committed
392

393
394
395
396
397
398
399
400
    def tearDown(self):
        file_list = glob.glob("smac3*") + ["param_config_space.pcs", "scenario.txt", "model_path"]
        for file in file_list:
            if os.path.exists(file):
                if os.path.isdir(file):
                    shutil.rmtree(file)
                else:
                    os.remove(file)
Deshui Yu's avatar
Deshui Yu committed
401

402
403
404
405
    def test_regularized_evolution_tuner(self):
        tuner_fn = lambda: RegularizedEvolutionTuner()
        self.nas_search_space_test_all(tuner_fn)

Deshui Yu's avatar
Deshui Yu committed
406
407
408

if __name__ == '__main__':
    main()