29.3  异步随机搜索

正如我们在上一节(29.2 节)中所见,由于超参数配置的评估代价高昂,我们可能需要等待数小时乃至数天,随机搜索才能返回一组优秀的超参数配置。在实践中,我们往往可以使用一组计算资源池,例如同一台机器上的多块 GPU,或者各自配备单块 GPU 的多台机器。这自然引出一个问题:如何高效地对随机搜索进行分布式并行化?

一般而言,并行超参数优化可分为同步与异步两类(参见 图 29.3.1)。在同步模式下,我们必须等待当前并发运行的所有试验全部结束后,才能启动下一批试验。考虑包含深度神经网络每层卷积核数或层数等超参数的配置空间:层数更多或卷积核数更多的超参数配置自然需要更长的运行时间才能完成,而同一批次中的其他试验都不得不在同步点处等待(即 图 29.3.1 中的灰色区域),然后才能继续优化流程。

在异步模式下,只要有计算资源空闲下来,我们就立即调度一次新试验。由于彻底消除了同步开销,这种方式能够最充分地利用计算资源。对于随机搜索而言,每个新超参数配置都是彼此独立选取的,尤其不需要依赖任何先前评估的观测结果,这意味着我们可以轻而易举地对随机搜索进行异步并行化。相比之下,对于依赖历史观测做出决策的更复杂方法(参见 29.5 节),异步化则并非易事。尽管异步随机搜索需要比顺序模式更多的计算资源,但它能实现线性加速比:若能并行运行 \(K\) 次试验,则达到给定性能的速度也会快 \(K\) 倍。

图 29.3.1: 同步与异步分布式超参数优化示意图。与顺序模式相比,分布式执行可在保持总算力不变的前提下缩短整体挂钟时间;若存在慢任务,同步调度会导致工作进程空闲等待。

本节将介绍在同一台机器的多个 Python 进程中执行试验的异步随机搜索。从零实现分布式作业调度与执行相当繁琐,因此我们将使用提供简洁异步 HPO 接口的 Syne Tune (Salinas 等 2022年)。Syne Tune 支持多种执行后端,感兴趣的读者不妨研读其简洁的 API,以进一步了解分布式 HPO。

import contextlib
import io
import logging
# Use INFO level so the periodic Syne Tune tuning-status table appears,
# but use a clean format that drops the "INFO:syne_tune.tuner:" prefix.
logging.basicConfig(level=logging.INFO, format="%(message)s", force=True)
# Silence Syne Tune's import-time chatter about optional AWS dependencies
# (sagemaker, s3fs) and Ray Tune. We use the local PythonBackend, so those
# are not needed. Suppress both print() and logging.info() during imports.
_root = logging.getLogger()
_prev_level = _root.level
_root.setLevel(logging.WARNING)
try:
    with contextlib.redirect_stdout(io.StringIO()):
        from syne_tune.config_space import loguniform, randint
        from syne_tune.backend.python_backend.python_backend import PythonBackend
        from syne_tune.optimizer.baselines import RandomSearch
        from syne_tune import Tuner, StoppingCriterion
        from syne_tune.experiments import load_experiment
finally:
    _root.setLevel(_prev_level)

# Silence the per-trial subprocess-command spam from local_backend and
# drop the per-trial scheduling / completion lines from the tuner logger.
# Keep the periodic "tuning status (last metric is reported)" updates so
# the reader can still see progress over time.
class _DropPerTrialNoise(logging.Filter):
    _DROP = (
        "results of trials will be saved",
        "scheduled ",
        "Trial trial_id ",
    )
    def filter(self, record):
        msg = record.getMessage()
        return not any(s in msg for s in self._DROP)

logging.getLogger("syne_tune.backend.local_backend").setLevel(logging.WARNING)
logging.getLogger("syne_tune.tuner").addFilter(_DropPerTrialNoise())

29.3.1 目标函数

首先,我们需要定义一个新的目标函数,使其通过 report 回调函数将性能指标汇报给 Syne Tune。

def hpo_objective_lenet_synetune(learning_rate, batch_size, max_epochs):
    from d2l import torch as d2l    
    from syne_tune import Reporter

    model = d2l.LeNet(lr=learning_rate, num_classes=10)
    trainer = d2l.HPOTrainer(max_epochs=1, num_gpus=1)
    data = d2l.FashionMNIST(batch_size=batch_size)
    model.apply_init([next(iter(data.get_dataloader(True)))[0]], d2l.init_cnn)
    report = Reporter() 
    for epoch in range(1, max_epochs + 1):
        if epoch == 1:
            # Initialize the state of Trainer
            trainer.fit(model=model, data=data) 
        else:
            trainer.fit_epoch()
        validation_error = trainer.validation_error()
        report(epoch=epoch, validation_error=validation_error)

注意,Syne Tune 的 PythonBackend 要求在函数定义内部导入所需依赖库。

29.3.2 异步调度器

首先,我们定义并发评估试验的工作进程(worker)数量,并通过设定总挂钟时间上限来指定随机搜索的运行时长。

# Each LeNet trial fits in well under 7 GB of GPU memory, so we can pack
# multiple trials per device. `PythonBackend(rotate_gpus=True)` (the
# default) round-robins trials across detected GPUs and falls back to
# sharing when `n_workers > num_gpus`. Allocate 7 GB per slot — this
# yields 3 slots on a 24 GB card and 4 slots on a 32 GB card after
# driver overhead, e.g. 4×24 GB → 12 slots; 2×32 GB → 8.
import torch
_GB = 1024 ** 3
n_workers = sum(
    torch.cuda.get_device_properties(i).total_memory // (7 * _GB)
    for i in range(torch.cuda.device_count())
) or 1

max_wallclock_time = 15 * 60  # 15 minutes

接下来,我们声明希望优化的指标以及是要最小化还是最大化该指标。具体而言,metric 需要与传给 report 回调函数的参数名一致。

mode = "min"
metric = "validation_error"

我们沿用前一个示例中的配置空间。在 Syne Tune 中,这个字典还可以用来向训练脚本传递常量属性,我们便利用这一特性传入 max_epochs。此外,我们在 initial_config 中指定首个待评估的配置。

config_space = {
    "learning_rate": loguniform(1e-2, 1),
    "batch_size": randint(32, 256),
    "max_epochs": 10,
}
initial_config = {
    "learning_rate": 0.1,
    "batch_size": 128,
}

接着,我们需要指定作业执行后端。这里仅考虑单机本机分发,即以子进程形式运行并行作业;但对于大规模 HPO,我们同样可以在集群或云环境中运行,让每次试验独占一个完整实例。

trial_backend = PythonBackend(
    tune_function=hpo_objective_lenet_synetune,
    config_space=config_space,
)

现在可以为异步随机搜索创建调度器了,其行为类似于 29.2 节 中的 BasicScheduler。

scheduler = RandomSearch(
    config_space,
    metric=metric,
    mode=mode,
    points_to_evaluate=[initial_config],
)
max_resource_level = 10, as inferred from config_space
Master random_seed = 1262744123

Syne Tune 同样提供了 Tuner 类,用于集中管理主实验循环与结果记录,并协调调度器与执行后端之间的交互。

stop_criterion = StoppingCriterion(max_wallclock_time=max_wallclock_time)

tuner = Tuner(
    trial_backend=trial_backend,
    scheduler=scheduler, 
    stop_criterion=stop_criterion,
    n_workers=n_workers,
    print_update_interval=int(max_wallclock_time * 0.6),
)

下面运行我们的分布式 HPO 实验。根据所设停止准则,它将运行约 15 分钟。

tuner.run()
tuning status (last metric is reported)
 trial_id     status  iter  learning_rate  batch_size  max_epochs  epoch  validation_error  worker-time
        0  Completed    10       0.100000         128          10     10            0.2923    24.180624
        1  Completed    10       0.082763         113          10     10            0.2644    24.934025
        2  Completed    10       0.080930         145          10     10            0.3151    22.784514
        3  Completed    10       0.322440         221          10     10            0.2375    19.111622
        4  Completed    10       0.068737          79          10     10            0.2696    31.304927
        5  Completed    10       0.873000          45          10     10            0.1271    50.856921
        6  Completed    10       0.291003         131          10     10            0.2747    22.858455
        7  Completed    10       0.043908          70          10     10            0.3156    35.170509
        8  Completed    10       0.038462         220          10     10            0.9000    19.027683
        9  Completed    10       0.172284          36          10     10            0.1557    61.369803
       10  Completed    10       0.024483         189          10     10            0.9000    20.478797
       11  Completed    10       0.020956         108          10     10            0.9000    26.251260
       12  Completed    10       0.048887         125          10     10            0.3936    20.209591
       13  Completed    10       0.564286          41          10     10            0.1407    58.065812
       14  Completed    10       0.011830         147          10     10            0.9000    21.675855
       15  Completed    10       0.014536         195          10     10            0.9000    20.842799
       16  Completed    10       0.025178         194          10     10            0.9000    20.872876
       17  Completed    10       0.749182         229          10     10            0.3169    19.869571
       18  Completed    10       0.140481          61          10     10            0.2102    40.129471
       19  Completed    10       0.082477         155          10     10            0.3306    23.295283
       20  Completed    10       0.046206          84          10     10            0.3166    31.231847
       21  Completed    10       0.472420         236          10     10            0.3068    19.213980
       22  Completed    10       0.392082         181          10     10            0.2116    20.849619
       23  Completed    10       0.208072         150          10     10            0.2631    19.606782
       24  Completed    10       0.532188         240          10     10            0.2020    17.290536
       25  Completed    10       0.013032         137          10     10            0.9000    22.963058
       26  Completed    10       0.880009         157          10     10            0.1678    21.478394
       27  Completed    10       0.381799          48          10     10            0.1408    45.632828
       28  Completed    10       0.024110         238          10     10            0.9000    18.564641
       29  Completed    10       0.011689         118          10     10            0.9000    24.454123
       30  Completed    10       0.270845          50          10     10            0.1605    45.937312
       31  Completed    10       0.117845         153          10     10            0.2748    21.869672
       32  Completed    10       0.281127         161          10     10            0.2239    21.272990
       33  Completed    10       0.559356         120          10     10            0.1561    24.321344
       34  Completed    10       0.022221          60          10     10            0.3719    37.052592
       35  Completed    10       0.201594         227          10     10            0.2625    18.939422
       36  Completed    10       0.567425         132          10     10            0.1620    22.784191
       37  Completed    10       0.010470         137          10     10            0.9000    22.976642
       38  Completed    10       0.011697          56          10     10            0.7861    42.085130
       39  Completed    10       0.016733         135          10     10            0.9000    23.487937
       40  Completed    10       0.017474         106          10     10            0.9000    26.340064
       41 InProgress     8       0.075841          32          10      8            0.2012    52.196238
       42  Completed    10       0.108654         140          10     10            0.2660    23.484949
       43  Completed    10       0.365593         210          10     10            0.2109    19.878235
       44 InProgress     8       0.031624         202          10      8            0.9000    16.066794
       45 InProgress     2       0.281488         147          10      2            0.7502     9.374961
3 trials running, 43 finished (43 until the end), 542.43s wallclock-time

reaching max wallclock time (900), stopping there.
Stopping trials that may still be running.
Tuning finished, results of trials can be found on syne-tune/python-entrypoint-2026-11-23-15-46-59-384
--------------------
Resource summary (last result is reported):
 trial_id     status  iter  learning_rate  batch_size  max_epochs  epoch  validation_error  worker-time
        0  Completed    10       0.100000         128          10   10.0            0.2923    24.180624
        1  Completed    10       0.082763         113          10   10.0            0.2644    24.934025
        2  Completed    10       0.080930         145          10   10.0            0.3151    22.784514
        3  Completed    10       0.322440         221          10   10.0            0.2375    19.111622
        4  Completed    10       0.068737          79          10   10.0            0.2696    31.304927
        5  Completed    10       0.873000          45          10   10.0            0.1271    50.856921
        6  Completed    10       0.291003         131          10   10.0            0.2747    22.858455
        7  Completed    10       0.043908          70          10   10.0            0.3156    35.170509
        8  Completed    10       0.038462         220          10   10.0            0.9000    19.027683
        9  Completed    10       0.172284          36          10   10.0            0.1557    61.369803
       10  Completed    10       0.024483         189          10   10.0            0.9000    20.478797
       11  Completed    10       0.020956         108          10   10.0            0.9000    26.251260
       12  Completed    10       0.048887         125          10   10.0            0.3936    20.209591
       13  Completed    10       0.564286          41          10   10.0            0.1407    58.065812
       14  Completed    10       0.011830         147          10   10.0            0.9000    21.675855
       15  Completed    10       0.014536         195          10   10.0            0.9000    20.842799
       16  Completed    10       0.025178         194          10   10.0            0.9000    20.872876
       17  Completed    10       0.749182         229          10   10.0            0.3169    19.869571
       18  Completed    10       0.140481          61          10   10.0            0.2102    40.129471
       19  Completed    10       0.082477         155          10   10.0            0.3306    23.295283
       20  Completed    10       0.046206          84          10   10.0            0.3166    31.231847
       21  Completed    10       0.472420         236          10   10.0            0.3068    19.213980
       22  Completed    10       0.392082         181          10   10.0            0.2116    20.849619
       23  Completed    10       0.208072         150          10   10.0            0.2631    19.606782
       24  Completed    10       0.532188         240          10   10.0            0.2020    17.290536
       25  Completed    10       0.013032         137          10   10.0            0.9000    22.963058
       26  Completed    10       0.880009         157          10   10.0            0.1678    21.478394
       27  Completed    10       0.381799          48          10   10.0            0.1408    45.632828
       28  Completed    10       0.024110         238          10   10.0            0.9000    18.564641
       29  Completed    10       0.011689         118          10   10.0            0.9000    24.454123
       30  Completed    10       0.270845          50          10   10.0            0.1605    45.937312
       31  Completed    10       0.117845         153          10   10.0            0.2748    21.869672
       32  Completed    10       0.281127         161          10   10.0            0.2239    21.272990
       33  Completed    10       0.559356         120          10   10.0            0.1561    24.321344
       34  Completed    10       0.022221          60          10   10.0            0.3719    37.052592
       35  Completed    10       0.201594         227          10   10.0            0.2625    18.939422
       36  Completed    10       0.567425         132          10   10.0            0.1620    22.784191
       37  Completed    10       0.010470         137          10   10.0            0.9000    22.976642
       38  Completed    10       0.011697          56          10   10.0            0.7861    42.085130
       39  Completed    10       0.016733         135          10   10.0            0.9000    23.487937
       40  Completed    10       0.017474         106          10   10.0            0.9000    26.340064
       41  Completed    10       0.075841          32          10   10.0            0.1832    64.374522
       42  Completed    10       0.108654         140          10   10.0            0.2660    23.484949
       43  Completed    10       0.365593         210          10   10.0            0.2109    19.878235
       44  Completed    10       0.031624         202          10   10.0            0.9000    18.761118
       45  Completed    10       0.281488         147          10   10.0            0.2361    23.991795
       46  Completed    10       0.190532         153          10   10.0            0.2482    21.258431
       47  Completed    10       0.325170         132          10   10.0            0.2217    22.704106
       48  Completed    10       0.188011         169          10   10.0            0.3072    20.850336
       49  Completed    10       0.327813         247          10   10.0            0.2401    17.456901
       50  Completed    10       0.011011         129          10   10.0            0.9000    23.416682
       51  Completed    10       0.132417         130          10   10.0            0.2599    23.082384
       52  Completed    10       0.344099         228          10   10.0            0.2314    18.955932
       53  Completed    10       0.036199         222          10   10.0            0.9000    19.796364
       54  Completed    10       0.016494          77          10   10.0            0.9000    33.558630
       55  Completed    10       0.032111         146          10   10.0            0.7620    22.493467
       56  Completed    10       0.021413          59          10   10.0            0.4491    40.675814
       57  Completed    10       0.493991         222          10   10.0            0.2692    18.877239
       58  Completed    10       0.300193         137          10   10.0            0.2070    23.010715
       59  Completed    10       0.504640          64          10   10.0            0.1503    35.827627
       60  Completed    10       0.131998         213          10   10.0            0.2927    20.928028
       61  Completed    10       0.038048         221          10   10.0            0.9000    18.682233
       62  Completed    10       0.087245         108          10   10.0            0.2637    25.803040
       63  Completed    10       0.013621          40          10   10.0            0.3979    51.572155
       64  Completed    10       0.053028         102          10   10.0            0.3449    26.897252
       65  Completed    10       0.011252          60          10   10.0            0.8099    37.590135
       66  Completed    10       0.534070         159          10   10.0            0.2422    21.234338
       67  Completed    10       0.070105         133          10   10.0            0.3313    22.401041
       68  Completed    10       0.018105         192          10   10.0            0.9000    20.837920
       69  Completed    10       0.364682         229          10   10.0            0.5061    18.501669
       70  Completed    10       0.038400          93          10   10.0            0.3607    29.295407
       71  Completed    10       0.233651         154          10   10.0            0.2252    21.028871
       72  Completed    10       0.020867         169          10   10.0            0.9000    21.482733
       73  Completed    10       0.650215          97          10   10.0            0.1634    27.433886
       74  Completed    10       0.291165         219          10   10.0            0.2304    19.184455
       75  Completed    10       0.019935         137          10   10.0            0.7915    22.716616
       76 InProgress     3       0.169711          67          10    3.0            0.2811    14.930157
       77 InProgress     7       0.021791         216          10    7.0            0.9000    15.219226
       78 InProgress     0       0.245067          33          10      -                 -            -
3 trials running, 76 finished (76 until the end), 900.27s wallclock-time

validation_error: best 0.1271 for trial-id 5
--------------------

所有已评估超参数配置的日志都会保存下来供后续分析。在调优作业运行期间的任意时刻,我们都可以轻松获取目前已得结果并绘制当前最优轨迹。

d2l.set_figsize()
tuning_experiment = load_experiment(tuner.name)
tuning_experiment.plot()

29.3.3 可视化异步优化过程

下面我们可视化异步优化过程中每次试验学习曲线的演化情况(图中每种颜色代表一次试验)。在任意时刻,并发运行的试验数都等于工作进程数;一旦某次试验结束,我们便立即启动下一次试验,而无需等待其他试验完成。借助异步调度,工作进程的空闲时间被降至最低。

d2l.set_figsize([6, 2.5])
results = tuning_experiment.results

for trial_id in results.trial_id.unique():
    df = results[results["trial_id"] == trial_id]
    d2l.plt.plot(
        df["st_tuner_time"],
        df["validation_error"],
        marker="o"
    )
    
d2l.plt.xlabel("wall-clock time")
d2l.plt.ylabel("objective function")
Text(0, 0.5, 'objective function')

29.3.4 小结

将试验分发到并行计算资源上,能够大幅缩短随机搜索的等待时间。总体而言,我们区分同步调度与异步调度:同步调度意味着必须等上一批超参数配置全部完成后才采样新一批配置,一旦出现慢任务(即耗时明显长于其他试验的试验),工作进程就不得不在同步点等待;异步调度则只要有资源空闲便立即评估新的超参数配置,从而确保所有工作进程在任意时刻都保持忙碌。虽然随机搜索无须改动算法本身即可轻松异步分布式运行,但其他方法往往需要做一些额外调整。

29.3.5 练习

  1. 假设 \(K\) 个工作进程运行若干试验,且各次试验的持续时间既独立于配置又彼此独立。
    1. 同步调度同时启动 \(K\) 次试验并等待最慢的一次完成。证明:若持续时间服从均值为 \(\mu\) 的指数分布,则一批试验的期望耗时为 \(\mu H_K\)(其中 \(H_K = 1 + 1/2 + \cdots + 1/K\)),从而工作进程处于忙碌状态的时间占比为 \(1/H_K\)。计算 \(K = 4\) 和 \(K = 12\) 时该占比的值。
    2. 若持续时间服从 \([T, 2T]\) 上的均匀分布,重复上述计算。为什么随着 \(K\) 增大,同步调度的忙碌时间占比在第一种情形下趋于零,而在第二种情形下却不会?
  2. 利用 tuning_experiment.results 衡量本节运行对工作进程的利用率。
    1. 对每次试验,取其最后汇报的 st_worker_time 值(即自该试验创建 Reporter 以来经过的秒数),将这些值的总和除以 n_workers * max_wallclock_time 并报告结果。找出 hpo_objective_lenet_synetune 在创建 Reporter 之前所做的工作,并指出使该比例低于 1 的其他开销。
    2. 在 29.2 节 的顺序 HPOTuner 下测量一次批量大小为 128 的 10 轮试验的运行时间,并与本次运行中相近批量大小试验的 st_worker_time 进行比较。n_workers 个工作进程相比顺序随机搜索取得了多大的加速比?当多个工作进程共享同一块 GPU 时,为什么加速比会小于 n_workers?
  3. 像贝叶斯优化这样从早期结果中学习的搜索器,在异步调度下会面临随机搜索所没有的问题:当某个工作进程空闲下来时,其他试验仍在运行。假设搜索器对目前已观测到的验证误差拟合高斯过程回归模型(第 28 章),并提议使采集函数最小化的配置。
    1. 若采集函数为后验均值 \(\mu(\mathbf{x})\),请解释为什么在新结果返回之前相继空闲下来的多个工作进程都会收到同一个配置。
    2. 一种常见补救办法是将每个尚未完成的待定配置 \(\mathbf{x}_p\) 视作已观测到数值 \(\mu(\mathbf{x}_p)\)。请利用新增单个观测时的后验更新公式证明:这样做会使后验均值在各处保持不变,同时降低 \(\mathbf{x}_p\) 附近的后验方差。
    3. 这一补救办法对最小化 \(\mu(\mathbf{x})\) 的搜索器有帮助吗?对于最小化 \(\mu(\mathbf{x}) - \kappa \sigma(\mathbf{x})\)(其中 \(\kappa > 0\),\(\sigma(\mathbf{x})\) 为后验标准差)的搜索器呢?
  4. 考虑 4.6 节 中实现并在 29.2 节 的练习 1 中使用过的 DropoutMLP 模型。
    1. 实现供 Syne Tune 使用的目标函数 hpo_objective_dropoutmlp_synetune,确保该函数在每一轮结束后汇报验证误差。
    2. 沿用 29.2 节 练习 1 的实验设置,比较随机搜索与贝叶斯优化。如果使用 SageMaker,不妨借助 Syne Tune 的基准测试工具并行运行实验。提示:贝叶斯优化由 syne_tune.optimizer.baselines.BayesianOptimization 提供。
    3. 本小题需要在至少配备 4 个 CPU 核心的实例上运行。任选上述一种方法(随机搜索或贝叶斯优化),分别以 n_workers=1、n_workers=2、n_workers=4 运行实验并比较结果(当前最优轨迹)。至少对于随机搜索,你应当能观察到随工作进程数呈线性扩展的加速效果。提示:为获得稳健结果,每种设置可能需要对多次重复实验取平均。
  5. 进阶。本练习的目标是在 Syne Tune 中实现一个新的调度器。
    1. 创建一个同时包含 d2lbook 与 syne-tune 源码的虚拟环境。
    2. 将 29.2 节 练习 2 中的 LocalSearcher 实现为 Syne Tune 中的新搜索器。提示:阅读这篇教程,或者参考这个示例。
    3. 在 DropoutMLP 基准上比较你新实现的 LocalSearcher 与 RandomSearch。