Sub topic 12
Running trials in parallel
Each trial in a study is independent, so you can run several at once and finish a search sooner. This chapter covers the two ways to do that in Optuna, how the shared storage coordinates workers, and the problems that appear when many workers sample from the same study.
It assumes you can write an objective function, create a study, and use a database storage as shown in the earlier chapters. It also assumes you know what a Python thread and a Python process are.
Why parallel trials need care
Sequential search has an advantage. Each new trial is chosen after seeing every earlier result. Run trials in parallel and a sampler such as TPE must pick new parameters while other trials are still running and have no result yet. You gain wall-clock speed but give up some sampling quality.
Optuna offers two models:
| Approach | How it works | Best for | Limits |
|---|---|---|---|
| `n_jobs` in `study.optimize` | Several threads in one process | Objectives that release the GIL, such as NumPy, scikit-learn with C code, or I/O | Python code that holds the GIL gains little. All threads share one process's memory. |
| Several processes or machines on one shared storage | Each worker calls `optimize` on the same named study | CPU-bound training, many cores, multiple machines | Needs a database or journal storage. Needs setup. |
Thread-based parallelism with n_jobs
Add n_jobs to optimize. Optuna starts that many threads, and each one runs trials.
import optuna
def objective(trial):
x = trial.suggest_float("x", -10, 10)
return (x - 2) ** 2
study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=100, n_jobs=4)
print(len(study.trials))
print(study.best_params)n_trials=100 is the total for this call, not per thread. Use n_jobs=-1 to use all CPU cores.
Threads in CPython share the global interpreter lock (GIL). If your objective is pure Python, the threads take turns and you see little speed-up. Training that runs in compiled code, such as many scikit-learn estimators, often gets a real gain. If you measure no speed-up, switch to processes.
Process-based parallelism with shared storage
The scalable pattern is to start the same script several times. Every copy connects to the same storage and the same study name. The storage hands each worker a unique trial number and records every result, so each worker's sampler can see what the others have finished.
The next script is a worker. Any number of copies can run at once.
# worker.py
import os
import optuna
from optuna.study import MaxTrialsCallback
from optuna.trial import TrialState
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
X, y = load_iris(return_X_y=True)
def objective(trial):
c = trial.suggest_float("svc_c", 1e-3, 1e3, log=True)
gamma = trial.suggest_float("svc_gamma", 1e-4, 1e1, log=True)
return cross_val_score(SVC(C=c, gamma=gamma), X, y, cv=3).mean()
if __name__ == "__main__":
storage = os.environ.get("OPTUNA_STORAGE", "sqlite:///optuna.db")
study = optuna.create_study(
study_name="svc-parallel",
storage=storage,
direction="maximize",
load_if_exists=True,
)
study.optimize(
objective,
callbacks=[MaxTrialsCallback(100, states=(TrialState.COMPLETE,))],
)Start four workers from a shell:
for i in 1 2 3 4; do python worker.py & done
waitAfterwards, read the combined result from any process:
import optuna
study = optuna.load_study(
study_name="svc-parallel", storage="sqlite:///optuna.db"
)
print(len(study.trials))
print(study.best_value)
print(study.best_params)Three details in worker.py matter:
load_if_exists=Truelets the first worker create the study and the others join it. Without it, the second worker fails because the name is already taken.n_trialscounts only the calling process. Four workers withn_trials=100would run 400 trials. Hereoptimizehas non_trials, andMaxTrialsCallbackstops each worker once 100 trials are complete across all workers.- Trials that were already running when the limit was reached still finish, so the total can end slightly above 100.
Choosing the storage
| Storage | Parallel use | Notes |
|---|---|---|
| In-memory (default) | Threads only | Lost when the process ends. Other processes cannot see it. |
| SQLite file | A few local processes | Locks the whole file on writes. Under heavy load you can see "database is locked" errors. |
| PostgreSQL or MySQL | Many processes and machines | Recommended for serious parallel and distributed runs. Needs a driver such as `psycopg2`. |
| `JournalStorage` with a file backend | Several processes | Appends to a log file. Avoids running a database server. It needs a file system with working file locks, which many network file systems do not have. |
For a database server, change only the URL, for example postgresql://user:password@host/optuna. The worker code stays the same. This is why worker.py reads the URL from an environment variable.
How parallelism affects the sampler
With TPE, trials that are still running have no objective value, so the sampler cannot learn from them. Several workers starting together can propose nearly identical parameters. Two things reduce this:
- Keep the number of workers small compared with the number of trials. Eight workers on 1,000 trials hurt little. Eight workers on 20 trials behave much like random search.
- Try
optuna.samplers.TPESampler(constant_liar=True). It treats running trials as if they already had a poor value, which pushes new proposals away from them. Check your Optuna version's documentation, because this option is marked experimental in some releases.
Pruning works unchanged. Each worker calls trial.report and trial.should_prune, and the pruner compares against reports from all workers in the storage.
Failed and stalled trials
If a worker is killed, its trial stays in the RUNNING state forever, because nobody marks it as failed. Optuna supports heartbeats on database storage to detect this.
import optuna
from optuna.storages import RDBStorage, RetryFailedTrialCallback
storage = RDBStorage(
"sqlite:///optuna.db",
heartbeat_interval=60,
grace_period=120,
failed_trial_callback=RetryFailedTrialCallback(max_retry=3),
)
study = optuna.create_study(
study_name="svc-parallel",
storage=storage,
direction="maximize",
load_if_exists=True,
)A running trial sends a heartbeat every 60 seconds. If no heartbeat arrives for 120 seconds, another worker marks the trial as failed, and the callback re-enqueues it up to three times. Without a heartbeat, count only COMPLETE trials when you decide whether a study is finished.
Pitfalls
- Thread safety of your objective. With
n_jobs, several threads runobjectiveat once. Do not write to a shared global list or model object inside it. - Seeds. A seeded sampler does not make a parallel run reproducible, because the order in which workers finish changes what each sampler sees. Seed the sampler in each worker if you want less randomness, but expect different results from run to run.
- Resource contention. Four workers that each use all CPU cores via
n_jobs=-1inside scikit-learn fight over the cores. Give each worker a fixed share, for example four workers with one core each. - GPU memory. Each process loads its own copy of the model. Set one worker per GPU, using an environment variable such as
CUDA_VISIBLE_DEVICES.
Exercise
You start 4 workers, and each calls study.optimize(objective, n_trials=50) on the same named study in a shared database. How many trials does the study hold at the end, and how would you cap it at 50 in total?
Show answer
About 200 trials, because n_trials applies to each call, not to the study. To cap the total at 50, call optimize without n_trials and pass callbacks=[MaxTrialsCallback(50, states=(TrialState.COMPLETE,))] in every worker. The total can pass 50 slightly, because trials already running when the limit is reached still finish.
Exercise
A worker process is killed with kill -9 while it runs a trial. Which state does that trial stay in, and which storage setting lets Optuna recover from this?
Show answer
The trial stays in the RUNNING state. Configure RDBStorage with heartbeat_interval and grace_period, and optionally failed_trial_callback=RetryFailedTrialCallback(max_retry=3). A live worker then marks the stale trial as failed and can re-enqueue it.