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

标签 python multithreading gpu optuna

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

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

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 做我想做的事。要将其纳入目标函数,我需要将其定义为 lambda 函数或类(我猜 partial 也可以)。 例如

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)

关于python - 有没有办法将参数传递给 optuna 中的多个工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61763206/

相关文章:

c# - ThreadLocal<T> 和静态方法?

由于 CPU 类型的原因,C++ Boost 多线程比单线程慢?

c# - 使用单独的对象进行同步

python - 使用拼写检查进行查询分段

cuda - Thrust:如何直接控制算法调用的执行位置?

cuda - 如何选择带有 CUDA 的 GPU?

performance - CUDA性能疑虑

python - 我只是想写一个 python 脚本来更改文件目录中的文件名

python - Pandas 在 A 列中搜索最小值,然后在同一行的 B 列中获取值

python - Keras 中的多个输出