sa_controller.py 7.1 KB
Newer Older
W
wanghaoshuang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The controller used to search hyperparameters or neural architecture"""

C
ceci3 已提交
16
import os
C
ceci3 已提交
17
import sys
W
wanghaoshuang 已提交
18 19 20 21
import copy
import math
import logging
import numpy as np
C
ceci3 已提交
22
import json
W
wanghaoshuang 已提交
23
from .controller import EvolutionaryController
C
ceci3 已提交
24
from .log_helper import get_logger
W
wanghaoshuang 已提交
25 26 27 28 29 30 31

__all__ = ["SAController"]

_logger = get_logger(__name__, level=logging.INFO)


class SAController(EvolutionaryController):
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    """Simulated annealing controller.

    Args:
        range_table(list<int>): Range table.
        reduce_rate(float): The decay rate of temperature.
        init_temperature(float): Init temperature.
        max_try_times(int): max try times before get legal tokens. Default: 300.
        init_tokens(list<int>): The initial tokens. Default: None.
        reward(float): The reward of current tokens. Default: -1.
        max_reward(float): The max reward in the search of sanas, in general, best tokens get max reward. Default: -1.
        iters(int): The iteration of sa controller. Default: 0.
        best_tokens(list<int>): The best tokens in the search of sanas, in general, best tokens get max reward. Default: None.
        constrain_func(function): The callback function used to check whether the tokens meet constraint. None means there is no constraint. Default: None.
        checkpoints(str): if checkpoint is None, donnot save checkpoints, else save scene to checkpoints file.
        searched(dict<list, float>): remember tokens which are searched.
        """
W
wanghaoshuang 已提交
48 49 50 51

    def __init__(self,
                 range_table=None,
                 reduce_rate=0.85,
52
                 init_temperature=None,
C
ceci3 已提交
53
                 max_try_times=300,
W
wanghaoshuang 已提交
54
                 init_tokens=None,
C
ceci3 已提交
55 56 57 58 59
                 reward=-1,
                 max_reward=-1,
                 iters=0,
                 best_tokens=None,
                 constrain_func=None,
C
ceci3 已提交
60 61
                 checkpoints=None,
                 searched=None):
W
wanghaoshuang 已提交
62 63 64 65 66 67
        super(SAController, self).__init__()
        self._range_table = range_table
        assert isinstance(self._range_table, tuple) and (
            len(self._range_table) == 2)
        self._reduce_rate = reduce_rate
        self._init_temperature = init_temperature
W
wanghaoshuang 已提交
68
        self._max_try_times = max_try_times
C
ceci3 已提交
69
        self._reward = reward
W
wanghaoshuang 已提交
70
        self._tokens = init_tokens
71 72 73 74 75 76 77

        if init_temperature == None:
            if init_tokens == None:
                self._init_temperature = 10.0
            else:
                self._init_temperature = 1.0

W
wanghaoshuang 已提交
78
        self._constrain_func = constrain_func
C
ceci3 已提交
79 80 81 82
        self._max_reward = max_reward
        self._best_tokens = best_tokens
        self._iter = iters
        self._checkpoints = checkpoints
C
ceci3 已提交
83
        self._searched = searched if searched != None else dict()
C
ceci3 已提交
84
        self._current_tokens = init_tokens
W
wanghaoshuang 已提交
85 86 87 88 89 90 91 92

    def __getstate__(self):
        d = {}
        for key in self.__dict__:
            if key != "_constrain_func":
                d[key] = self.__dict__[key]
        return d

C
ceci3 已提交
93 94
    @property
    def best_tokens(self):
95 96 97 98 99
        """Get current best tokens.

        Returns:
            list<int>: The best tokens.
        """
C
ceci3 已提交
100 101 102 103 104 105 106 107
        return self._best_tokens

    @property
    def max_reward(self):
        return self._max_reward

    @property
    def current_tokens(self):
108 109 110 111 112 113
        """Get tokens generated in current searching step.

        Returns:
            list<int>: The best tokens.
        """

114
        return self._current_tokens
C
ceci3 已提交
115

116
    def update(self, tokens, reward, iter, client_num):
W
wanghaoshuang 已提交
117 118
        """
        Update the controller according to latest tokens and reward.
119

W
wanghaoshuang 已提交
120
        Args:
121
            tokens(list<int>): The tokens generated in current step.
W
wanghaoshuang 已提交
122
            reward(float): The reward of tokens.
123 124
            iter(int): The current step of searching client.
            client_num(int): The total number of searching client. 
W
wanghaoshuang 已提交
125
        """
W
wanghaoshuang 已提交
126
        iter = int(iter)
W
wanghaoshuang 已提交
127 128
        if iter > self._iter:
            self._iter = iter
C
ceci3 已提交
129
        self._searched[str(tokens)] = reward
130 131
        temperature = self._init_temperature * self._reduce_rate**(client_num *
                                                                   self._iter)
W
wanghaoshuang 已提交
132 133 134 135 136 137 138 139
        if (reward > self._reward) or (np.random.random() <= math.exp(
            (reward - self._reward) / temperature)):
            self._reward = reward
            self._tokens = tokens
        if reward > self._max_reward:
            self._max_reward = reward
            self._best_tokens = tokens
        _logger.info(
C
ceci3 已提交
140
            "Controller - iter: {}; best_reward: {}, best tokens: {}, current_reward: {}; current tokens: {}".
C
ceci3 已提交
141 142
            format(self._iter, self._max_reward, self._best_tokens, reward,
                   tokens))
143 144 145
        _logger.debug(
            'Controller - iter: {}, controller current tokens: {}, controller current reward: {}'.
            format(self._iter, self._tokens, self._reward))
C
ceci3 已提交
146 147 148

        if self._checkpoints != None:
            self._save_checkpoint(self._checkpoints)
W
wanghaoshuang 已提交
149 150 151 152

    def next_tokens(self, control_token=None):
        """
        Get next tokens.
153 154 155 156 157 158

        Args:
            control_token: The tokens used to generate next tokens.

        Returns:
            list<int>: The next tokens.
W
wanghaoshuang 已提交
159 160 161 162 163
        """
        if control_token:
            tokens = control_token[:]
        else:
            tokens = self._tokens
C
ceci3 已提交
164 165 166 167 168 169 170 171
        for it in range(self._max_try_times):
            new_tokens = tokens[:]
            index = int(len(self._range_table[0]) * np.random.random())
            new_tokens[index] = np.random.randint(self._range_table[0][index],
                                                  self._range_table[1][index])
            _logger.debug("change index[{}] from {} to {}".format(
                index, tokens[index], new_tokens[index]))

C
ceci3 已提交
172
            if str(new_tokens) in self._searched.keys():
C
ceci3 已提交
173 174 175
                _logger.debug('get next tokens including searched tokens: {}'.
                              format(new_tokens))
                continue
W
wanghaoshuang 已提交
176
            else:
C
ceci3 已提交
177
                self._searched[str(new_tokens)] = -1
W
wanghaoshuang 已提交
178
                break
C
ceci3 已提交
179 180 181 182 183 184 185

        if it == self._max_try_times - 1:
            _logger.info(
                "cannot get a effective search space which is not searched in max try times!!!"
            )
            sys.exit()

C
ceci3 已提交
186
        self._current_tokens = new_tokens
C
ceci3 已提交
187

W
wanghaoshuang 已提交
188
        return new_tokens
C
ceci3 已提交
189

C
fix bug  
ceci3 已提交
190
    def _save_checkpoint(self, output_dir):
C
ceci3 已提交
191 192 193
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
        file_path = os.path.join(output_dir, 'sanas.checkpoints')
C
ceci3 已提交
194
        scene = dict()
C
fix bug  
ceci3 已提交
195
        for key in self.__dict__:
C
ceci3 已提交
196 197 198
            if key in ['_checkpoints']:
                continue
            scene[key] = self.__dict__[key]
C
fix bug  
ceci3 已提交
199 200
        with open(file_path, 'w') as f:
            json.dump(scene, f)