MedianPruner leaks numpy's "All-NaN slice encountered" RuntimeWarning when a trial reports only NaN intermediate values
Expected behavior
When a trial reports only NaN intermediate values, MedianPruner (and PercentilePruner in general) prunes the trial, which is correct. But while deciding, it lets numpy's RuntimeWarning: All-NaN slice encountered escape to the user's console/logs. The pruner already handles the all-NaN case correctly (NaN propagates and the trial is pruned), so no warning should be emitted — a user monitoring warnings (or running with -W error) gets noise/failures from a code path that is working as intended.
The warning comes from _get_best_intermediate_result_over_steps in optuna/pruners/_percentile.py, which calls np.nanmin / np.nanmax on the trial's intermediate values without guarding the all-NaN case.
Notably, the test suite itself has to suppress exactly this warning (tests/pruners_tests/test_percentile.py::test_get_best_intermediate_result_over_steps wraps the all-NaN case in warnings.simplefilter("ignore", category=RuntimeWarning)), so the leak is known — it just isn't fixed at the source.
Environment
- Optuna version: 5.0.0 (also reproduced on current
master) - Python version: 3.12.10
- OS: Windows 11 (not OS-specific)
Error messages, stack traces, or logs
RuntimeWarning: All-NaN slice encountered
...\optuna\pruners\_percentile.py:26: RuntimeWarning: All-NaN slice encounteredSteps to reproduce
import math
import warnings
import optuna
optuna.logging.set_verbosity(optuna.logging.ERROR)
def objective(trial):
healthy = trial.number == 0
for step in range(3):
trial.report(0.5 if healthy else math.nan, step)
if trial.should_prune():
raise optuna.TrialPruned()
return 0.5
study = optuna.create_study(
pruner=optuna.pruners.MedianPruner(n_startup_trials=1, n_warmup_steps=0)
)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
study.optimize(objective, n_trials=2)
print([t.state.name for t in study.trials]) # ['COMPLETE', 'PRUNED'] — pruning is correct
for w in caught:
if issubclass(w.category, RuntimeWarning):
print("LEAKED:", w.message, f"({w.filename}:{w.lineno})")Output on 5.0.0:
['COMPLETE', 'PRUNED']
LEAKED: All-NaN slice encountered (...\optuna\pruners\_percentile.py:26)Additional context (optional)
The fix is small: return NaN directly from _get_best_intermediate_result_over_steps when all values are NaN (preserving the ValueError for the empty case), and tighten the existing test from simplefilter("ignore") to simplefilter("error") so the leak can't come back. I have this ready and will open a PR right after filing this issue.
Source: optuna/optuna