Skip to content

Remove prior_mu from compute_sigmas - #6574

Merged
c-bata merged 2 commits into
optuna:masterfrom
not522:fix-compute-sigmas
Apr 6, 2026
Merged

c-bata merged 2 commits into
optuna:masterfrom
not522:fix-compute-sigmas

Conversation

@not522

@not522 not522 commented Mar 25, 2026

Copy link
Copy Markdown
Member

This PR is the same as #6261. The previous PR was closed due to performance concerns. But, after our subsequent discussion, we concluded that the performance changes were small enough to be acceptable.

The followings are copied from #6261.

Motivation

The calculation of sigmas in ParzenEstimator is influenced by the prior's mu, but this is inappropriate for the window computation. This behavior stems from referencing the implementation of hyperopt (hyperopt/hyperopt@5d8b88e).

Description of the changes

This PR removes prior_mu from compute_sigmas.

Benchmark results vary depending on the objective function, and when the optimal values are in the middle of the suggestion ranges, performance slightly deteriorated.

import numpy as np
import matplotlib.pyplot as plt
import optuna

def objective(trial):
    params = np.empty(20)
    for i in range(20):
        params[i] = trial.suggest_float(f"x{i}", -10, 10)
    return np.sum(params ** 2)
    # return np.sum((params - 5) ** 2)

N_STUDIES = 100
N_TRIALS = 100

y = [[] for _ in  range(N_STUDIES)]
for seed in range(N_STUDIES):
    sampler = optuna.samplers.TPESampler(seed=seed)
    study = optuna.create_study(sampler=sampler)
    study.optimize(objective, n_trials=N_TRIALS)
    trials = study.trials
    y[seed].append(trials[0].value)
    for i in range(1, N_TRIALS):
        y[seed].append(min(y[seed][-1], trials[i].value))

y = np.asarray(y)
np.save("master.npy", y)
# np.save("pr.npy", y)
y = np.load("master.npy")
mean = np.mean(y, axis=0)
std = np.std(y, axis=0)
plt.fill_between(range(N_TRIALS), mean + std, mean - std, alpha=0.1)
plt.plot(range(N_TRIALS), mean, label="master")

y = np.load("pr.npy")
mean = np.mean(y, axis=0)
std = np.std(y, axis=0)
plt.fill_between(range(N_TRIALS), mean + std, mean - std, alpha=0.1)
plt.plot(range(N_TRIALS), mean, label="fixed")

plt.xlabel("trial number")
plt.ylabel("loss")
plt.legend()
plt.savefig("sigma.png")

Σx^2 / Σ(x-5)^2

sigma0 sigma5

The internal state of the ParzenEstimator was verified using the following code:

import numpy as np
import matplotlib.pyplot as plt
import optuna
import optunahub

def objective(trial):
    params = np.empty(20)
    for i in range(20):
        params[i] = trial.suggest_float(f"x{i}", -10, 10)
    return np.sum(params ** 2)

module = optunahub.load_module(
    package="visualization/tpe_acquisition_visualizer",
)
tpe_acquisition_visualizer = module.TPEAcquisitionVisualizer()
sampler = optuna.samplers.TPESampler(seed=0)
study = optuna.create_study(sampler=sampler)
study.optimize(objective, n_trials=11, callbacks=[tpe_acquisition_visualizer])
fig = tpe_acquisition_visualizer.plot(study, 10, "x0")
fig.savefig(f"x0_10.png")
plt.close(fig)

master / PR

x0_10_master x0_10_pr

@not522 not522 assigned c-bata and y0z Mar 25, 2026
@not522

not522 commented Mar 25, 2026

Copy link
Copy Markdown
Member Author

@c-bata @y0z Could you review this PR?

@nabenabe0928

nabenabe0928 commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

Just to note from my past experiments:
Performance issue by removing the prior mu is likely to be observed for non-smooth functions.
Namely, benchmarking on some discrete functions and HPO-related datasets would be beneficial to see a potential negative effect.

If this PR retains moderate performance on such scenario, the change itself would be more consistent (and preferable).

@y0z y0z left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@github-actions

github-actions Bot commented Apr 2, 2026

Copy link
Copy Markdown
Contributor

This pull request has not seen any recent activity.

@github-actions github-actions Bot added the stale Exempt from stale bot labeling. label Apr 2, 2026
@c-bata c-bata removed the stale Exempt from stale bot labeling. label Apr 3, 2026

@c-bata c-bata left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@c-bata c-bata added the enhancement Change that does not break compatibility and not affect public interfaces, but improves performance. label Apr 6, 2026
@c-bata c-bata added this to the v4.9.0 milestone Apr 6, 2026
@c-bata
c-bata merged commit c811509 into optuna:master Apr 6, 2026
13 checks passed
@not522
not522 deleted the fix-compute-sigmas branch April 7, 2026 01:05
@nabenabe0928

Copy link
Copy Markdown
Contributor

I tried the current latest and v4.8.0 to benchmark the performance impact.

Results

  • Tested TPESampler with multivariate=True and multivariate=False with the bandwidth heuristic for multivariate=True deactivated over 10 random seeds
  • Used HPOLib, and HPOBench, which contain numerical discrete parameters that should be negatively affected when the bandwidth becomes small
  • Saw almost no significant performance difference (but found significant performance difference in two cases) based on the Wilcoxon's signed rank test

Significant differences were observed at n_trials=100,150 for multivariate=False and,
hpobench4

at n_trials=25 for multivariate=False.
hpolib3

I used the following script:

Experiment Script
from __future__ import annotations

import optuna
from optuna.samplers._tpe.parzen_estimator import _ParzenEstimator
import optunahub


HPOLib = optunahub.load_module("benchmarks/hpolib").Problem
HPOBench = optunahub.load_module("benchmarks/hpobench_nn").Problem

class CustomParzenEstimator(_ParzenEstimator):
    # This class invalidates the weak bandwidth heuristic.
    def __init__(self, observations, search_space, parameters, predetermined_weights=None):
        parameters = parameters._replace(multivariate=False)
        super().__init__(observations, search_space, parameters, predetermined_weights)


def experiment(trial: optuna.Trial) -> float:
    seed = trial.suggest_int("seed", 0, 9)
    multivariate = trial.suggest_categorical("multivariate", [True, False])
    bench_name = trial.suggest_categorical("bench_name", ["hpolib", "hpobench"])
    if bench_name == "hpolib":
        dataset_id = trial.suggest_int("dataset_id", 0, 3)
        problem = HPOLib(dataset_id=dataset_id, seed=seed)
    elif bench_name == "hpobench":
        dataset_id = trial.suggest_int("dataset_id", 0, 7)
        problem = HPOBench(dataset_id=dataset_id, seed=seed)
    else:
        assert False, f"Unknown {bench_name=}"

    sampler = optuna.samplers.TPESampler(multivariate=multivariate, seed=seed)
    sampler._parzen_estimator_cls = CustomParzenEstimator
    study = optuna.create_study(sampler=sampler)
    study.optimize(problem, n_trials=200)
    trial.set_user_attr("results", [float(t.value) for t in study.trials])
    return 0.0


if __name__ == "__main__":
    optuna_version = optuna.__version__
    sampler = optuna.samplers.BruteForceSampler()
    storage = optuna.storages.JournalStorage(optuna.storages.journal.JournalFileBackend("result.log"))
    study = optuna.create_study(
        sampler=sampler, storage=storage, study_name=f"bench-{optuna_version}", load_if_exists=True
    )
    study.optimize(experiment)
Visualization Script
import os

import matplotlib.pyplot as plt
import numpy as np
import optuna
import pandas as pd


plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.size"] = 18


def extract() -> pd.DataFrame:
    file_path = "./extract.json"
    if os.path.exists(file_path):
        return pd.read_json(file_path)
    storage = optuna.storages.JournalStorage(optuna.storages.journal.JournalFileBackend("result.log"))
    results = []
    for v in ["4.8.0", "4.9.0.dev"]:
        for t in optuna.load_study(storage=storage, study_name=f"bench-{v}").trials:
            row = t.params.copy()
            bench_name = row.pop("bench_name")
            dataset_id = row.pop("dataset_id")
            row.update(version=v, dataset_name=f"{bench_name}{dataset_id}", values=t.user_attrs["results"])
            results.append(row)
    res = pd.DataFrame(results)
    res.to_json(file_path)
    return res


def plot_results(
    ax: plt.Axes,
    df: pd.DataFrame,
    multivariate: bool,
    version: str,
    dataset_name: str,
) -> None:
    target = (
        (df["version"] == version)
        & (df["dataset_name"] == dataset_name)
        & (df["multivariate"] if multivariate else ~df["multivariate"])
    )
    # Remove initial samples.
    n_init = 10
    values = np.minimum.accumulate(df[target]["values"].to_list(), axis=-1)[:, n_init:]
    m = np.mean(values, axis=0)
    s = np.std(values, axis=0) / np.sqrt(len(values))
    steps = np.arange(len(m)) + n_init + 1
    color = "darkred" if version == "4.9.0.dev" else "black"
    ls = "dashed" if multivariate else "dotted"
    marker = "*" if multivariate else "s"
    label = f"{multivariate=} ({version[:5]})"
    ax.plot(steps, m, color=color, ls=ls, marker=marker, markevery=20, ms=10, label=label)
    ax.fill_between(steps, m - s, m + s, alpha=0.2, color=color)
    ax.set_xlim(steps[0], steps[-1])


def plot(dataset_name: str) -> None:
    df = extract()
    _, ax = plt.subplots()
    for version in ["4.8.0", "4.9.0.dev"]:
        for multivariate in [True, False]:
            plot_results(ax, df, multivariate, version, dataset_name)

    ax.set_title(dataset_name[:4].upper() + dataset_name[4:-1].lower() + f" (dataset ID: {dataset_name[-1]})")
    ax.set_xlabel("# of Trials")
    ax.set_ylabel("Objective")
    ax.grid(which="minor", color="gray", linestyle=":")
    ax.grid(which="major", color="black")
    ax.legend()
    if dataset_name.startswith("hpolib"):
        ax.set_yscale("log")
    os.makedirs("figs/", exist_ok=True)
    plt.savefig(f"figs/{dataset_name}.png",)


if __name__ == "__main__":
    for i in range(4):
        plot(f"hpolib{i}")
    for i in range(8):
        plot(f"hpobench{i}")
Statistical Test
import os

import numpy as np
import pandas as pd
from scipy.stats import wilcoxon


def extract() -> pd.DataFrame:
    file_path = "./extract.json"
    if os.path.exists(file_path):
        return pd.read_json(file_path)
    raise FileNotFoundError(f"{file_path} not found. Run visualize.py first.")


def get_cummin(df: pd.DataFrame, version: str, dataset_name: str, multivariate: bool) -> np.ndarray:
    mask = (
        (df["version"] == version)
        & (df["dataset_name"] == dataset_name)
        & (df["multivariate"] if multivariate else ~df["multivariate"])
    )
    return np.minimum.accumulate(df[mask]["values"].to_list(), axis=-1)


def wilcoxon_test_per_step(
    df: pd.DataFrame,
    dataset_name: str,
    multivariate: bool,
) -> list[dict]:
    v48 = get_cummin(df, "4.8.0", dataset_name, multivariate)
    v49 = get_cummin(df, "4.9.0.dev", dataset_name, multivariate)
    rows = []
    for t in [24, 49, 99, 149, 199]:
        _, p_value = wilcoxon(v48[:, t], v49[:, t])
        rows.append(dict(dataset_name=dataset_name, n_trials=t + 1, multivariate=multivariate, p_value=p_value))
    return rows


if __name__ == "__main__":
    df = extract()
    dataset_names = sorted(df["dataset_name"].unique())
    rows = []
    for dataset_name in dataset_names:
        for multivariate in [True, False]:
            rows.extend(wilcoxon_test_per_step(df, dataset_name, multivariate))

    results = pd.DataFrame(rows)
    results["significant"] = results["p_value"] < 0.05
    print(results.sort_values(by="p_value").head(15))

Post Edit

I also tried some BBOB functions, but I observed almost no significance.

BBOB Experiment
BBOB = optunahub.load_module("benchmarks/bbob").Problem
INSTANCE_IDS = [1, 2, 3, 4, 5, 71, 72, 73, 74, 75]


def experiment_bbob(trial: optuna.Trial) -> float:
    seed = trial.suggest_int("seed", 0, 9)
    multivariate = trial.suggest_categorical("multivariate", [True, False])
    function_id = trial.suggest_categorical("function_id", [2, 8, 11, 15, 20])
    dim = trial.suggest_categorical("dim", [5, 10])
    problem = BBOB(function_id=function_id, dimension=dim, instance_id=INSTANCE_IDS[seed])
    sampler = optuna.samplers.TPESampler(multivariate=multivariate, seed=seed)
    sampler._parzen_estimator_cls = CustomParzenEstimator
    study = optuna.create_study(sampler=sampler)
    study.optimize(problem, n_trials=200)
    trial.set_user_attr("results", [float(t.value) for t in study.trials])
    return 0.0

@c-bata

c-bata commented May 1, 2026

Copy link
Copy Markdown
Member

@nabenabe0928 Thank you for reporting this! I will discuss with the core devs whether we should revert this PR to fix the performance regression.

@nabenabe0928

nabenabe0928 commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

@c-bata
Hi thank you for the response:)
My summary just says we won't see distinguishable performance difference in most Cases, while we may see it on some cases especially for multivariate=False.
That said, the old version didn't consistently outperform the new version either, justifying the latest implementation (IMO).

@y0z

y0z commented May 12, 2026

Copy link
Copy Markdown
Member

Thank you for sharing your valuable benchmark results. Based on the following points, we do not intend to revert:

  • The original implementation is incorrect, as described in the Motivation section (even if there are a few cases where it works well as a heuristic).
  • We are considering making multivariate=True the default in v5, which would likely resolve performance concerns.
  • Reports indicate that no performance degradation was observed in the more widely adopted BBOB problem set.

Thank you for your understanding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Change that does not break compatibility and not affect public interfaces, but improves performance.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants