Sub topic 14
Making runs reproducible
This chapter assumes you can write an objective function, run a study with a sampler, and use scikit-learn cross-validation. It also assumes you know what a random seed does. Reproducible here means that running the same script twice gives the same trials, the same scores and the same best parameters.
Why reproducibility needs care
An Optuna run involves several separate sources of randomness. Seeding one of them does not make the whole run repeatable. If your objective is noisy, you can also get a different "best" result each time and read the difference as a real improvement.
| Source | Where it lives | How to control it |
|---|---|---|
| Parameter suggestions | The sampler | Pass `seed=` to the sampler |
| Model initialisation and bagging | Your estimator | Pass `random_state=` to the estimator |
| Data splits | Your cross-validation object | Fix `random_state` on the splitter, or avoid shuffling |
| Trial scheduling | `n_jobs` and parallel workers | Run sequentially when you need exact repeatability |
| Libraries and hardware | NumPy, scikit-learn, GPU kernels | Record versions and pin them |
Seed the sampler
The sampler decides which parameters to try next. If you do not give it a seed, it draws from an unseeded random generator, and every run explores a different sequence. Pass a seed when you build the sampler:
import optuna
sampler = optuna.samplers.TPESampler(seed=42)
study = optuna.create_study(direction="maximize", sampler=sampler)The same applies to other samplers. RandomSampler(seed=42) and GridSampler (which is deterministic by construction) behave the same way. The TPE sampler starts with random startup trials and then uses its own generator for candidate sampling. Both draw from the one seed, so a single seed argument is enough.
Seeding the sampler only fixes the suggestions. It does not fix the score you get for a given suggestion. That depends on the objective.
Seed everything inside the objective
The objective must return the same value when called twice with the same parameters. Check three things.
- Every estimator that uses randomness gets a
random_state. Random forests, gradient boosting with subsampling, SGD and neural networks all do. - The data split is fixed. With
cross_val_score(model, X, y, cv=3)on a classifier, scikit-learn usesStratifiedKFoldwithout shuffling, which is deterministic. If you shuffle, setrandom_stateon the splitter. - No hidden randomness comes from your own code, such as a call to
np.random.randor an unseededtrain_test_split.
Here is a complete example that proves repeatability by running the same study twice and comparing every trial:
import optuna
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_score
optuna.logging.set_verbosity(optuna.logging.WARNING)
SEED = 42
X, y = load_iris(return_X_y=True)
cv = StratifiedKFold(n_splits=3, shuffle=True, random_state=SEED)
def objective(trial):
depth = trial.suggest_int("max_depth", 2, 16)
n_trees = trial.suggest_int("n_estimators", 20, 200, step=20)
model = RandomForestClassifier(
max_depth=depth, n_estimators=n_trees, random_state=SEED
)
trial.set_user_attr("seed", SEED)
return cross_val_score(model, X, y, cv=cv).mean()
def run():
sampler = optuna.samplers.TPESampler(seed=SEED)
study = optuna.create_study(direction="maximize", sampler=sampler)
study.optimize(objective, n_trials=20)
return study
first = run()
second = run()
print(first.best_params == second.best_params)
print(first.best_value == second.best_value)
print([t.params for t in first.trials] == [t.params for t in second.trials])All three lines should print True. If one prints False, a source of randomness is not controlled. A good way to find it is to compare the trial lists. If the parameters differ, the sampler is the cause. If the parameters match but the values differ, the objective is the cause.
Parallel runs break the sequence
With a seeded sampler, a sequential run is deterministic because each suggestion depends only on the seed and the finished trials so far. In a parallel run this is no longer true.
When you pass n_jobs greater than 1, or start several worker processes on shared storage, trials finish in an order that depends on timing. TPE bases each suggestion on the trials that have finished when it asks. A different finishing order therefore gives different suggestions, even with the same seed. Workers on shared storage cannot be made repeatable this way.
Pruning adds a similar effect. A pruner compares a trial with other trials' reports. In parallel runs, which reports exist at that moment depends on timing, so which trials get pruned can change from run to run.
Resuming a study does not continue the random sequence
The sampler object is not saved in the storage. A database keeps trials, parameters, values and attributes, but not the generator state. When you reload a study, you must pass a sampler again:
import optuna
study = optuna.load_study(
study_name="svc-tuning",
storage="sqlite:///optuna.db",
sampler=optuna.samplers.TPESampler(seed=42),
)If you do not pass a sampler, Optuna uses a default one with no seed. If you pass one with the same seed, its generator starts from the beginning. The resumed suggestions are therefore not the same as those an uninterrupted run would have made, although the sampler still sees all the old trials. If you want a different random stream after each resume, change the seed, for example by using the number of existing trials: seed=len(study.trials). Choose this deliberately, because reusing the same seed after every resume can repeat early random choices.
Record what you ran
Reproducibility also means that someone else, or you in six months, can find out how a result was produced. Optuna lets you attach this information to the study and to individual trials with user attributes:
import sys
import optuna
import sklearn
study = optuna.create_study(direction="maximize")
study.set_user_attr("optuna_version", optuna.__version__)
study.set_user_attr("sklearn_version", sklearn.__version__)
study.set_user_attr("python_version", sys.version.split()[0])
study.set_user_attr("sampler_seed", 42)
print(study.user_attrs)With a database as storage, these attributes are saved with the study. Keep a pinned requirements file as well. The same seed does not guarantee the same numbers across versions of Optuna, scikit-learn or NumPy, because internal algorithms and default values change between releases.
Reproducing the final model
The point of a study is usually a model you can train again. Do not rely on the study to rebuild it. Take study.best_params, train the final model with those parameters and the same seed, and save the model and the parameters together. This also gives you a clean place to evaluate on a held-out test set, which the study never saw.
Two cautions apply to hardware. GPU training can be non-deterministic even with fixed seeds, because some kernels use atomic operations whose order varies. Multi-threaded libraries can also sum floating-point numbers in different orders. Where this matters, use the deterministic options your framework offers and expect small differences otherwise.
A noisy objective is a reproducibility problem too
Even with all seeds fixed, a single seed gives only one sample of how the model behaves. If two parameter sets differ by less than the noise between seeds, the study's choice of "best" is arbitrary, and a different seed could pick the other one. Two practical remedies:
- Use more cross-validation folds or repeated cross-validation, so the score is an average over more splits.
- After the study, re-evaluate the top few trials with several different seeds and choose by the mean, not by one lucky run.
Exercise
You run a seeded TPE study with n_jobs=4, and two runs of the same script give different best parameters. Name two separate reasons this can happen, and say how you would check each.
Show answer
First, trials finish in a different order because of timing, so the sampler sees a different set of finished trials at each suggestion. Check by running the study again with n_jobs=1; if the two runs now match, scheduling was the cause. Second, the objective may be non-deterministic, for example an estimator without random_state or an unseeded shuffled split. Check by calling the objective twice with the same fixed parameters, or by running sequentially and comparing [t.value for t in study.trials] across runs: matching parameters with different values point to the objective.
Exercise
You stop a seeded study after 50 trials, reload it with load_study and the same TPESampler(seed=42), and run 50 more. Will the result match a single uninterrupted run of 100 trials? Why or why not?
Show answer
No. The sampler's random generator state is not stored in the database. The reloaded sampler starts its generator from the seed again, so its random draws after the resume differ from those the uninterrupted run would have made at trial 50 onward. The earlier 50 trials are still visible to the sampler, but the random stream is restarted.