tuner.py 9.94 KB
Newer Older
Deshui Yu's avatar
Deshui Yu committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish, distribute,
# sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
# OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# ==================================================================================================
20
21
22
23
24
25
26
27

"""
Tuner is an AutoML algorithm, which generates a new configuration for the next try.
A new trial will run with this configuration.

See :class:`Tuner`' specification and ``docs/en_US/tuners.rst`` for details.
"""

Deshui Yu's avatar
Deshui Yu committed
28
29
import logging

xuehui's avatar
xuehui committed
30
import nni
31

32
from .recoverable import Recoverable
Deshui Yu's avatar
Deshui Yu committed
33

34
35
__all__ = ['Tuner']

Deshui Yu's avatar
Deshui Yu committed
36
37
38
_logger = logging.getLogger(__name__)


39
class Tuner(Recoverable):
40
41
42
43
44
    """
    Tuner is an AutoML algorithm, which generates a new configuration for the next try.
    A new trial will run with this configuration.

    This is the abstract base class for all tuners.
liuzhe-lz's avatar
liuzhe-lz committed
45
    Tuning algorithms should inherit this class and override :meth:`update_search_space`, :meth:`receive_trial_result`,
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    as well as :meth:`generate_parameters` or :meth:`generate_multiple_parameters`.

    After initializing, NNI will first call :meth:`update_search_space` to tell tuner the feasible region,
    and then call :meth:`generate_parameters` one or more times to request for hyper-parameter configurations.

    The framework will train several models with given configuration.
    When one of them is finished, the final accuracy will be reported to :meth:`receive_trial_result`.
    And then another configuration will be reqeusted and trained, util the whole experiment finish.

    If a tuner want's to know when a trial ends, it can also override :meth:`trial_end`.

    Tuners use *parameter ID* to track trials.
    In tuner context, there is a one-to-one mapping between parameter ID and trial.
    When the framework ask tuner to generate hyper-parameters for a new trial,
    an ID has already been assigned and can be recorded in :meth:`generate_parameters`.
    Later when the trial ends, the ID will be reported to :meth:`trial_end`,
    and :meth:`receive_trial_result` if it has a final result.
    Parameter IDs are unique integers.

    The type/format of search space and hyper-parameters are not limited,
    as long as they are JSON-serializable and in sync with trial code.
    For HPO tuners, however, there is a widely shared common interface,
    which supports ``choice``, ``randint``, ``uniform``, and so on.
    See ``docs/en_US/Tutorial/SearchSpaceSpec.md`` for details of this interface.

    [WIP] For advanced tuners which take advantage of trials' intermediate results,
    an ``Advisor`` interface is under development.

    See Also
    --------
    Builtin tuners:
    :class:`~nni.hyperopt_tuner.hyperopt_tuner.HyperoptTuner`
    :class:`~nni.evolution_tuner.evolution_tuner.EvolutionTuner`
    :class:`~nni.smac_tuner.smac_tuner.SMACTuner`
    :class:`~nni.gridsearch_tuner.gridsearch_tuner.GridSearchTuner`
    :class:`~nni.networkmorphism_tuner.networkmorphism_tuner.NetworkMorphismTuner`
82
83
    :class:`~nni.metis_tuner.metis_tuner.MetisTuner`
    :class:`~nni.gp_tuner.gp_tuner.GPTuner`
84
    """
Deshui Yu's avatar
Deshui Yu committed
85

86
    def generate_parameters(self, parameter_id, **kwargs):
87
88
89
90
91
92
93
94
95
96
97
98
99
        """
        Abstract method which provides a set of hyper-parameters.

        This method will get called when the framework is about to launch a new trial,
        if user does not override :meth:`generate_multiple_parameters`.

        The return value of this method will be received by trials via :func:`nni.get_next_parameter`.
        It should fit in the search space, though the framework will not verify this.

        User code must override either this method or :meth:`generate_multiple_parameters`.

        Parameters
        ----------
liuzhe-lz's avatar
liuzhe-lz committed
100
        parameter_id : int
101
            Unique identifier for requested hyper-parameters. This will later be used in :meth:`receive_trial_result`.
liuzhe-lz's avatar
liuzhe-lz committed
102
        **kwargs
103
104
105
106
107
108
109
110
111
112
113
            Unstable parameters which should be ignored by normal users.

        Returns
        -------
        any
            The hyper-parameters, a dict in most cases, but could be any JSON-serializable type when needed.

        Raises
        ------
        nni.NoMoreTrialError
            If the search space is fully explored, tuner can raise this exception.
Deshui Yu's avatar
Deshui Yu committed
114
        """
115
116
        # FIXME: some tuners raise NoMoreTrialError when they are waiting for more trial results
        # we need to design a new exception for this purpose
Deshui Yu's avatar
Deshui Yu committed
117
118
        raise NotImplementedError('Tuner: generate_parameters not implemented')

119
    def generate_multiple_parameters(self, parameter_id_list, **kwargs):
120
121
122
123
124
125
126
127
128
129
130
131
132
        """
        Callback method which provides multiple sets of hyper-parameters.

        This method will get called when the framework is about to launch one or more new trials.

        If user does not override this method, it will invoke :meth:`generate_parameters` on each parameter ID.

        See :meth:`generate_parameters` for details.

        User code must override either this method or :meth:`generate_parameters`.

        Parameters
        ----------
liuzhe-lz's avatar
liuzhe-lz committed
133
        parameter_id_list : list of int
134
135
            Unique identifiers for each set of requested hyper-parameters.
            These will later be used in :meth:`receive_trial_result`.
liuzhe-lz's avatar
liuzhe-lz committed
136
        **kwargs
137
138
139
140
141
142
            Unstable parameters which should be ignored by normal users.

        Returns
        -------
        list
            List of hyper-parameters. An empty list indicates there are no more trials.
Deshui Yu's avatar
Deshui Yu committed
143
        """
xuehui's avatar
xuehui committed
144
145
        result = []
        for parameter_id in parameter_id_list:
xuehui's avatar
xuehui committed
146
            try:
liuzhe-lz's avatar
liuzhe-lz committed
147
                _logger.debug("generating param for %s", parameter_id)
148
                res = self.generate_parameters(parameter_id, **kwargs)
xuehui's avatar
xuehui committed
149
150
151
            except nni.NoMoreTrialError:
                return result
            result.append(res)
xuehui's avatar
xuehui committed
152
        return result
Deshui Yu's avatar
Deshui Yu committed
153

154
    def receive_trial_result(self, parameter_id, parameters, value, **kwargs):
155
156
157
158
159
160
161
162
        """
        Abstract method invoked when a trial reports its final result. Must override.

        This method only listens to results of algorithm-generated hyper-parameters.
        Currently customized trials added from web UI will not report result to this method.

        Parameters
        ----------
liuzhe-lz's avatar
liuzhe-lz committed
163
        parameter_id : int
164
165
166
167
168
            Unique identifier of used hyper-parameters, same with :meth:`generate_parameters`.
        parameters
            Hyper-parameters generated by :meth:`generate_parameters`.
        value
            Result from trial (the return value of :func:`nni.report_final_result`).
liuzhe-lz's avatar
liuzhe-lz committed
169
        **kwargs
170
            Unstable parameters which should be ignored by normal users.
Deshui Yu's avatar
Deshui Yu committed
171
172
173
        """
        raise NotImplementedError('Tuner: receive_trial_result not implemented')

174
175
176
177
178
179
180
    def _accept_customized_trials(self, accept=True):
        # FIXME: because Tuner is designed as interface, this API should not be here

        # Enable or disable receiving results of user-added hyper-parameters.
        # By default `receive_trial_result()` will only receive results of algorithm-generated hyper-parameters.
        # If tuners want to receive those of customized parameters as well, they can call this function in `__init__()`.

liuzhe-lz's avatar
liuzhe-lz committed
181
        # pylint: disable=attribute-defined-outside-init
182
        self._accept_customized = accept
Deshui Yu's avatar
Deshui Yu committed
183

184
    def trial_end(self, parameter_id, success, **kwargs):
185
186
187
188
189
        """
        Abstract method invoked when a trial is completed or terminated. Do nothing by default.

        Parameters
        ----------
liuzhe-lz's avatar
liuzhe-lz committed
190
        parameter_id : int
191
            Unique identifier for hyper-parameters used by this trial.
liuzhe-lz's avatar
liuzhe-lz committed
192
        success : bool
193
            True if the trial successfully completed; False if failed or terminated.
liuzhe-lz's avatar
liuzhe-lz committed
194
        **kwargs
195
            Unstable parameters which should be ignored by normal users.
196
197
        """

Deshui Yu's avatar
Deshui Yu committed
198
    def update_search_space(self, search_space):
199
200
201
202
203
204
205
206
207
208
209
        """
        Abstract method for updating the search space. Must override.

        Tuners are advised to support updating search space at run-time.
        If a tuner can only set search space once before generating first hyper-parameters,
        it should explicitly document this behaviour.

        Parameters
        ----------
        search_space
            JSON object defined by experiment owner.
Deshui Yu's avatar
Deshui Yu committed
210
211
212
        """
        raise NotImplementedError('Tuner: update_search_space not implemented')

213
    def load_checkpoint(self):
214
215
        """
        Internal API under revising, not recommended for end users.
Deshui Yu's avatar
Deshui Yu committed
216
        """
217
        checkpoin_path = self.get_checkpoint_path()
liuzhe-lz's avatar
liuzhe-lz committed
218
        _logger.info('Load checkpoint ignored by tuner, checkpoint path: %s', checkpoin_path)
Deshui Yu's avatar
Deshui Yu committed
219

220
    def save_checkpoint(self):
221
222
        """
        Internal API under revising, not recommended for end users.
Deshui Yu's avatar
Deshui Yu committed
223
        """
224
        checkpoin_path = self.get_checkpoint_path()
liuzhe-lz's avatar
liuzhe-lz committed
225
        _logger.info('Save checkpoint ignored by tuner, checkpoint path: %s', checkpoin_path)
Deshui Yu's avatar
Deshui Yu committed
226

227
228
    def import_data(self, data):
        """
229
230
231
232
233
        Internal API under revising, not recommended for end users.
        """
        # Import additional data for tuning
        # data: a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'
        pass
234

235
236
    def _on_exit(self):
        pass
Deshui Yu's avatar
Deshui Yu committed
237

238
239
    def _on_error(self):
        pass