Sub topic 10
Choosing a pruner
This chapter assumes you can write an Optuna objective that calls trial.report and trial.should_prune, as in the previous chapter on pruning. It also assumes your model trains in steps, such as epochs or boosting rounds. Here we cover which pruner to pass to create_study, what each one assumes, and the mistakes that make pruning silently do nothing.
What a pruner decides
A pruner is an object that trial.should_prune() consults. It receives the current trial and the study's history of intermediate values, and it returns True or False. Your objective then raises optuna.TrialPruned. Pruners differ in how they compare the running trial with earlier ones.
If you pass no pruner, Optuna uses MedianPruner. All pruners respect the study direction, so "worse" means lower for maximize and higher for minimize.
The built-in pruners
MedianPruner and PercentilePruner
MedianPruner prunes a trial when its best intermediate value so far is worse than the median of the values earlier trials reported at the same step. Three parameters control when it may act:
n_startup_trials: no pruning until this many trials have completed. The default is 5.n_warmup_steps: no pruning in a trial's first steps. The default is 0.interval_steps: check only every N steps. The default is 1.
PercentilePruner(percentile=25.0) generalises this. It keeps a trial only if it is in the top 25 percent at that step. The median pruner is the 50th-percentile case. Lower percentiles prune harder.
SuccessiveHalvingPruner
Optuna's implementation is asynchronous successive halving. A trial runs for a minimum budget (min_resource). It then continues only if it ranks in the top 1 / reduction_factor of trials that reached the same rung. Surviving trials get reduction_factor times more budget before the next check. Rungs are checked as trials arrive, so workers never wait for each other.
The catch is that the result depends on min_resource. If it is too small, noisy early scores eliminate good trials. The default "auto" estimates it from the first completed trial.
HyperbandPruner
Hyperband runs several successive-halving "brackets" with different min_resource values. Some brackets prune early and some barely prune. This hedges against the case where early scores do not predict final scores. The main parameters are min_resource, max_resource and reduction_factor. Set max_resource to your real step count. With "auto", Optuna infers it from the first completed trial, which can be wrong if that trial was cut short.
Other pruners
| Pruner | Rule | Typical use |
|---|---|---|
| `NopPruner` | Never prunes | Baseline, or disabling pruning without editing the objective |
| `ThresholdPruner` | Prunes if a value leaves `[lower, upper]` | Catching divergence, `nan`, or exploding loss |
| `PatientPruner` | Wraps another pruner and waits `patience` steps | Noisy curves that dip temporarily |
PatientPruner and ThresholdPruner are guards rather than a full strategy. A common combination is PatientPruner(MedianPruner(), patience=3).
Comparing pruners on one problem
The script below runs the same objective under four pruners and counts how many trials each one cut. It needs optuna and scikit-learn.
import numpy as np
import optuna
from optuna.trial import TrialState
from sklearn.datasets import load_digits
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
optuna.logging.set_verbosity(optuna.logging.WARNING)
X, y = load_digits(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(X, y, random_state=0)
classes = np.unique(y)
N_STEPS = 20
def objective(trial):
alpha = trial.suggest_float("alpha", 1e-6, 1e-1, log=True)
clf = SGDClassifier(alpha=alpha, random_state=0)
acc = 0.0
for step in range(N_STEPS):
clf.partial_fit(X_train, y_train, classes=classes)
acc = clf.score(X_val, y_val)
trial.report(acc, step)
if trial.should_prune():
raise optuna.TrialPruned()
return acc
pruners = {
"none": optuna.pruners.NopPruner(),
"median": optuna.pruners.MedianPruner(n_startup_trials=5, n_warmup_steps=5),
"halving": optuna.pruners.SuccessiveHalvingPruner(min_resource=1, reduction_factor=3),
"hyperband": optuna.pruners.HyperbandPruner(
min_resource=1, max_resource=N_STEPS, reduction_factor=3
),
}
for name, pruner in pruners.items():
study = optuna.create_study(
direction="maximize",
sampler=optuna.samplers.TPESampler(seed=42),
pruner=pruner,
)
study.optimize(objective, n_trials=40)
pruned = study.get_trials(states=[TrialState.PRUNED])
print(f"{name:10s} best={study.best_value:.4f} pruned={len(pruned)}/40")Expect none to prune nothing and the others to prune a share of the 40 trials. The best values should be close to each other. Exact counts vary with your library versions. The point of pruning is similar quality for less compute, not a higher score.
Notice that best_value comes only from completed trials. Pruned trials never become the best trial, even if their last reported value was high.
How the pruners decide
The diagram shows the order of checks inside a median-style pruner, which is the simplest of the group.
Every early exit leads to "keep running". A misconfigured median pruner therefore fails by never pruning, not by pruning too much. Check TrialState.PRUNED counts after a run to confirm it is active.
Choosing between them
Work through these questions in order:
- Do you have no intermediate values to report, such as a single
fitcall? Pruning does not apply. You can still report once per cross-validation fold, which gives you steps. - Are the learning curves smooth and roughly rank-preserving? Start with
MedianPruner. It has few settings and a gentle failure mode. - Do you have many trials, a long training budget, and several workers? Try
HyperbandPrunerwith an explicitmax_resource. - Do early scores mislead, as with learning-rate warmup or late-improving schedules? Raise
n_warmup_steps, use a lowerPercentilePruneraggressiveness, or wrap the pruner inPatientPruner. - Do some settings diverge to
nan? Add aThresholdPruner, or handle it in the objective.
Common errors
- Inconsistent steps. Pruners compare values at the same step number. If one trial reports per epoch and another per batch, comparisons are meaningless. Use one step definition throughout.
- Reporting the same step twice. Optuna ignores the second report and logs a warning. Increment the step.
- Forgetting to raise.
should_prune()only returns a boolean. If you do notraise optuna.TrialPruned(), the trial finishes and nothing is saved. - Wrong metric at each step. Report a value on the same scale as the returned value. Reporting training loss while returning validation accuracy leads to confusing pruning.
- Pruning too early. With no warmup, a median pruner may cut a slow starter that would have won. Raise
n_warmup_stepsfirst. - Multi-objective studies.
trial.reportis not supported there, so pruners cannot be used. - Auto resources. With
"auto"formin_resourceormax_resource, the first completed trial sets the scale. Set them explicitly if that trial is unrepresentative.
Exercise
A MedianPruner study with nstartuptrials=10 and n_trials=8 reports zero pruned trials. Why, and what is the fix?
Show answer
Pruning only begins after 10 trials have completed, and the study runs only 8, so the startup condition is never met. Lower nstartuptrials (for example to 3) or increase ntrials. In general, set nstartuptrials well below ntrials.
Exercise
Your objective calls crossvalscore(model, X, y, cv=5) once and returns the mean. Can you add a pruner as it stands? If not, what is the smallest change that makes pruning possible?
Show answer
No, because there are no intermediate values to report. Loop over the folds yourself, call trial.report with the running mean score after each fold using the fold index as the step, and check trial.shouldprune() after each report. Only pruners that act on few steps make sense here, so use a small nwarmup_steps.