有没有办法将参数传递给 optuna 中的多个作业?

Is there a way to pass arguments to multiple jobs in optuna?

我正在尝试使用 optuna 搜索超参数空间。

在一个特定场景中,我在一台带有几个 GPU 的机器上训练了一个模型。 模型和批量大小允许我 运行 每 1 个 GPU 进行 1 次训练。 所以,理想情况下,我想让 optuna 将所有试验分散到可用的 GPU 上 这样每个 GPU 上总有 1 次试验 运行ning。

docs 它说,我应该在单独的终端中为每个 GPU 启动一个进程,例如:

CUDA_VISIBLE_DEVICES=0 optuna study optimize foo.py objective --study foo --storage sqlite:///example.db

我想避免这种情况,因为在那之后整个超参数搜索会在多轮中继续进行。我不想总是为每个 GPU 手动启动一个进程,检查所有进程何时完成,然后开始下一轮。

我看到 study.optimize 有一个 n_jobs 参数。 乍一看,这似乎是完美的。 例如我可以这样做:

import optuna

def objective(trial):
    # the actual model would be trained here
    # the trainer here would need to know which GPU
    # it should be using
    best_val_loss = trainer(**trial.params)
    return best_val_loss

study = optuna.create_study()
study.optimize(objective, n_trials=100, n_jobs=8)

这将启动多个线程,每个线程开始一个训练。 然而,objective 中的训练器不知何故需要知道它应该使用哪个 GPU。 有什么技巧可以做到吗?

经过几次精神崩溃后,我发现我可以使用 multiprocessing.Queue 做我想做的事。要将其放入 objective 函数中,我需要将其定义为 lambda 函数或 class(我想部分函数也可以)。 例如

from contextlib import contextmanager
import multiprocessing
N_GPUS = 2

class GpuQueue:

    def __init__(self):
        self.queue = multiprocessing.Manager().Queue()
        all_idxs = list(range(N_GPUS)) if N_GPUS > 0 else [None]
        for idx in all_idxs:
            self.queue.put(idx)

    @contextmanager
    def one_gpu_per_process(self):
        current_idx = self.queue.get()
        yield current_idx
        self.queue.put(current_idx)


class Objective:

    def __init__(self, gpu_queue: GpuQueue):
        self.gpu_queue = gpu_queue

    def __call__(self, trial: Trial):
        with self.gpu_queue.one_gpu_per_process() as gpu_i:
            best_val_loss = trainer(**trial.params, gpu=gpu_i)
            return best_val_loss

if __name__ == '__main__':
    study = optuna.create_study()
    study.optimize(Objective(GpuQueue()), n_trials=100, n_jobs=8)

如果您想要一个将参数传递给多个作业使用的 objective 函数的记录解决方案,那么 Optuna docs 提供了两个解决方案:

  • 可调用类(可以与多处理结合),
  • lambda 函数包装器(注意:更简单,但不适用于多处理)。

如果您准备走一些捷径,那么您可以通过将全局值(常量,例如使用的 GPU 数量)直接(通过 python 环境)传递到 __call__() 方法(而不是作为 __init__() 的参数)。

可调用 类 解决方案已经过测试(在 optuna==2.0.0 中)与两个多处理后端 (loky/multiprocessing) 和远程数据库后端 (mariadb/postgresql) 一起工作。