Sub topic 9
Pruning with trial.report and trial.should_prune
Some trials are obviously bad after a few steps. A learning rate that is far too high, for example, produces a flat or diverging validation curve almost at once. Pruning lets Optuna stop such a trial early and spend the saved time on other candidates. This chapter covers the two calls that make pruning work, the pruner that makes the decision, and the mistakes that cause pruning to silently do nothing.
This chapter assumes you can write an Optuna objective function and run study.optimize. It also assumes you know what an epoch or training step is, and that you can train a model incrementally.
What pruning needs from your code
A pruner can only judge a trial by its intermediate results, so your objective must produce them. That means the model has to train in stages, such as epochs, boosting rounds or batches of partial_fit. A model fitted in a single call, like a plain RandomForestClassifier.fit, offers no checkpoints, so there is nothing to prune.
Pruning needs three things:
- A loop that trains one step at a time.
trial.report(value, step)after each step, to record the metric.trial.should_prune()to ask the study's pruner for a verdict. If it returnsTrue, you raiseoptuna.TrialPruned().
Optuna never interrupts your code. The pruner only answers a question, and your objective decides whether to stop.
A complete example
This script tunes the regularisation strength alpha of an SGDClassifier. Each call to partial_fit is one step, and the validation accuracy after it is the intermediate value.
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
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)
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(20):
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
pruner = optuna.pruners.MedianPruner(n_startup_trials=5, n_warmup_steps=5)
study = optuna.create_study(direction="maximize", pruner=pruner)
study.optimize(objective, n_trials=30)
pruned = study.get_trials(states=[TrialState.PRUNED])
complete = study.get_trials(states=[TrialState.COMPLETE])
print(f"complete: {len(complete)}, pruned: {len(pruned)}")
print("best:", study.best_value, study.best_params)The exact counts vary with the data and library version. The point is that some trials end with state PRUNED after fewer than 20 steps. A pruned trial has no final value, so study.best_trial only ever picks from completed trials.
What each call does
trial.report(value, step) stores value as the intermediate value for that step. Three details matter:
stepmust be an integer, and each step should be reported once. Reporting the same step again is ignored with a warning, so the first value stays.- The value must be on the same scale and in the same direction as the metric you return at the end. Do not report loss and return accuracy.
- Reporting alone prunes nothing. It only records data.
trial.should_prune() hands the trial's recorded history to the pruner and returns a boolean. It reads the study's direction, so a MedianPruner in a maximize study treats low values as bad.
raise optuna.TrialPruned() is how you stop. study.optimize catches the exception and marks the trial PRUNED. If you forget to raise and just carry on, the trial wastes time and is recorded as complete.
How MedianPruner decides
MedianPruner compares a trial against earlier trials at the same step. At step s, it prunes if the trial's best intermediate value so far is worse than the median of the values that earlier trials reported at step s. It is simple and works well as a default.
| Parameter | Default | Effect |
|---|---|---|
| `n_startup_trials` | 5 | No trial is pruned until this many trials have completed. This builds the baseline. |
| `n_warmup_steps` | 0 | Steps below this number are never pruned. Use it when early values are noisy. |
| `interval_steps` | 1 | Check for pruning only every N steps after the warmup. |
In the example, n_startup_trials=5 means the first five trials always run to the end. Trials from the sixth onward can be pruned, but only at step 5 or later.
Pruning and the sampler
Pruned trials are not thrown away. Their intermediate values are stored with the trial, and TPE-style samplers use the last reported value of a pruned trial as evidence about the region of the search space it came from. So pruning does not blind the sampler to bad regions. It lets the sampler learn about them cheaply.
Common problems
Nothing is ever pruned. Check these causes in order:
should_prune()is never called, or its result is not used to raiseTrialPruned.n_startup_trialsis larger than the number of trials you run.n_warmup_stepsis at least as large as your number of steps.- Your study uses the default pruner. The default for
create_studyisMedianPruner, but if you passedoptuna.pruners.NopPruner(), pruning is disabled by design.
Good trials get pruned. A metric that starts low and improves late, such as a model with a long warmup, looks bad against the median early on. Raise n_warmup_steps, or choose a more tolerant pruner, as described in the next chapter.
Pruning in multi-objective studies. should_prune is not supported when a study has more than one objective. Calling it there raises an error, so use pruning only in single-objective studies.
Reporting on mixed scales. If you report training loss at some steps and validation accuracy at others, the pruner compares unlike numbers. Report one metric consistently.
Pruning with cross-validation
A common case is cross_val_score, which fits all folds in one call and offers no checkpoint. You have two options. You can loop over folds yourself and report the running mean of the folds so far, using the fold index as the step. Or you can drop pruning for that model and rely on the sampler alone. The first option works, but fold results can differ a lot, so a median comparison at step 0 or 1 is noisy. Set n_warmup_steps to at least 1 so that a single fold cannot end a trial.
Exercise
Your study uses MedianPruner(nstartuptrials=10, nwarmupsteps=3) and runs 8 trials with 20 steps each. How many trials will be pruned, and why? What would you change to enable pruning?
Show answer
None will be pruned. The pruner waits until 10 trials have completed, and the study only runs 8, so no baseline exists and every trial runs all 20 steps. To enable pruning, lower nstartuptrials (for example to 3) or run more than 10 trials. Also check that the objective calls trial.should_prune() and raises optuna.TrialPruned() when it returns True.
Exercise
A colleague's objective calls trial.report(loss, step) each epoch but never calls trial.should_prune(). The study still shows every trial as COMPLETE. Explain why, and show the two lines to add inside the loop.
Show answer
trial.report only records the intermediate value. The pruner is consulted only when shouldprune() is called, and a trial only stops when the objective raises TrialPruned. Add these lines after the report call inside the loop: if trial.shouldprune(): raise optuna.TrialPruned()