sa_controller.py 5.1 KB
Newer Older
W
wanghaoshuang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#   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"""

import copy
import math
import logging
import numpy as np
C
ceci3 已提交
20
import json
W
wanghaoshuang 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
from .controller import EvolutionaryController
from log_helper import get_logger

__all__ = ["SAController"]

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


class SAController(EvolutionaryController):
    """Simulated annealing controller."""

    def __init__(self,
                 range_table=None,
                 reduce_rate=0.85,
                 init_temperature=1024,
W
wanghaoshuang 已提交
36
                 max_try_times=None,
W
wanghaoshuang 已提交
37
                 init_tokens=None,
C
ceci3 已提交
38 39 40 41 42 43
                 reward=-1,
                 max_reward=-1,
                 iters=0,
                 best_tokens=None,
                 constrain_func=None,
                 checkpoints=None):
W
wanghaoshuang 已提交
44 45 46 47 48
        """Initialize.
        Args:
            range_table(list<int>): Range table.
            reduce_rate(float): The decay rate of temperature.
            init_temperature(float): Init temperature.
W
wanghaoshuang 已提交
49
            max_try_times(int): max try times before get legal tokens.
W
wanghaoshuang 已提交
50 51
            init_tokens(list<int>): The initial tokens.
            constrain_func(function): The callback function used to check whether the tokens meet constraint. None means there is no constraint. Default: None.
C
ceci3 已提交
52
            checkpoints(str): if checkpoint is None, donnot save checkpoints, else save scene to checkpoints file.
W
wanghaoshuang 已提交
53 54 55 56 57 58 59
        """
        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 已提交
60
        self._max_try_times = max_try_times
C
ceci3 已提交
61
        self._reward = reward
W
wanghaoshuang 已提交
62 63
        self._tokens = init_tokens
        self._constrain_func = constrain_func
C
ceci3 已提交
64 65 66 67
        self._max_reward = max_reward
        self._best_tokens = best_tokens
        self._iter = iters
        self._checkpoints = checkpoints
W
wanghaoshuang 已提交
68 69 70 71 72 73 74 75

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

W
wanghaoshuang 已提交
76
    def update(self, tokens, reward, iter):
W
wanghaoshuang 已提交
77 78 79 80 81 82
        """
        Update the controller according to latest tokens and reward.
        Args:
            tokens(list<int>): The tokens generated in last step.
            reward(float): The reward of tokens.
        """
W
wanghaoshuang 已提交
83
        iter = int(iter)
W
wanghaoshuang 已提交
84 85
        if iter > self._iter:
            self._iter = iter
W
wanghaoshuang 已提交
86
        temperature = self._init_temperature * self._reduce_rate**self._iter
W
wanghaoshuang 已提交
87 88 89 90 91 92 93 94
        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 已提交
95 96 97 98 99 100
            "Controller - iter: {}; best_reward: {}, best tokens: {}, current_reward: {}; current tokens: {}".
            format(self._iter, self._reward, self._tokens, reward, tokens))

        if self._checkpoints != None:
            self._save_checkpoint(self._checkpoints)

W
wanghaoshuang 已提交
101 102 103 104 105 106 107 108 109 110 111 112

    def next_tokens(self, control_token=None):
        """
        Get next tokens.
        """
        if control_token:
            tokens = control_token[:]
        else:
            tokens = self._tokens
        new_tokens = tokens[:]
        index = int(len(self._range_table[0]) * np.random.random())
        new_tokens[index] = np.random.randint(self._range_table[0][index],
C
ceci3 已提交
113
                                              self._range_table[1][index])
W
wanghaoshuang 已提交
114 115
        _logger.debug("change index[{}] from {} to {}".format(index, tokens[
            index], new_tokens[index]))
W
wanghaoshuang 已提交
116
        if self._constrain_func is None or self._max_try_times is None:
W
wanghaoshuang 已提交
117
            return new_tokens
W
wanghaoshuang 已提交
118
        for _ in range(self._max_try_times):
W
wanghaoshuang 已提交
119 120 121 122 123
            if not self._constrain_func(new_tokens):
                index = int(len(self._range_table[0]) * np.random.random())
                new_tokens = tokens[:]
                new_tokens[index] = np.random.randint(
                    self._range_table[0][index],
C
ceci3 已提交
124
                    self._range_table[1][index])
W
wanghaoshuang 已提交
125 126 127
            else:
                break
        return new_tokens
C
ceci3 已提交
128 129 130 131 132 133 134 135 136 137 138

    def _save_checkpoint(self, output_file):
        scene = dict()
        for key in self.__dict__():
            if key in ['_checkpoints']:
                continue
            scene[key] = self.__dict__[key]
        f = open(output_file, 'w')
        json.dump(scene)
        f.close()