第19章ハイパーパラメータ最適化
19.4.1. Successive Halving19.4.1 逐次半減法
One of the simplest ways to adapt random search to the multi-fidelity setting is successive halving (Jamieson and Talwalkar, 2016, Karnin et al., 2013). The basic idea is to start with configurations, for example randomly sampled from the configuration space, and to train each of them for epochs only. We then discard a fraction of the worst performing trials and train the remaining ones for longer. Iterating this process, fewer trials run for longer, until at least one trial reaches epochs.
英語のヒント
ランダム探索をマルチフィデリティの設定に適応させる最も簡単な方法の一つは、逐次半減法である(Jamieson and Talwalkar, 2016、Karnin et al., 2013)。基本的な考え方は、たとえば設定空間からランダムに抜き出した個の設定から始め、それぞれをエポックだけ訓練することである。それから、最も性能の悪い試行の一部を捨て、残りをもっと長く訓練する。この過程を繰り返すと、少なくとも一つの試行がエポックに達するまで、より少ない試行がより長く実行される。
More formally, consider a minimum budget (for example 1 epoch), a maximum budget , for example
max_epochs in our previous example, and a halving constant . For simplicity, assume that , with . The number of initial configurations is then . Let us define the set of rungs .英語のヒント
もっと形式的には、最小の予算(たとえば1エポック)、最大の予算(たとえば前の例の
max_epochs)、半減定数を考える。簡単にするため、としてと仮定する。すると、最初の設定の数はである。段の集合をと定義しよう。One round of successive halving proceeds as follows. We start with running trials until the first rung . Sorting the validation errors, we keep the top fraction (which amounts to configurations) and discard all the rest. The surviving trials are trained for the next rung ( epochs), and the process is repeated. At each rung, a fraction of trials survives and their training continues with a times larger budget. With this particular choice of , only a single trial will be trained to the full budget . Once such a round of successive halving is done, we start the next one with a new set of initial configurations, iterating until the total budget is spent.
英語のヒント
逐次半減法の1ラウンドは次のように進む。まず、最初の段まで個の試行を実行する。検証誤差を並べ替え、上位のの割合(個の設定に当たる)を残し、残りはすべて捨てる。生き残った試行は次の段(エポック)まで訓練され、この過程が繰り返される。各段で、試行のの割合が生き残り、その訓練は倍大きな予算で続く。をこのように選ぶと、一つの試行だけが予算いっぱいのまで訓練される。逐次半減法のそうした1ラウンドが終わったら、新しい最初の設定の集合で次のラウンドを始め、総予算を使い切るまで繰り返す。
Fig. 19.4.2図19.4.2
Learning curves of random hyperparameter configurations.
英語のヒント
ランダムなハイパーパラメータの設定の学習曲線。
We subclass the
HPOScheduler base class from Section 19.2 in order to implement successive halving, allowing for a generic HPOSearcher object to sample configurations (which, in our example below, will be a RandomSearcher). Additionally, the user has to pass the minimum resource , the maximum resource and as input. Inside our scheduler, we maintain a queue of configurations that still need to be evaluated for the current rung . We update the queue every time we jump to the next rung.英語のヒント
逐次半減法を実装するため、19.2節の基底クラス
HPOSchedulerのサブクラスを作り、設定を抜き出すのに汎用のHPOSearcherオブジェクト(下の例ではRandomSearcher)を使えるようにする。さらに、利用者は最小の資源、最大の資源、を入力として渡さなければならない。スケジューラの中では、現在の段でまだ評価する必要がある設定の待ち行列を保持する。次の段に移るたびに、待ち行列を更新する。class SuccessiveHalvingScheduler(d2l.HPOScheduler): #@save
def __init__(self, searcher, eta, r_min, r_max, prefact=1):
self.save_hyperparameters()
# Compute K, which is later used to determine the number of configurations
self.K = int(np.log(r_max / r_min) / np.log(eta))
# Define the rungs
self.rung_levels = [r_min * eta ** k for k in range(self.K + 1)]
if r_max not in self.rung_levels:
# The final rung should be r_max
self.rung_levels.append(r_max)
self.K += 1
# Bookkeeping
self.observed_error_at_rungs = defaultdict(list)
self.all_observed_error_at_rungs = defaultdict(list)
# Our processing queue
self.queue = []In the beginning our queue is empty, and we fill it with configurations, which are first evaluated on the smallest rung . Here, allows us to reuse our code in a different context. For the purpose of this section, we fix . Every time resources become available and the
HPOTuner object queries the suggest function, we return an element from the queue. Once we finish one round of successive halving, which means that we evaluated all surviving configurations on the highest resource level and our queue is empty, we start the entire process again with a new, randomly sampled set of configurations.英語のヒント
最初は待ち行列は空で、そこを個の設定で満たす。これらはまず最小の段で評価される。ここで、を使えば、別の文脈でコードを再利用できる。この節の目的のためには、に固定する。資源が使えるようになり、
HPOTunerオブジェクトがsuggest関数に問い合わせるたびに、待ち行列から要素を一つ返す。逐次半減法の1ラウンドが終わったら、つまり生き残ったすべての設定を最も高い資源の水準で評価し、待ち行列が空になったら、新しくランダムに抜き出した設定の集合で、過程全体を再び始める。@d2l.add_to_class(SuccessiveHalvingScheduler) #@save
def suggest(self):
if len(self.queue) == 0:
# Start a new round of successive halving
# Number of configurations for the first rung:
n0 = int(self.prefact * self.eta ** self.K)
for _ in range(n0):
config = self.searcher.sample_configuration()
config["max_epochs"] = self.r_min # Set r = r_min
self.queue.append(config)
# Return an element from the queue
return self.queue.pop()When we collected a new data point, we first update the searcher module. Afterwards we check if we already collect all data points on the current rung. If so, we sort all configurations and push the top configurations into the queue.
英語のヒント
新しいデータ点を集めたら、まずサーチャーのモジュールを更新する。その後、現在の段ですべてのデータ点をすでに集めたかどうかを確かめる。そうであれば、すべての設定を並べ替え、上位の設定を待ち行列に入れる。
@d2l.add_to_class(SuccessiveHalvingScheduler) #@save
def update(self, config: dict, error: float, info=None):
ri = int(config["max_epochs"]) # Rung r_i
# Update our searcher, e.g if we use Bayesian optimization later
self.searcher.update(config, error, additional_info=info)
self.all_observed_error_at_rungs[ri].append((config, error))
if ri < self.r_max:
# Bookkeeping
self.observed_error_at_rungs[ri].append((config, error))
# Determine how many configurations should be evaluated on this rung
ki = self.K - self.rung_levels.index(ri)
ni = int(self.prefact * self.eta ** ki)
# If we observed all configuration on this rung r_i, we estimate the
# top 1 / eta configuration, add them to queue and promote them for
# the next rung r_{i+1}
if len(self.observed_error_at_rungs[ri]) >= ni:
kiplus1 = ki - 1
niplus1 = int(self.prefact * self.eta ** kiplus1)
best_performing_configurations = self.get_top_n_configurations(
rung_level=ri, n=niplus1
)
riplus1 = self.rung_levels[self.K - kiplus1] # r_{i+1}
# Queue may not be empty: insert new entries at the beginning
self.queue = [
dict(config, max_epochs=riplus1)
for config in best_performing_configurations
] + self.queue
self.observed_error_at_rungs[ri] = [] # ResetConfigurations are sorted based on their observed performance on the current rung.
英語のヒント
設定は、現在の段で観測された性能にもとづいて並べ替えられる。
@d2l.add_to_class(SuccessiveHalvingScheduler) #@save
def get_top_n_configurations(self, rung_level, n):
rung = self.observed_error_at_rungs[rung_level]
if not rung:
return []
sorted_rung = sorted(rung, key=lambda x: x[1])
return [x[0] for x in sorted_rung[:n]]Let us see how successive halving is doing on our neural network example. We will use , , , so that rung levels are .
英語のヒント
ニューラルネットワークの例で、逐次半減法がどうふるまうかを見てみよう。、、を使うので、段の水準はになる。
min_number_of_epochs = 2
max_number_of_epochs = 10
eta = 2
num_gpus=1
config_space = {
"learning_rate": stats.loguniform(1e-2, 1),
"batch_size": stats.randint(32, 256),
}
initial_config = {
"learning_rate": 0.1,
"batch_size": 128,
}We just replace the scheduler with our new
SuccessiveHalvingScheduler.英語のヒント
スケジューラを新しい
SuccessiveHalvingSchedulerに置き換えるだけでよい。searcher = d2l.RandomSearcher(config_space, initial_config=initial_config)
scheduler = SuccessiveHalvingScheduler(
searcher=searcher,
eta=eta,
r_min=min_number_of_epochs,
r_max=max_number_of_epochs,
)
tuner = d2l.HPOTuner(
scheduler=scheduler,
objective=d2l.hpo_objective_lenet,
)
tuner.run(number_of_trials=30) error = 0.17762434482574463, runtime = 53.576584339141846We can visualize the learning curves of all configurations that we evaluated. Most of the configurations are stopped early and only the better performing configurations survive until . Compare this to vanilla random search, which would allocate to every configuration.
英語のヒント
評価したすべての設定の学習曲線を可視化できる。設定のほとんどは早めに止められ、性能のよりよい設定だけがまで生き残る。これを、すべての設定にを割り当てる素のランダム探索と比べよう。
for rung_index, rung in scheduler.all_observed_error_at_rungs.items():
errors = [xi[1] for xi in rung]
d2l.plt.scatter([rung_index] * len(errors), errors)
d2l.plt.xlim(min_number_of_epochs - 0.5, max_number_of_epochs + 0.5)
d2l.plt.xticks(
np.arange(min_number_of_epochs, max_number_of_epochs + 1),
np.arange(min_number_of_epochs, max_number_of_epochs + 1)
)
d2l.plt.ylabel("validation error")
d2l.plt.xlabel("epochs")Text(0.5, 0, 'epochs')Finally, note some slight complexity in our implementation of
SuccessiveHalvingScheduler. Say that a worker is free to run a job, and suggest is called when the current rung has almost been completely filled, but another worker is still busy with an evaluation. Since we lack the metric value from this worker, we cannot determine the top fraction to open up the next rung. On the other hand, we want to assign a job to our free worker, so it does not remain idle. Our solution is to start a new round of successive halving and assign our worker to the first trial there. However, once a rung is completed in update, we make sure to insert new configurations at the beginning of the queue, so they take precedence over configurations from the next round.英語のヒント
最後に、
SuccessiveHalvingSchedulerの実装には少し複雑な点があることに注意しよう。あるワーカーがジョブを実行できる状態にあり、現在の段がほぼ完全に埋まったときにsuggestが呼ばれたが、別のワーカーはまだ評価で忙しいとしよう。このワーカーからの指標の値がないので、次の段を開くための上位の割合を決められない。一方、空いているワーカーが遊ばないように、それにジョブを割り当てたい。解決策は、逐次半減法の新しいラウンドを始め、そのワーカーをそこでの最初の試行に割り当てることである。しかし、updateで段が完了したら、新しい設定を待ち行列の先頭に入れ、次のラウンドの設定よりも優先されるようにする。