29.4  多保真度超参数优化

即便在中等规模的数据集上,训练神经网络也可能代价高昂。视配置空间(29.1.1.2 节)的大小而定,超参数优化往往需要数十乃至数百次函数评估才能找到一组表现优良的超参数配置。正如我们在 29.3 节 中所见,利用并行计算资源可以显著缩短 HPO 的整体挂钟时间,但这并不会减少所需的总计算量。

本节将介绍如何加速超参数配置的评估过程。随机搜索等方法会为每次超参数评估分配同等数量的资源(例如训练轮数、训练样本数)。图 29.4.1 描绘了用不同超参数配置训练的一组神经网络的学习曲线。可以看到,仅训练几轮之后,我们就能凭肉眼区分出表现良好的配置与次优配置。不过,由于学习曲线带有噪声,要选出真正最优的那一个配置可能仍需跑满全部 100 轮。

图 29.4.1: 随机超参数配置的学习曲线

多保真度超参数优化(multi-fidelity hyperparameter optimization)将更多资源分配给有潜力的配置,并尽早终止表现欠佳配置的评估。由于在相同总资源预算下能够尝试更多配置,这一策略显著加快了优化进程。

更形式化地说,我们扩展 29.1.1 节 中的定义,为目标函数 \(f(\mathbf{x}, r)\) 引入额外输入 \(r \in [r_{\mathrm{min}}, r_{\mathrm{max}}]\),用于指定我们愿意为评估配置 \(\mathbf{x}\) 投入的资源量。我们假设误差 \(f(\mathbf{x}, r)\) 随 \(r\) 增大而减小,而计算代价 \(c(\mathbf{x}, r)\) 则随之增加。通常 \(r\) 表示训练神经网络的轮数,但也可以表示训练子集大小或交叉验证折数。

from collections import defaultdict
from scipy import stats
from collections import defaultdict
from scipy import stats
from collections import defaultdict
from scipy import stats
d2l.set_figsize()
d2l.set_figsize()
d2l.set_figsize()

29.4.1 逐次减半

将随机搜索推广到多保真度设定的最简单方法之一是逐次减半(successive halving)(Jamieson 和 Talwalkar 2016年; Karnin 等 2013年)。其基本思想是:先从配置空间中(例如随机采样)取出 \(N\) 个配置,仅将每个配置训练 \(r_{\mathrm{min}}\) 轮;随后淘汰表现最差的一部分试验,让保留下来的试验继续训练更长时间。如此反复迭代,留存试验越来越少、训练时间越来越长,直到至少有一次试验达到 \(r_{\mathrm{max}}\) 轮。

更形式化地,考虑最小预算 \(r_{\mathrm{min}}\)(例如 1 轮)、最大预算 \(r_{\mathrm{max}}\)(例如前一示例中的 max_epochs)以及减半常数 \(\eta\in\{2, 3, \dots\}\)。为简单起见,假设 \(r_{\mathrm{max}} = r_{\mathrm{min}} \eta^K\),其中 \(K \in \mathbb{N}\),初始配置数设为 \(N = \eta^K\)。我们定义梯级(rung)集合为 \(\mathcal{R} = \{ r_{\mathrm{min}}, r_{\mathrm{min}}\eta, r_{\mathrm{min}}\eta^2, \dots, r_{\mathrm{max}} \}\)。

一轮逐次减半的流程如下:首先将 \(N\) 次试验运行到第一个梯级 \(r_{\mathrm{min}}\);按验证误差排序后,保留最优的 \(1 / \eta\) 比例(共 \(\eta^{K-1}\) 个配置),其余全部淘汰;留存试验继续训练到下一个梯级(\(r_{\mathrm{min}}\eta\) 轮),如此重复。在每个梯级上,都有 \(1 / \eta\) 的试验留存下来,并以扩大为原来 \(\eta\) 倍的预算继续训练。在上述 \(N\) 的取值下,最终恰有一次试验会训练满全部预算 \(r_{\mathrm{max}}\)。一轮逐次减半结束后,我们就用新一批初始配置开启下一轮,如此迭代直至耗尽总预算。

图 29.4.2: 逐次减半下随机超参数配置的学习曲线。

我们通过继承 29.2 节 中的 HPOScheduler 基类来实现逐次减半,使其可以配合通用的 HPOSearcher 对象采样配置(在下面的示例中将使用 RandomSearcher)。此外,用户还需传入最小资源 \(r_{\mathrm{min}}\)、最大资源 \(r_{\mathrm{max}}\) 和 \(\eta\)。在调度器内部,我们维护一个队列,存放当前梯级 \(r_i\) 上尚待评估的配置,并在每次跃迁到下一梯级时更新该队列。

class SuccessiveHalvingScheduler(d2l.HPOScheduler):
    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 = []
class SuccessiveHalvingScheduler(d2l.HPOScheduler):
    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 = []
class SuccessiveHalvingScheduler(d2l.HPOScheduler):
    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 = []

初始时队列为空,我们先向其中填入 \(n = \textrm{prefact} \cdot \eta^{K}\) 个配置,在最小梯级 \(r_{\mathrm{min}}\) 上进行首轮评估。这里的 \(\textrm{prefact}\) 便于我们在其他场景下复用代码;就本节而言,固定取 \(\textrm{prefact} = 1\)。每当有可用资源且 HPOTuner 对象调用 suggest 函数时,我们就从队列中取出一个元素返回。一旦完成一整轮逐次减半(即所有留存配置都已在最高资源级别 \(r_{\mathrm{max}}\) 上完成评估且队列变空),我们便用新一组随机采样的配置重新开启整个流程。

@d2l.add_to_class(SuccessiveHalvingScheduler)
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()
@d2l.add_to_class(SuccessiveHalvingScheduler)
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()
@d2l.add_to_class(SuccessiveHalvingScheduler)
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()

每收集到一个新的数据点时,我们先更新搜索器模块,随后检查当前梯级上的所有数据点是否均已收集完毕。若是,则对所有配置排序,并将排名前 \(\frac{1}{\eta}\) 的配置压入队列。

@d2l.add_to_class(SuccessiveHalvingScheduler)
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
@d2l.add_to_class(SuccessiveHalvingScheduler)
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
@d2l.add_to_class(SuccessiveHalvingScheduler)
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

各配置按其在当前梯级上观测到的性能进行排序。

@d2l.add_to_class(SuccessiveHalvingScheduler)
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]]

@d2l.add_to_class(SuccessiveHalvingScheduler)
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]]

@d2l.add_to_class(SuccessiveHalvingScheduler)
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]]

下面看看逐次减半在我们的神经网络示例上表现如何。我们取 \(r_{\mathrm{min}} = 2\)、\(\eta = 2\)、\(r_{\mathrm{max}} = 10\),因此各梯级水平依次为 \(2, 4, 8, 10\)。

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 即可。

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)
Trial 0: learning_rate = 0.1638, batch_size = 212, max_epochs = 2

    error = 0.9000, runtime = 10.2 s
Trial 1: learning_rate = 0.3775, batch_size = 155, max_epochs = 2

    error = 0.3961, runtime = 10.2 s
Trial 2: learning_rate = 0.02491, batch_size = 228, max_epochs = 2

    error = 0.9000, runtime = 7.0 s
Trial 3: learning_rate = 0.3017, batch_size = 72, max_epochs = 2

    error = 0.3405, runtime = 15.6 s
Trial 4: learning_rate = 0.09218, batch_size = 90, max_epochs = 2

    error = 0.9000, runtime = 13.7 s
Trial 5: learning_rate = 0.273, batch_size = 78, max_epochs = 2

    error = 0.3946, runtime = 14.8 s
Trial 6: learning_rate = 0.04858, batch_size = 136, max_epochs = 2

    error = 0.9000, runtime = 7.6 s
Trial 7: learning_rate = 0.1, batch_size = 128, max_epochs = 2

    error = 0.9000, runtime = 9.7 s
Trial 8: learning_rate = 0.1638, batch_size = 212, max_epochs = 4

    error = 0.7982, runtime = 7.3 s
Trial 9: learning_rate = 0.3775, batch_size = 155, max_epochs = 4

    error = 0.3318, runtime = 9.7 s
Trial 10: learning_rate = 0.273, batch_size = 78, max_epochs = 4

    error = 0.2684, runtime = 18.9 s
Trial 11: learning_rate = 0.3017, batch_size = 72, max_epochs = 4

    error = 0.3075, runtime = 20.4 s
Trial 12: learning_rate = 0.3017, batch_size = 72, max_epochs = 8

    error = 0.1806, runtime = 40.2 s
Trial 13: learning_rate = 0.273, batch_size = 78, max_epochs = 8

    error = 0.2286, runtime = 37.2 s
Trial 14: learning_rate = 0.3017, batch_size = 72, max_epochs = 10

    error = 0.1734, runtime = 35.3 s
Trial 15: learning_rate = 0.7063, batch_size = 36, max_epochs = 2

    error = 0.2735, runtime = 12.4 s
Trial 16: learning_rate = 0.9233, batch_size = 210, max_epochs = 2

    error = 0.4177, runtime = 8.0 s
Trial 17: learning_rate = 0.05791, batch_size = 132, max_epochs = 2

    error = 0.9000, runtime = 7.0 s
Trial 18: learning_rate = 0.01888, batch_size = 226, max_epochs = 2

    error = 0.9000, runtime = 7.5 s
Trial 19: learning_rate = 0.01166, batch_size = 58, max_epochs = 2

    error = 0.9000, runtime = 8.9 s
Trial 20: learning_rate = 0.06343, batch_size = 228, max_epochs = 2

    error = 0.9000, runtime = 2.9 s
Trial 21: learning_rate = 0.06858, batch_size = 136, max_epochs = 2

    error = 0.9000, runtime = 3.8 s
Trial 22: learning_rate = 0.1522, batch_size = 51, max_epochs = 2

    error = 0.3353, runtime = 10.2 s
Trial 23: learning_rate = 0.05791, batch_size = 132, max_epochs = 4

    error = 0.9000, runtime = 7.5 s
Trial 24: learning_rate = 0.9233, batch_size = 210, max_epochs = 4

    error = 0.2432, runtime = 5.9 s
Trial 25: learning_rate = 0.1522, batch_size = 51, max_epochs = 4

    error = 0.2587, runtime = 16.5 s
Trial 26: learning_rate = 0.7063, batch_size = 36, max_epochs = 4

    error = 0.1686, runtime = 22.3 s
Trial 27: learning_rate = 0.9233, batch_size = 210, max_epochs = 8

    error = 0.1791, runtime = 11.5 s
Trial 28: learning_rate = 0.7063, batch_size = 36, max_epochs = 8

    error = 0.1319, runtime = 42.0 s
Trial 29: learning_rate = 0.7063, batch_size = 36, max_epochs = 10

    error = 0.1175, runtime = 56.5 s
Trial 0: learning_rate = 0.1927, batch_size = 224, max_epochs = 2

    error = 0.9000, runtime = 25.2 s
Trial 1: learning_rate = 0.02629, batch_size = 111, max_epochs = 2

    error = 0.9000, runtime = 26.4 s
Trial 2: learning_rate = 0.02917, batch_size = 220, max_epochs = 2

    error = 0.9000, runtime = 25.3 s
Trial 3: learning_rate = 0.0734, batch_size = 237, max_epochs = 2

    error = 0.9000, runtime = 23.0 s
Trial 4: learning_rate = 0.04774, batch_size = 206, max_epochs = 2

    error = 0.9000, runtime = 23.9 s
Trial 5: learning_rate = 0.02717, batch_size = 96, max_epochs = 2

    error = 0.9000, runtime = 17.4 s
Trial 6: learning_rate = 0.02495, batch_size = 149, max_epochs = 2

    error = 0.9000, runtime = 27.5 s
Trial 7: learning_rate = 0.1, batch_size = 128, max_epochs = 2

    error = 0.9000, runtime = 16.8 s
Trial 8: learning_rate = 0.0734, batch_size = 237, max_epochs = 4

    error = 0.9000, runtime = 10.1 s
Trial 9: learning_rate = 0.02917, batch_size = 220, max_epochs = 4

    error = 0.8636, runtime = 9.6 s
Trial 10: learning_rate = 0.02629, batch_size = 111, max_epochs = 4

    error = 0.9000, runtime = 12.2 s
Trial 11: learning_rate = 0.1927, batch_size = 224, max_epochs = 4

    error = 0.4942, runtime = 10.0 s
Trial 12: learning_rate = 0.02917, batch_size = 220, max_epochs = 8

    error = 0.9000, runtime = 13.2 s
Trial 13: learning_rate = 0.1927, batch_size = 224, max_epochs = 8

    error = 0.2833, runtime = 13.1 s
Trial 14: learning_rate = 0.1927, batch_size = 224, max_epochs = 10

    error = 0.2791, runtime = 14.6 s
Trial 15: learning_rate = 0.04153, batch_size = 35, max_epochs = 2

    error = 0.6617, runtime = 22.5 s
Trial 16: learning_rate = 0.3541, batch_size = 74, max_epochs = 2

    error = 0.3017, runtime = 17.9 s
Trial 17: learning_rate = 0.6643, batch_size = 81, max_epochs = 2

    error = 0.2607, runtime = 21.4 s
Trial 18: learning_rate = 0.0434, batch_size = 247, max_epochs = 2

    error = 0.9000, runtime = 22.2 s
Trial 19: learning_rate = 0.01825, batch_size = 157, max_epochs = 2

    error = 0.9000, runtime = 24.4 s
Trial 20: learning_rate = 0.0129, batch_size = 233, max_epochs = 2

    error = 0.9000, runtime = 27.4 s
Trial 21: learning_rate = 0.02479, batch_size = 237, max_epochs = 2

    error = 0.8298, runtime = 8.7 s
Trial 22: learning_rate = 0.01104, batch_size = 229, max_epochs = 2

    error = 0.9000, runtime = 21.7 s
Trial 23: learning_rate = 0.02479, batch_size = 237, max_epochs = 4

    error = 0.9000, runtime = 10.4 s
Trial 24: learning_rate = 0.04153, batch_size = 35, max_epochs = 4

    error = 0.3268, runtime = 20.6 s
Trial 25: learning_rate = 0.3541, batch_size = 74, max_epochs = 4

    error = 0.2296, runtime = 14.6 s
Trial 26: learning_rate = 0.6643, batch_size = 81, max_epochs = 4

    error = 0.2295, runtime = 13.1 s
Trial 27: learning_rate = 0.3541, batch_size = 74, max_epochs = 8

    error = 0.1714, runtime = 47.3 s
Trial 28: learning_rate = 0.6643, batch_size = 81, max_epochs = 8

    error = 0.1645, runtime = 20.4 s
Trial 29: learning_rate = 0.6643, batch_size = 81, max_epochs = 10

    error = 0.1470, runtime = 23.7 s
Trial 0: learning_rate = 0.06612, batch_size = 191, max_epochs = 2

    error = 0.9000, runtime = 14.2 s
Trial 1: learning_rate = 0.03328, batch_size = 195, max_epochs = 2

    error = 0.9000, runtime = 11.7 s
Trial 2: learning_rate = 0.362, batch_size = 131, max_epochs = 2

    error = 0.4842, runtime = 11.3 s
Trial 3: learning_rate = 0.05792, batch_size = 243, max_epochs = 2

    error = 0.9000, runtime = 12.1 s
Trial 4: learning_rate = 0.06889, batch_size = 249, max_epochs = 2

    error = 0.9000, runtime = 10.9 s
Trial 5: learning_rate = 0.01612, batch_size = 140, max_epochs = 2

    error = 0.9000, runtime = 10.9 s
Trial 6: learning_rate = 0.0255, batch_size = 138, max_epochs = 2

    error = 0.9000, runtime = 10.5 s
Trial 7: learning_rate = 0.1, batch_size = 128, max_epochs = 2

    error = 0.9000, runtime = 11.2 s
Trial 8: learning_rate = 0.05792, batch_size = 243, max_epochs = 4

    error = 0.9000, runtime = 5.5 s
Trial 9: learning_rate = 0.03328, batch_size = 195, max_epochs = 4

    error = 0.9000, runtime = 6.8 s
Trial 10: learning_rate = 0.06612, batch_size = 191, max_epochs = 4

    error = 0.9000, runtime = 6.7 s
Trial 11: learning_rate = 0.362, batch_size = 131, max_epochs = 4

    error = 0.3472, runtime = 8.1 s
Trial 12: learning_rate = 0.05792, batch_size = 243, max_epochs = 8

    error = 0.9000, runtime = 12.7 s
Trial 13: learning_rate = 0.362, batch_size = 131, max_epochs = 8

    error = 0.2602, runtime = 12.9 s
Trial 14: learning_rate = 0.362, batch_size = 131, max_epochs = 10

    error = 0.3311, runtime = 14.9 s
Trial 15: learning_rate = 0.01299, batch_size = 71, max_epochs = 2

    error = 0.9000, runtime = 12.2 s
Trial 16: learning_rate = 0.04391, batch_size = 199, max_epochs = 2

    error = 0.9000, runtime = 9.9 s
Trial 17: learning_rate = 0.3167, batch_size = 62, max_epochs = 2

    error = 0.2634, runtime = 15.5 s
Trial 18: learning_rate = 0.5671, batch_size = 35, max_epochs = 2

    error = 0.2823, runtime = 21.4 s
Trial 19: learning_rate = 0.06123, batch_size = 215, max_epochs = 2

    error = 0.9000, runtime = 8.9 s
Trial 20: learning_rate = 0.1101, batch_size = 196, max_epochs = 2

    error = 0.9000, runtime = 9.2 s
Trial 21: learning_rate = 0.1629, batch_size = 38, max_epochs = 2

    error = 0.3008, runtime = 19.6 s
Trial 22: learning_rate = 0.0417, batch_size = 219, max_epochs = 2

    error = 0.9000, runtime = 10.6 s
Trial 23: learning_rate = 0.01299, batch_size = 71, max_epochs = 4

    error = 0.9000, runtime = 14.6 s
Trial 24: learning_rate = 0.1629, batch_size = 38, max_epochs = 4

    error = 0.2223, runtime = 22.6 s
Trial 25: learning_rate = 0.5671, batch_size = 35, max_epochs = 4

    error = 0.2124, runtime = 21.8 s
Trial 26: learning_rate = 0.3167, batch_size = 62, max_epochs = 4

    error = 0.2200, runtime = 12.8 s
Trial 27: learning_rate = 0.3167, batch_size = 62, max_epochs = 8

    error = 0.1598, runtime = 22.5 s
Trial 28: learning_rate = 0.5671, batch_size = 35, max_epochs = 8

    error = 0.1835, runtime = 48.9 s
Trial 29: learning_rate = 0.3167, batch_size = 62, max_epochs = 10

    error = 0.1514, runtime = 36.8 s

我们可以将所有已评估配置的学习曲线可视化。可以看到,大多数配置都被提前终止,只有表现较优的配置才留存到 \(r_{\mathrm{max}}\)。不妨将其与向每个配置都分配 \(r_{\mathrm{max}}\) 资源的朴素随机搜索对比。

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')

Text(0.5, 0, 'epochs')

Text(0.5, 0, 'epochs')

最后,留意 SuccessiveHalvingScheduler 实现中的一处细节。假设某个工作进程空闲下来可以运行作业,此时调用了 suggest,而当前梯级几乎已经填满,仅剩另一个工作进程仍在执行评估。由于缺少该工作进程的指标值,我们尚无法确定前 \(1 / \eta\) 的晋级名单以开启下一梯级;但另一方面,我们又希望给空闲工作进程分配任务以免闲置。我们的解决办法是直接开启新一轮逐次减半,将该工作进程分配给新一轮的首个试验;而一旦某个梯级在 update 中收集完毕,我们就确保将晋级配置插入队列头部,使其优先于下一轮的配置执行。

29.4.2 小结

本节介绍了多保真度超参数优化的概念:假设我们可以获取目标函数的低成本近似指标,例如以训练若干轮后的验证误差作为跑满全部训练轮数后验证误差的代理。多保真度超参数优化不仅能缩短挂钟时间,还能切实降低 HPO 的总体计算开销。

我们实现并评估了逐次减半这一简洁而高效的多保真度 HPO 算法。

29.4.3 练习

  1. 考虑包含 \(N = \eta^K\) 个配置且 \(r_{\mathrm{max}} = r_{\mathrm{min}}\eta^K\) 的一轮逐次减半,其中每次试验都像 hpo_objective_lenet 那样从头开始训练。
    1. 证明每个梯级总计训练 \(r_{\mathrm{max}}\) 轮,从而一整轮逐次减半共训练 \((K+1)r_{\mathrm{max}}\) 轮。在相同总训练轮数下,随机搜索可以将多少个配置训练到 \(r_{\mathrm{max}}\) 轮?
    2. 针对本节实验,推导出当 \(r_{\mathrm{min}} = 2\)、\(\eta = 2\)、\(r_{\mathrm{max}} = 10\) 时,SuccessiveHalvingScheduler 构造函数算出的 rung_levels 与 K 的值、每个梯级上的试验次数,以及一轮中的总试验次数和总训练轮数。tuner.run(number_of_trials=30) 完成了多少轮?若以 max_epochs=10 运行 30 次随机搜索试验,总共需要训练多少轮?
  2. 29.4.1 节 最后一段描述了当某个梯级仍在等待结果时调用 suggest 会发生什么,并指出晋级配置会被插入 self.queue 头部,从而优先于下一轮的配置执行。采用本节实验的参数设置,并设两个工作进程共享同一个 SuccessiveHalvingScheduler:梯级 \(r_{\mathrm{min}}\) 上的八个结果已返回七个,第八次试验仍在运行,此时队列为空,而空闲工作进程调用了 suggest。
    1. 依次写出在这次调用 suggest 之后、在携第八个结果调用 update 之后,以及在随后两次调用 suggest 之后 self.queue 的内容。接下来两次调用分别返回哪些配置?
    2. 这与正文描述一致吗?若不一致,请修改 suggest 或 update 中的一行代码,使晋级配置优先返回,并用一个直接返回随机数而不实际训练模型的目标函数驱动两个模拟工作进程来验证你的修改。
  3. 当噪声使最优配置在低梯级上看起来不如其他配置时,逐次减半可能会将其误淘汰。将配置 \(i\) 在梯级 \(r\) 上观测到的验证误差建模为 \(f_i + \epsilon_i\),其中 \(\epsilon_i \sim \mathcal{N}(0, \sigma_r^2)\) 相互独立,并假设在该梯级上最优配置比其余 \(n - 1\) 个配置中的每一个都至少优 \(\Delta > 0\)。
    1. 设 \(M\) 为观测误差小于最优配置观测误差的其他配置个数。证明 \(\mathbb{E}[M] \leq (n-1)\,\Phi(-\Delta/(\sqrt{2}\sigma_r))\),其中 \(\Phi\) 为标准正态分布的累积分布函数。
    2. 仅当 \(M \geq n/\eta\) 时,最优配置才会被淘汰。请利用马尔可夫不等式证明该事件发生的概率至多为 \(\eta\,\Phi(-\Delta/(\sqrt{2}\sigma_r))\)。这一推导遵循 Karnin 等 (2013年) 对逐次减半的分析。
    3. 假设 \(\sigma_r = \sigma/\sqrt{r}\)。在一轮逐次减半中,哪个梯级对丢失最优配置的概率贡献最大?这对选择 \(r_{\mathrm{min}}\) 有何启示?
  4. 逐次减半需要事先选定 \(r_{\mathrm{min}}\):取值过小虽然能尝试大量配置,却依赖不可靠的早期误差进行排序;取值过大虽能可靠排序,但尝试的配置数量又太少。Hyperband (Li 等 2018年) 在若干个分桶(bracket)中运行逐次减半:在 \(r_{\mathrm{max}} = r_{\mathrm{min}}\eta^K\) 下,分桶 \(s \in \{K, K-1, \ldots, 0\}\) 在起始资源 \(r_{\mathrm{max}}\eta^{-s}\) 上启动 \(\lceil (K+1)\eta^s/(s+1) \rceil\) 个配置。
    1. 证明:将 SuccessiveHalvingScheduler 的 r_min 设为 \(r_{\mathrm{max}}\eta^{-s}\)、将 prefact 设为 \((K+1)/(s+1)\) 时,在不计取整误差的情况下恰好以该配置数启动分桶 \(s\)。
    2. 对 \(\eta = 3\)、\(r_{\mathrm{min}} = 1\)、\(r_{\mathrm{max}} = 27\),列出每个分桶的起始资源、各梯级上的配置数,以及每次试验均从头训练时的总训练轮数。观察各分桶的总训练轮数,你能发现什么规律?
    3. 当训练 1 轮后的排序已经能够预测训练 27 轮后的排序时,你预期哪个分桶会返回最优配置?当早期排序无法预测最终排序时呢?
  5. 在相同总训练轮数下比较逐次减半与随机搜索。取 \(\eta = 3\)、\(r_{\mathrm{min}} = 1\)、\(r_{\mathrm{max}} = 9\) 时,一轮逐次减半共评估 13 次试验、训练 27 轮,恰好等于 max_epochs=9 下三次随机搜索试验的训练轮数。
    1. 以 functools.partial(d2l.hpo_objective_lenet, max_epochs=9) 作为目标函数,分别运行一轮 SuccessiveHalvingScheduler 以及三次基于 BasicScheduler 的随机搜索试验。使用不同随机种子各自重复三次,报告两种方法所返回配置在 9 轮后的验证误差(对三次重复取平均)。
    2. 在逐次减半训练 1 轮后所评估的配置中,有多大比例的误差高于 0.85(接近随机猜测水平 0.9)?请结合这一比例解释上述对比实验的结果。对于该模型,你会选择怎样的 \(r_{\mathrm{min}}\)?