.. _sec_mf_hpo:
マルチフィデリティ・ハイパーパラメータ最適化
============================================
ニューラルネットワークの学習は、中規模のデータセットであっても高コストになり得る。
構成空間(:numref:`sec_intro_config_spaces`\ )によっては、
ハイパーパラメータ最適化では、性能の良いハイパーパラメータ構成を見つけるために数十回から数百回の関数評価が必要になる。
:numref:`sec_rs_async`
で見たように、並列リソースを活用することでHPOの全体的な壁時計時間を大幅に短縮できるが、必要な総計算量は減らない。
この節では、ハイパーパラメータ構成の評価をどのように高速化できるかを示す。
ランダムサーチのような手法では、各ハイパーパラメータ評価に同じ量のリソース(たとえばエポック数や学習データ点数)を割り当てる。
:numref:`img_samples_lc`
は、異なるハイパーパラメータ構成で学習したニューラルネットワーク群の学習曲線を示している。
数エポック後には、性能の良い構成と不十分な構成を視覚的に区別できるようになる。
しかし、学習曲線にはノイズがあるため、最良の構成を特定するには依然として100エポック分の完全な評価が必要かもしれない。
.. _img_samples_lc:
.. figure:: ../img/samples_lc.svg
ランダムなハイパーパラメータ構成の学習曲線
マルチフィデリティ・ハイパーパラメータ最適化では、有望な構成により多くのリソースを割り当て、性能の悪い構成の評価は早期に打ち切りる。
これにより、同じ総リソース量でより多くの構成を試せるため、最適化プロセスが高速化される。
より形式的には、 :numref:`sec_definition_hpo`
における定義を拡張し、目的関数 :math:`f(\mathbf{x}, r)` に追加の入力
:math:`r \in [r_{\mathrm{min}}, r_{max}]` を導入する。これは、構成
:math:`\mathbf{x}`
の評価に対してどれだけのリソースを費やすかを指定する。 ここでは、誤差
:math:`f(\mathbf{x}, r)` は :math:`r` とともに減少し、計算コスト
:math:`c(\mathbf{x}, r)` は増加すると仮定する。 通常、\ :math:`r`
はニューラルネットワークの学習エポック数を表すが、学習サブセットのサイズや交差検証の分割数でもかまわない。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
from d2l import torch as d2l
import numpy as np
from scipy import stats
from collections import defaultdict
d2l.set_figsize()
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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 = []
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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 = []
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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 = []
.. raw:: html
.. raw:: html
.. _sec_mf_hpo_sh:
逐次半減法
----------
マルチフィデリティ設定にランダムサーチを適応させる最も簡単な方法の1つが、\ *逐次半減法*
:cite:`jamieson-aistats16,karnin-icml13` である。
基本的な考え方は、たとえば構成空間からランダムにサンプルした :math:`N`
個の構成から始め、それぞれを :math:`r_{\mathrm{min}}`
エポックだけ学習することである。
その後、性能の悪い試行の一部を捨て、残ったものをより長く学習する。
このプロセスを繰り返すことで、より少ない試行がより長く実行され、少なくとも1つの試行が
:math:`r_{max}` エポックに到達するまで続く。
より形式的には、最小予算
:math:`r_{\mathrm{min}}`\ (たとえば1エポック)、最大予算
:math:`r_{max}`\ (たとえば前の例の ``max_epochs``\ )、および半減定数
:math:`\eta\in\{2, 3, \dots\}` を考える。
簡単のために、\ :math:`r_{max} = r_{\mathrm{min}} \eta^K`\ 、ただし
:math:`K \in \mathbb{I}` と仮定する。 このとき初期構成数は
:math:`N = \eta^K` である。 段(rung)の集合を
:math:`\mathcal{R} = \{ r_{\mathrm{min}}, r_{\mathrm{min}}\eta, r_{\mathrm{min}}\eta^2, \dots, r_{max} \}`
と定義する。
逐次半減法の1ラウンドは次のように進みる。 まず :math:`N`
個の試行を最初の段 :math:`r_{\mathrm{min}}` まで実行する。
検証誤差を並べ替え、上位 :math:`1 / \eta` の割合(これは
:math:`\eta^{K-1}`
個の構成に相当する)を残し、それ以外はすべて破棄する。
生き残った試行は次の段(\ :math:`r_{\mathrm{min}}\eta`
エポック)まで学習され、この過程を繰り返す。 各段で試行の
:math:`1 / \eta` が生き残り、その学習は :math:`\eta`
倍大きい予算で継続される。 この :math:`N`
の選び方では、最終的に1つの試行だけが完全な予算 :math:`r_{max}`
まで学習される。
このような逐次半減法の1ラウンドが終わると、新しい初期構成集合で次のラウンドを開始し、総予算を使い切るまで繰り返す。
.. figure:: ../img/sh.svg
ランダムなハイパーパラメータ構成の学習曲線。
逐次半減法を実装するために、 :numref:`sec_api_hpo` の ``HPOScheduler``
基底クラスを継承し、汎用の ``HPOSearcher``
オブジェクトが構成をサンプルできるようにする(以下の例では
``RandomSearcher`` になる)。 さらに、ユーザーは最小リソース
:math:`r_{\mathrm{min}}`\ 、最大リソース :math:`r_{max}`\ 、および
:math:`\eta` を入力として渡す必要がある。 スケジューラ内部では、現在の段
:math:`r_i` でまだ評価が必要な構成のキューを保持する。
次の段へ進むたびに、このキューを更新する。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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 = []
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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,
}
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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,
}
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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,
}
.. raw:: html
.. raw:: html
最初はキューは空で、そこに :math:`n = \textrm{prefact} \cdot \eta^{K}`
個の構成を入れる。 それらはまず最小の段 :math:`r_{\mathrm{min}}`
で評価される。 ここで :math:`\textrm{prefact}`
は、別の文脈でこのコードを再利用できるようにするためのものである。
この節では、\ :math:`\textrm{prefact} = 1` に固定する。
リソースが利用可能になり、\ ``HPOTuner`` オブジェクトが ``suggest``
関数を呼び出すたびに、キューから1つの要素を返す。
逐次半減法の1ラウンドが完了し、つまり生き残ったすべての構成を最高リソースレベル
:math:`r_{max}`
まで評価し終えてキューが空になったら、新しいランダムサンプルの構成集合でプロセス全体を再開する。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
@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()
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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)
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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)
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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)
.. raw:: html
.. raw:: html
新しいデータ点を収集したら、まず searcher モジュールを更新する。
その後、現在の段のすべてのデータ点をすでに収集し終えたかを確認する。
もしそうなら、すべての構成を並べ替え、上位 :math:`\frac{1}{\eta}`
の構成をキューに入れる。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
@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] = [] # Reset
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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")
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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")
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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")
.. raw:: html
.. raw:: html
構成は、現在の段で観測された性能に基づいて並べ替えられる。
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
@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]]
逐次半減法がニューラルネットワークの例でどのように機能するか見てみよう。
ここでは
:math:`r_{\mathrm{min}} = 2`\ 、\ :math:`\eta = 2`\ 、\ :math:`r_{max} = 10`
とし、段のレベルは :math:`2, 4, 8, 10` になる。
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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,
}
スケジューラを新しい ``SuccessiveHalvingScheduler``
に置き換えるだけである。
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
error = 0.1657370924949646, runtime = 67.32617664337158
.. figure:: output_sh-intro_737282_65_1.svg
.. figure:: output_sh-intro_737282_65_2.svg
.. figure:: output_sh-intro_737282_65_3.svg
.. figure:: output_sh-intro_737282_65_4.svg
.. figure:: output_sh-intro_737282_65_5.svg
.. figure:: output_sh-intro_737282_65_6.svg
.. figure:: output_sh-intro_737282_65_7.svg
.. figure:: output_sh-intro_737282_65_8.svg
.. figure:: output_sh-intro_737282_65_9.svg
.. figure:: output_sh-intro_737282_65_10.svg
.. figure:: output_sh-intro_737282_65_11.svg
.. figure:: output_sh-intro_737282_65_12.svg
.. figure:: output_sh-intro_737282_65_13.svg
.. figure:: output_sh-intro_737282_65_14.svg
.. figure:: output_sh-intro_737282_65_15.svg
.. figure:: output_sh-intro_737282_65_16.svg
.. figure:: output_sh-intro_737282_65_17.svg
.. figure:: output_sh-intro_737282_65_18.svg
.. figure:: output_sh-intro_737282_65_19.svg
.. figure:: output_sh-intro_737282_65_20.svg
.. figure:: output_sh-intro_737282_65_21.svg
.. figure:: output_sh-intro_737282_65_22.svg
.. figure:: output_sh-intro_737282_65_23.svg
.. figure:: output_sh-intro_737282_65_24.svg
.. figure:: output_sh-intro_737282_65_25.svg
.. figure:: output_sh-intro_737282_65_26.svg
.. figure:: output_sh-intro_737282_65_27.svg
.. figure:: output_sh-intro_737282_65_28.svg
.. figure:: output_sh-intro_737282_65_29.svg
.. figure:: output_sh-intro_737282_65_30.svg
評価したすべての構成の学習曲線を可視化できる。
ほとんどの構成は早期に打ち切られ、より性能の良い構成だけが
:math:`r_{max}` まで生き残る。 これを、すべての構成に :math:`r_{max}`
を割り当てる通常のランダムサーチと比較せよ。
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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")
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
Text(0.5, 0, 'epochs')
.. figure:: output_sh-intro_737282_67_1.svg
最後に、\ ``SuccessiveHalvingScheduler``
の実装には少し複雑な点があることに注意せよ。
あるワーカーがジョブを実行可能で、現在の段がほぼ埋まっている一方で、別のワーカーがまだ評価中だとする。
このワーカーからのメトリック値がまだないため、次の段を開くための上位
:math:`1 / \eta` の割合を決定できない。
一方で、空いているワーカーにジョブを割り当てて、アイドル状態のままにしたくはない。
そこで、私たちは新しい逐次半減法のラウンドを開始し、そのワーカーをそこでの最初の試行に割り当てる。
ただし、\ ``update``
である段が完了したら、新しい構成をキューの先頭に挿入し、次のラウンドの構成よりも優先されるようにしている。
まとめ
------
この節では、マルチフィデリティ・ハイパーパラメータ最適化の概念を導入した。
ここでは、完全なエポック数での検証誤差の代用として、あるエポック数まで学習した後の検証誤差のような、安価に評価できる目的関数の近似にアクセスできると仮定する。
マルチフィデリティ・ハイパーパラメータ最適化は、壁時計時間を短縮するだけでなく、HPOに必要な総計算量そのものを削減できる。
単純でありながら効率的なマルチフィデリティHPOアルゴリズムである逐次半減法を実装し、評価した。