Sub topic 12
Running trials in parallel
This chapter assumes you can write an objective function and that you know how to persist a study in a database. Here you will run several trials at once, either in threads or in separate processes.
Two ways to parallelise
study.optimize accepts an n_jobs argument. It runs trials in threads inside one Python process. Because of the Global Interpreter Lock, this only speeds things up when the objective spends its time in code that releases the lock, such as many NumPy or scikit-learn routines. For pure Python objectives it gives little gain.
The more reliable approach is to start several worker processes that share one study through a database. Each worker calls optimize on the same study, and the shared storage hands out trial numbers and records the results.
A worker script
Save this as worker.py:
import optuna
def objective(trial):
x = trial.suggest_float("x", -10, 10)
y = trial.suggest_float("y", -10, 10)
return (x - 2) ** 2 + (y + 1) ** 2
if __name__ == "__main__":
sampler = optuna.samplers.TPESampler(constant_liar=True)
study = optuna.create_study(
study_name="parallel-demo",
storage="sqlite:///parallel.db",
load_if_exists=True,
direction="minimize",
sampler=sampler,
)
study.optimize(objective, n_trials=25)
print(len(study.trials), study.best_value)Start it in three terminals, or run python worker.py & three times in a shell. Every process uses the same study_name and storage, so they all add to one study.
Things that change when you parallelise
n_trialsis per worker. Three workers withn_trials=25produce about 75 trials in total. To cap the total, usetimeout, or stop workers whenlen(study.trials)reaches your limit.- Running trials have no result yet. The TPE sampler learns from finished trials, so workers started together may propose similar points. Setting
constant_liar=Truemakes TPE treat running trials as if they had a pessimistic value. This spreads the workers out. - Seeds need care. If every worker builds its sampler with the same
seed, the workers can propose identical early trials. Give each worker a different seed, or leave the seed unset. - Pruning still works. Reported values are written to storage, so a pruner can compare a trial against trials from other workers.
- Choose storage for the load. SQLite is fine on one machine with a few workers, but heavy concurrent writes can cause "database is locked" errors. For many workers or several machines, use PostgreSQL or MySQL.
Exercise
You start four worker processes on one study. Each calls study.optimize(objective, n_trials=50). Roughly how many trials does the study contain at the end, and why might a TPE study produce poorer suggestions early on than a single-worker run?
Show answer
About 200 trials, because n_trials applies to each worker separately. Early on, several trials are running at once without results. TPE only learns from finished trials, so workers may propose similar points. Using constant_liar=True reduces this effect.