Sub topic 11
Persisting and resuming studies with a database
This chapter assumes you can write an objective function, create a study and call study.optimize, as covered in earlier chapters. You also need basic familiarity with SQL databases, but you do not need to write any SQL.
Why in-memory studies are not enough
By default, optuna.create_study keeps all trials in the memory of the Python process. When the process ends, the history is gone. That causes three practical problems:
- A crash, a closed notebook or a pre-empted cloud machine loses every finished trial.
- You cannot add 100 more trials tomorrow to a study you ran today without starting from scratch. The sampler would also lose everything it had learned.
- Several processes cannot cooperate on one study, because each has its own private memory.
A storage fixes all three. It is a backend where Optuna writes every study, trial, parameter and value as they happen. The usual choice is a relational database, accessed through an SQLAlchemy-style URL.
Creating a persistent study
Pass a storage URL and a study name to create_study:
import optuna
study = optuna.create_study(
study_name="svc-tuning",
storage="sqlite:///optuna.db",
load_if_exists=True,
direction="maximize",
)Three arguments work together here:
storageis the database URL.sqlite:///optuna.dbcreates or opens the fileoptuna.dbin the current directory. Optuna creates the tables on first use.study_nameis the key that identifies the study inside the database. One database can hold many studies.load_if_exists=Truemakes the call idempotent. If a study with that name exists, Optuna loads it. Otherwise it creates it.
Without load_if_exists=True, a second run raises optuna.exceptions.DuplicatedStudyError. That behaviour is sometimes useful, since it stops you from silently mixing two experiments under one name.
What the database stores
| Stored | Not stored |
|---|---|
| Study name, direction(s), user attributes | Your objective function code |
| Each trial: number, state, parameters, values | The sampler and pruner objects |
| Intermediate values from `trial.report` | Models, data and files your objective creates |
| Trial user attributes and timestamps | Python random state |
The second column matters. The database holds the history, not the logic. When you resume, you must supply the objective function again. You must also pass the sampler and pruner again, with the same configuration you want. If you forget, Optuna falls back to its defaults (TPE with no seed, and a median pruner).
Resuming a study
A complete script that can be run repeatedly looks like this:
import optuna
def objective(trial):
x = trial.suggest_float("x", -10, 10)
return (x - 2) ** 2
study = optuna.create_study(
study_name="quadratic",
storage="sqlite:///optuna.db",
load_if_exists=True,
direction="minimize",
sampler=optuna.samplers.TPESampler(seed=42),
)
print("Trials already stored:", len(study.trials))
study.optimize(objective, n_trials=20)
print("Trials now stored:", len(study.trials))
print("Best value:", study.best_value)Run it three times. The first run reports 0 trials stored and ends with 20. The second starts at 20 and ends at 40. The n_trials argument counts trials for that call to optimize, not for the whole study. The TPE sampler reads all stored trials when it proposes the next one, so each run continues from what earlier runs learned.
If you only want to read a study and not create it, use load_study:
import optuna
study = optuna.load_study(study_name="quadratic", storage="sqlite:///optuna.db")
print(study.best_params)
print(len(study.trials))load_study raises KeyError if the study does not exist. The sampler argument is available here too, which matters if you plan to call optimize on the loaded study.
Inspecting what is stored
You can list the studies in a database without loading each one:
import optuna
for summary in optuna.get_all_study_summaries(storage="sqlite:///optuna.db"):
print(summary.study_name, summary.n_trials, summary.best_trial)For a loaded study, study.trials_dataframe() returns a pandas DataFrame with one row per trial. This requires pandas. The columns include number, value, state, datetime_start and one params_* column per parameter. The state column is worth checking. A trial is COMPLETE, PRUNED, FAIL or RUNNING, and best_value only considers complete trials.
To remove a study, call optuna.delete_study(study_name="quadratic", storage="sqlite:///optuna.db"). This is irreversible, so confirm the name first.
Interrupted trials
If a process is killed in the middle of a trial, the database keeps that trial in the RUNNING state forever. It never becomes COMPLETE and the sampler cannot use it. With a single process this is only untidy. With a cluster of workers it can hide lost work.
The RDBStorage class can detect dead trials with a heartbeat. Each running trial periodically updates a timestamp. When a trial misses its heartbeat for longer than the grace period, Optuna marks it as failed. A callback can then re-queue it:
import optuna
from optuna.storages import RDBStorage, RetryFailedTrialCallback
storage = RDBStorage(
url="sqlite:///optuna.db",
heartbeat_interval=60,
grace_period=120,
failed_trial_callback=RetryFailedTrialCallback(max_retry=3),
)
study = optuna.create_study(
study_name="quadratic",
storage=storage,
load_if_exists=True,
direction="minimize",
)Here a worker that dies is detected after about two minutes, and its parameters are retried up to three times. Choose grace_period longer than the heartbeat interval, and make sure your heartbeat is not so frequent that it loads the database.
Choosing a backend
| Backend | URL example | Use it when |
|---|---|---|
| In memory (default) | none | Quick experiments you can afford to lose |
| SQLite | `sqlite:///optuna.db` | One machine, one or a few processes, resuming later |
| PostgreSQL | `postgresql://user:pw@host/dbname` | Many workers on several machines |
| MySQL | `mysql://user:pw@host/dbname` | Same as PostgreSQL, if your team already runs it |
SQLite locks the whole file during writes. With many parallel workers you may see database is locked errors or slow trials. Network databases handle concurrent writers properly. The next chapter covers parallel runs in more detail. Server databases also need their Python driver installed, such as psycopg2 for PostgreSQL.
Pitfalls when resuming
- Changed direction. Resuming a
maximizestudy withdirection="minimize"is rejected by Optuna with an error. The direction is fixed when the study is created. - Changed search space. Stored trials keep the parameter ranges they used. If you widen or rename a parameter, old trials may not fit the new space. Samplers can ignore such trials, so the search learns less than you expect. For a real change of space, start a new study name.
- Changed objective. Optuna cannot tell that your metric, data split or preprocessing changed between runs. Mixing old and new values in one study gives meaningless comparisons. Treat a changed objective as a new study.
- Lost sampler seed. A seeded sampler gives repeatable runs only when the whole history is produced by the same sequence of calls. A resumed run with
seed=42starts its random stream again from the seed, so the result differs from one uninterrupted run of the same length. - Forgetting the pruner. The pruner is not stored. A resumed study without it runs every trial to the end.
Exercise
You run a script that creates a study with study_name="exp1", storage="sqlite:///optuna.db" and load_if_exists=True, then calls study.optimize(objective, n_trials=25). You run the script four times. How many trials does the study hold at the end, and what would happen on the second run if you had left out load_if_exists=True?
Show answer
The study holds 100 trials, because each call to optimize adds 25 and the stored history carries over. Without load_if_exists=True, the second run would raise DuplicatedStudyError, because a study named "exp1" already exists in the database.
Exercise
After resuming a study you notice it no longer prunes trials, although the first run did. The objective function is unchanged and still calls trial.should_prune(). What is the likely cause?
Show answer
The pruner is not saved in the database. The resumed create_study call did not pass the pruner argument, so Optuna used its default pruner instead of the one from the first run. Pass the same pruner again on every run.