autoft.py 13.3 KB
Newer Older
K
kinghuin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# coding:utf-8
# Copyright (c) 2019  PaddlePaddle Authors. All Rights Reserved.
#
# 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.
from multiprocessing.pool import ThreadPool
S
Steffy-zxf 已提交
16
import cma
K
kinghuin 已提交
17 18 19 20 21 22 23
import copy
import json
import math
import numpy as np
import six
import time

S
Steffy-zxf 已提交
24
from tb_paddle import SummaryWriter
K
kinghuin 已提交
25 26
from paddlehub.common.logger import logger
from paddlehub.common.utils import mkdir
S
Steffy-zxf 已提交
27
from paddlehub.autofinetune.evaluator import REWARD_SUM
K
kinghuin 已提交
28 29 30 31 32 33 34

if six.PY3:
    INF = math.inf
else:
    INF = float("inf")


S
Steffy-zxf 已提交
35
class BaseTuningStrategy(object):
K
kinghuin 已提交
36 37 38 39 40 41 42 43 44 45 46 47
    def __init__(
            self,
            evaluator,
            cudas=["0"],
            popsize=5,
            output_dir=None,
    ):
        self._num_thread = len(cudas)
        self._popsize = popsize
        self.cudas = cudas
        self.is_cuda_free = {"free": [], "busy": []}
        self.is_cuda_free["free"] = cudas
S
Steffy-zxf 已提交
48
        self._round = 0
K
kinghuin 已提交
49 50 51

        self.evaluator = evaluator
        self.init_input = evaluator.get_init_params()
S
Steffy-zxf 已提交
52 53
        self.num_hparam = len(self.init_input)
        self.best_hparams_all_pop = []
K
kinghuin 已提交
54
        self.best_reward_all_pop = INF
S
Steffy-zxf 已提交
55 56 57 58
        self.current_hparams = [[0] * self.num_hparam] * self._popsize
        self.hparams_name_list = [
            param["name"] for param in evaluator.params['param_list']
        ]
K
kinghuin 已提交
59 60 61 62 63 64 65

        if output_dir is None:
            now = int(time.time())
            time_str = time.strftime("%Y%m%d%H%M%S", time.localtime(now))
            self._output_dir = "output_" + time_str
        else:
            self._output_dir = output_dir
S
Steffy-zxf 已提交
66
        self.writer = SummaryWriter(logdir=self._output_dir + '/tb_paddle')
K
kinghuin 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

    @property
    def thread(self):
        return self._num_thread

    @property
    def popsize(self):
        return self._popsize

    @property
    def output_dir(self):
        return self._output_dir

    @property
    def iteration(self):
        return self._iteration

S
Steffy-zxf 已提交
84 85 86 87
    @property
    def round(self):
        return self._round

K
kinghuin 已提交
88 89 90 91 92 93 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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    def set_output_dir(self, output_dir=None):
        if output_dir is not None:
            output_dir = output_dir
        else:
            output_dir = self._output_dir
        return output_dir

    def randomSolution(self):
        solut = [0] * self.num_hparm
        for i in range(self.num_hparm):
            ratio = (np.random.random_sample() - 0.5) * 2.0
            if ratio >= 0:
                solut[i] = (
                    1.0 - self.init_input[i]) * ratio + self.init_input[i]
            else:
                solut[i] = (
                    self.init_input[i] + 1.0) * ratio + self.init_input[i]
        return solut

    def smallPeturb(self):
        for i in range(self.popsize):
            for j in range(self.num_hparm):
                ratio = (np.random.random_sample() - 0.5) * 2.0
                if ratio >= 0:
                    self.current_hparams[i][j] = (
                        1.0 - self.current_hparams[i][j]
                    ) * ratio * self.epsilon + self.current_hparams[i][j]
                else:
                    self.current_hparams[i][j] = (
                        self.current_hparams[i][j] +
                        1.0) * ratio * self.epsilon + self.current_hparams[i][j]

    def estimatePopGradients(self):
        gradients = [[0] * self.num_hparm] * self.popsize
        for i in range(self.popsize):
            for j in range(self.num_hparm):
                gradients[i][j] = self.current_hparams[i][
                    j] - self.best_hparms_all_pop[j]
        return gradients

    def estimateLocalGradients(self):
        gradients = [[0] * self.num_hparm] * self.popsize
        for i in range(self.popsize):
            for j in range(self.num_hparm):
                gradients[i][j] = self.current_hparams[i][
                    j] - self.best_hparams_per_pop[i][j]
        return gradients

    def estimateMomemtum(self):
        popGrads = self.estimatePopGradients()
        localGrads = self.estimateLocalGradients()
        for i in range(self.popsize):
            for j in range(self.num_hparm):
                self.momentums[i][j] = (
                    1 - 3.0 * self.alpha / self.iteration
                ) * self.momentums[i][j] - self.alpha * localGrads[i][
                    j] - self.alpha * popGrads[i][j]

    def is_stop(self):
        return False

S
Steffy-zxf 已提交
149
    def get_current_hparams(self):
K
kinghuin 已提交
150 151 152
        return self.current_hparams

    def feedback(self, params_list, reward_list):
S
Steffy-zxf 已提交
153 154 155 156
        return NotImplementedError

    def get_best_hparams(self):
        return self.best_hparams_all_pop
K
kinghuin 已提交
157

S
Steffy-zxf 已提交
158 159
    def get_best_eval_value(self):
        return REWARD_SUM - self.best_reward_all_pop
K
kinghuin 已提交
160 161

    def step(self, output_dir):
S
Steffy-zxf 已提交
162
        solutions = self.get_current_hparams()
K
kinghuin 已提交
163 164 165 166 167 168

        params_cudas_dirs = []
        solution_results = []
        cnt = 0
        solutions_ckptdirs = {}
        mkdir(output_dir)
Z
zhangxuefei 已提交
169

K
kinghuin 已提交
170 171 172 173 174 175 176 177
        for idx, solution in enumerate(solutions):
            cuda = self.is_cuda_free["free"][0]
            ckptdir = output_dir + "/ckpt-" + str(idx)
            log_file = output_dir + "/log-" + str(idx) + ".info"
            params_cudas_dirs.append([solution, cuda, ckptdir, log_file])
            solutions_ckptdirs[tuple(solution)] = ckptdir
            self.is_cuda_free["free"].remove(cuda)
            self.is_cuda_free["busy"].append(cuda)
Z
zhangxuefei 已提交
178 179
            if len(params_cudas_dirs
                   ) == self.thread or idx == len(solutions) - 1:
K
kinghuin 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193
                tp = ThreadPool(len(params_cudas_dirs))
                solution_results += tp.map(self.evaluator.run,
                                           params_cudas_dirs)
                cnt += 1
                tp.close()
                tp.join()
                for param_cuda in params_cudas_dirs:
                    self.is_cuda_free["free"].append(param_cuda[1])
                    self.is_cuda_free["busy"].remove(param_cuda[1])
                params_cudas_dirs = []

        self.feedback(solutions, solution_results)

        return solutions_ckptdirs
S
Steffy-zxf 已提交
194 195 196 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


class HAZero(BaseTuningStrategy):
    def __init__(
            self,
            evaluator,
            cudas=["0"],
            popsize=1,
            output_dir=None,
            sigma=0.2,
    ):
        super(HAZero, self).__init__(evaluator, cudas, popsize, output_dir)

        self._sigma = sigma

        self.evolution_stratefy = cma.CMAEvolutionStrategy(
            self.init_input, sigma, {
                'popsize': self.popsize,
                'bounds': [-1, 1],
                'AdaptSigma': True,
                'verb_disp': 1,
                'verb_time': 'True',
            })

    @property
    def sigma(self):
        return self._sigma

    def get_current_hparams(self):
        return self.evolution_stratefy.ask()

    def is_stop(self):
        return self.evolution_stratefy.stop()

    def feedback(self, params_list, reward_list):
        self._round = self._round + 1

        local_min_reward = min(reward_list)
        local_min_reward_index = reward_list.index(local_min_reward)
        local_hparams = self.evaluator.convert_params(
            params_list[local_min_reward_index])
        print("The local best eval value in the %s-th round is %s." %
              (self._round - 1, REWARD_SUM - local_min_reward))
        print("The local best hyperparameters are as:")
        for index, hparam_name in enumerate(self.hparams_name_list):
            print("%s=%s" % (hparam_name, local_hparams[index]))

        for i in range(self.popsize):
            if reward_list[i] < self.best_reward_all_pop:
                self.best_hparams_all_pop = self.current_hparams[i]
                self.best_reward_all_pop = reward_list[i]

        best_hparams = self.evaluator.convert_params(self.best_hparams_all_pop)
        for index, name in enumerate(self.hparams_name_list):
            self.writer.add_scalar(
Z
zhangxuefei 已提交
249
                tag="hyperparameter_tuning/" + name,
S
Steffy-zxf 已提交
250 251 252
                scalar_value=best_hparams[index],
                global_step=self.round)
        self.writer.add_scalar(
Z
zhangxuefei 已提交
253
            tag="hyperparameter_tuning/best_eval_value",
S
Steffy-zxf 已提交
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 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
            scalar_value=self.get_best_eval_value(),
            global_step=self.round)

        self.evolution_stratefy.tell(params_list, reward_list)
        self.evolution_stratefy.disp()

    def get_best_hparams(self):
        return list(self.evolution_stratefy.result.xbest)


class PSHE2(BaseTuningStrategy):
    def __init__(
            self,
            evaluator,
            cudas=["0"],
            popsize=1,
            output_dir=None,
            alpha=0.5,
            epsilon=0.2,
    ):
        super(PSHE2, self).__init__(evaluator, cudas, popsize, output_dir)

        self._alpha = alpha
        self._epsilon = epsilon

        self.best_hparams_per_pop = [[0] * self.num_hparam] * self._popsize
        self.best_reward_per_pop = [INF] * self._popsize
        self.momentums = [[0] * self.num_hparam] * self._popsize
        for i in range(self.popsize):
            self.current_hparams[i] = self.set_random_hparam()

    @property
    def alpha(self):
        return self._alpha

    @property
    def epsilon(self):
        return self._epsilon

    def set_random_hparam(self):
        solut = [0] * self.num_hparam
        for i in range(self.num_hparam):
            ratio = (np.random.random_sample() - 0.5) * 2.0
            if ratio >= 0:
                solut[i] = (
                    1.0 - self.init_input[i]) * ratio + self.init_input[i]
            else:
                solut[i] = (
                    self.init_input[i] + 1.0) * ratio + self.init_input[i]
        return solut

    def small_peturb(self):
        for i in range(self.popsize):
            for j in range(self.num_hparam):
                ratio = (np.random.random_sample() - 0.5) * 2.0
                if ratio >= 0:
                    self.current_hparams[i][j] = (
                        1.0 - self.current_hparams[i][j]
                    ) * ratio * self.epsilon + self.current_hparams[i][j]
                else:
                    self.current_hparams[i][j] = (
                        self.current_hparams[i][j] +
                        1.0) * ratio * self.epsilon + self.current_hparams[i][j]

    def estimate_popgradients(self):
        gradients = [[0] * self.num_hparam] * self.popsize
        for i in range(self.popsize):
            for j in range(self.num_hparam):
                gradients[i][j] = self.current_hparams[i][
                    j] - self.best_hparams_all_pop[j]
        return gradients

    def estimate_local_gradients(self):
        gradients = [[0] * self.num_hparam] * self.popsize
        for i in range(self.popsize):
            for j in range(self.num_hparam):
                gradients[i][j] = self.current_hparams[i][
                    j] - self.best_hparams_per_pop[i][j]
        return gradients

    def estimate_momemtum(self):
        popGrads = self.estimate_popgradients()
        localGrads = self.estimate_local_gradients()
        for i in range(self.popsize):
            for j in range(self.num_hparam):
                self.momentums[i][j] = (
                    1 - 3.0 * self.alpha / self.round
                ) * self.momentums[i][j] - self.alpha * localGrads[i][
                    j] - self.alpha * popGrads[i][j]

    def is_stop(self):
        return False

    def feedback(self, params_list, reward_list):
        self._round = self._round + 1

        local_min_reward = min(reward_list)
        local_min_reward_index = reward_list.index(local_min_reward)
        local_hparams = self.evaluator.convert_params(
            params_list[local_min_reward_index])
        print("The local best eval value in the %s-th round is %s." %
              (self._round - 1, REWARD_SUM - local_min_reward))
        print("The local best hyperparameters are as:")
        for index, hparam_name in enumerate(self.hparams_name_list):
            print("%s=%s" % (hparam_name, local_hparams[index]))

        for i in range(self.popsize):
            if reward_list[i] < self.best_reward_per_pop[i]:
                self.best_hparams_per_pop[i] = copy.deepcopy(
                    self.current_hparams[i])
                self.best_reward_per_pop[i] = reward_list[i]
            if reward_list[i] < self.best_reward_all_pop:
                self.best_hparams_all_pop = self.current_hparams[i]
                self.best_reward_all_pop = reward_list[i]

        best_hparams = self.evaluator.convert_params(self.best_hparams_all_pop)
        for index, name in enumerate(self.hparams_name_list):
            self.writer.add_scalar(
Z
zhangxuefei 已提交
372
                tag="hyperparameter_tuning/" + name,
S
Steffy-zxf 已提交
373 374 375
                scalar_value=best_hparams[index],
                global_step=self.round)
        self.writer.add_scalar(
Z
zhangxuefei 已提交
376
            tag="hyperparameter_tuning/best_eval_value",
S
Steffy-zxf 已提交
377 378 379 380 381 382 383 384 385
            scalar_value=self.get_best_eval_value(),
            global_step=self.round)

        self.estimate_momemtum()
        for i in range(self.popsize):
            for j in range(len(self.init_input)):
                self.current_hparams[i][j] = self.current_hparams[i][
                    j] + self.alpha * self.momentums[i][j]
        self.small_peturb()