Repository navigation
Add qConstrainedLogEHVI in GPSampler - #6804
Conversation
Benchmark (Updated on August 20th)I compared the optimization performance of this PR with that of the master branch through simulations of parallel optimization. The optimization performance was evaluated by plotting the achieved hypervolume against the number of completed trials. Overall, this PR achieved higher hypervolume than the master branch for the same number of completed trials. The benchmark was conducted using the C-DTLZ benchmark problems. Simulation Codefrom __future__ import annotations
import argparse
import itertools
import pickle
import time
from pathlib import Path
from typing import Any
import optuna
import optunahub
from optuna.distributions import (
BaseDistribution,
CategoricalDistribution,
FloatDistribution,
IntDistribution,
)
wfg = optunahub.load_module("benchmarks/wfg")
dtlz_constrained = optunahub.load_module("benchmarks/dtlz_constrained")
def create_problem(
problem_module: str,
function_id: int,
n_objectives: int,
dimension: int,
k: int | None,
constraint_type: int | None,
):
if problem_module == "wfg":
return wfg.Problem(
function_id=function_id,
n_objectives=n_objectives,
dimension=dimension,
k=k,
)
if problem_module == "dtlz_constrained":
if constraint_type is None:
raise ValueError("--constraint-type is required for dtlz_constrained.")
return dtlz_constrained.Problem(
function_id=function_id,
n_objectives=n_objectives,
constraint_type=constraint_type,
dimension=dimension,
)
raise ValueError(f"Unsupported problem_module: {problem_module}")
def set_problem_attrs(
study: optuna.Study,
*,
problem_module: str,
function_id: int,
n_objectives: int,
dimension: int,
k: int | None,
constraint_type: int | None,
) -> None:
study.set_user_attr("problem_module", problem_module)
study.set_user_attr("function_id", function_id)
study.set_user_attr("n_objectives", n_objectives)
study.set_user_attr("dimension", dimension)
if k is not None:
study.set_user_attr("k", k)
if constraint_type is not None:
study.set_user_attr("constraint_type", constraint_type)
def suggest_from_distribution(
trial: optuna.Trial, name: str, dist: BaseDistribution
) -> Any:
if isinstance(dist, FloatDistribution):
return trial.suggest_float(name, dist.low, dist.high, log=dist.log, step=dist.step)
if isinstance(dist, IntDistribution):
return trial.suggest_int(name, dist.low, dist.high, log=dist.log, step=dist.step)
if isinstance(dist, CategoricalDistribution):
return trial.suggest_categorical(name, dist.choices)
raise TypeError(f"Unsupported distribution type for {name}: {type(dist)}")
def suggest_params(
trial: optuna.Trial, search_space: dict[str, BaseDistribution]
) -> dict[str, Any]:
return {
name: suggest_from_distribution(trial, name, dist)
for name, dist in search_space.items()
}
def simulate(
n_workers: int,
n_trials: int,
n_startup_trials: int,
seed: int,
problem_module: str,
function_id: int,
n_objectives: int,
dimension: int,
k: int | None,
constraint_type: int | None,
) -> optuna.Study:
if n_workers <= 0:
raise ValueError("n_workers must be >= 1")
problem = create_problem(
problem_module=problem_module,
function_id=function_id,
n_objectives=n_objectives,
dimension=dimension,
k=k,
constraint_type=constraint_type,
)
sampler_kwargs: dict[str, Any] = dict(
n_startup_trials=n_startup_trials,
seed=seed,
deterministic_objective=True,
)
if hasattr(problem, "constraints_func"):
sampler_kwargs["constraints_func"] = problem.constraints_func
sampler = optuna.samplers.GPSampler(**sampler_kwargs)
# sampler._q_acqf_n_qmc_samples = 128
study = optuna.create_study(directions=problem.directions, sampler=sampler)
start_time = time.perf_counter()
pending: list[tuple[optuna.Trial, dict[str, Any]] | None] = [None] * n_workers
n_suggested = 0
n_completed = 0
for worker_id in itertools.cycle(range(n_workers)):
print(f"Worker {worker_id} is working..., n_suggested={n_suggested}, n_completed={n_completed}")
if n_completed >= n_trials:
break
if pending[worker_id] is not None:
previous_trial, previous_params = pending[worker_id]
value = problem.evaluate(previous_params)
study.tell(previous_trial, value)
pending[worker_id] = None
n_completed += 1
if n_completed >= n_trials:
break
if n_suggested < n_trials:
trial = study.ask()
params = suggest_params(trial, problem.search_space)
trial.set_user_attr("cumtime", time.perf_counter() - start_time)
pending[worker_id] = (trial, params)
n_suggested += 1
trials = [
t
for t in study.trials[n_startup_trials+n_workers-1:]
if t.state == optuna.trial.TrialState.COMPLETE and "cumtime" in t.user_attrs
]
trials = trials[: max(0, n_trials - n_startup_trials - n_workers + 1)]
new_study = optuna.create_study(directions=problem.directions)
new_study.add_trials(trials)
set_problem_attrs(
new_study,
problem_module=problem_module,
function_id=function_id,
n_objectives=n_objectives,
dimension=dimension,
k=k,
constraint_type=constraint_type,
)
return new_study
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--label", required=True)
parser.add_argument("--out-dir", default="./gp_simulator_results_without_evaltime_n5_bbo_dataset10")
parser.add_argument("--n-workers", type=int, default=5)
parser.add_argument("--n-trials", type=int, default=100)
parser.add_argument("--n-startup-trials", type=int, default=10)
parser.add_argument("--n-seeds", type=int, default=10)
parser.add_argument(
"--problem-module",
choices=("wfg", "dtlz_constrained"),
default="wfg",
)
parser.add_argument("--function-id", type=int, default=4)
parser.add_argument("--n-objectives", type=int, default=2)
parser.add_argument("--dimension", type=int, default=3)
parser.add_argument("--k", type=int, default=1)
parser.add_argument("--constraint-type", type=int)
args = parser.parse_args()
study_list: list[optuna.Study] = []
for seed in range(args.n_seeds):
study = simulate(
n_workers=args.n_workers,
n_trials=args.n_trials,
n_startup_trials=args.n_startup_trials,
seed=seed,
problem_module=args.problem_module,
function_id=args.function_id,
n_objectives=args.n_objectives,
dimension=args.dimension,
k=args.k,
constraint_type=args.constraint_type,
)
study_list.append(study)
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"{args.label}.pickle"
with out_path.open("wb") as f:
pickle.dump(study_list, f)
print(f"Saved {len(study_list)} studies to {out_path}")
if __name__ == "__main__":
main()Plot Codefrom __future__ import annotations
import argparse
import pickle
import re
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import optuna
import optunahub
from optuna.visualization._hypervolume_history import _get_hypervolume_history_info
wfg = optunahub.load_module("benchmarks/wfg")
def load_study_list(result_dir: Path, label: str) -> list[optuna.Study]:
path = result_dir / f"{label}.pickle"
with path.open("rb") as f:
study_list = pickle.load(f)
return study_list
def get_style(label: str) -> dict[str, str]:
if label in {"qConstrainedLogEHVI"}:
return {
"color": "red",
"marker": "*",
"ls": "dotted",
"plot_label": "qConstrainedLogEHVI",
}
return {
"color": "blue",
"marker": "s",
"ls": "dashed",
"plot_label": label,
}
def build_plot_title(result_dir: Path) -> str:
name = result_dir.name.lower()
parts: list[str] = []
if "wfg" in name:
function_match = re.search(r"_function(\d+)", name)
objective_match = re.search(r"_n(\d+)", name)
dimension_match = re.search(r"_d(\d+)", name)
k_match = re.search(r"_k(\d+)", name)
benchmark = "WFG"
if function_match:
benchmark += f" Function {function_match.group(1)}"
details = []
if objective_match:
details.append(f"{objective_match.group(1)} objectives")
if dimension_match:
details.append(f"dim={dimension_match.group(1)}")
if k_match:
details.append(f"k={k_match.group(1)}")
parts.append(benchmark)
if details:
parts.append(f"({', '.join(details)})")
else:
dataset_match = re.search(r"dataset(\d+)", name)
dataset_id = dataset_match.group(1) if dataset_match else "unknown"
if "bbo" in name or "bbob" in name:
parts.append(f"BBOB Dataset {dataset_id}")
else:
parts.append(f"HPOBench Dataset {dataset_id}")
worker_match = re.search(r"(?:without_evaltime_|results_)n(\d+)(?:_|$)", name)
if worker_match:
parts.append(f"{worker_match.group(1)} workers")
if "without_evaltime" in name:
parts.append("without evaluation time")
if not parts:
return result_dir.name
return " | ".join(parts)
def create_problem(
function_id: int,
n_objectives: int,
dimension: int,
k: int,
):
return wfg.Problem(
function_id=function_id,
n_objectives=n_objectives,
dimension=dimension,
k=k,
)
def get_reference_point(study_list: list[optuna.Study], args: argparse.Namespace) -> np.ndarray:
attrs = study_list[0].user_attrs
if attrs.get("problem_module") == "wfg":
problem = create_problem(
function_id=int(attrs["function_id"]),
n_objectives=int(attrs["n_objectives"]),
dimension=int(attrs["dimension"]),
k=int(attrs["k"]),
)
return np.asarray(problem.reference_point, dtype=np.float64)
if None not in (args.function_id, args.n_objectives, args.dimension, args.k):
problem = create_problem(
function_id=args.function_id,
n_objectives=args.n_objectives,
dimension=args.dimension,
k=args.k,
)
return np.asarray(problem.reference_point, dtype=np.float64)
raise ValueError(
"Could not determine the WFG problem configuration from the study. "
"Please regenerate the pickle with the updated simulator or pass "
"--function-id, --n-objectives, --dimension, and --k."
)
def get_hypervolume_history(
study: optuna.Study, reference_point: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
if not study._is_multi_objective():
raise ValueError(
"Hypervolume is only available for multi-objective studies, "
f"but got {len(study.directions)} objective(s)."
)
info = _get_hypervolume_history_info(study, reference_point)
return np.asarray(info.trial_numbers, dtype=int), np.asarray(info.values, dtype=float)
def aggregate_histories(
study_list: list[optuna.Study], reference_point: np.ndarray
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
histories = [get_hypervolume_history(study, reference_point) for study in study_list]
all_trial_numbers = sorted({int(trial) for trials, _ in histories for trial in trials})
trial_to_index = {trial_number: i for i, trial_number in enumerate(all_trial_numbers)}
values = np.full((len(histories), len(all_trial_numbers)), np.nan, dtype=float)
for row, (trial_numbers, hv_values) in enumerate(histories):
for trial_number, hv_value in zip(trial_numbers, hv_values):
values[row, trial_to_index[int(trial_number)]] = hv_value
mean = np.nanmean(values, axis=0)
std = np.nanstd(values, axis=0)
return np.asarray(all_trial_numbers, dtype=int), mean, std
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"--result-dir",
default="./gp_simulator_results_without_evaltime_n5_bbo_dataset10",
help="Directory containing pickled study lists.",
)
parser.add_argument(
"--labels",
nargs="+",
required=True,
help="Labels to load, e.g. method-a method-b",
)
parser.add_argument(
"--function-id",
type=int,
help="WFG function id. Used only when the pickle does not include problem metadata.",
)
parser.add_argument(
"--n-objectives",
type=int,
help="Number of WFG objectives. Used only when the pickle does not include problem metadata.",
)
parser.add_argument(
"--dimension",
type=int,
help="WFG search-space dimension. Used only when the pickle does not include problem metadata.",
)
parser.add_argument(
"--k",
type=int,
help="WFG position parameter k. Used only when the pickle does not include problem metadata.",
)
parser.add_argument(
"--output",
default="hypervolume_history.png",
help="Output image path.",
)
args = parser.parse_args()
result_dir = Path(args.result_dir)
_, ax = plt.subplots()
for label in args.labels:
study_list = load_study_list(result_dir, label)
reference_point = get_reference_point(study_list, args)
trial_numbers, mean, std = aggregate_histories(study_list, reference_point)
style = get_style(label)
ax.plot(
trial_numbers,
mean,
color=style["color"],
marker=style["marker"],
linestyle=style["ls"],
markevery=max(1, len(trial_numbers) // 10),
label=style["plot_label"],
)
ax.fill_between(
trial_numbers,
mean - std,
mean + std,
color=style["color"],
alpha=0.2,
)
ax.grid(True, which="major", alpha=0.5)
ax.grid(True, which="minor", alpha=0.2)
ax.set_xlabel("Trial number")
ax.set_ylabel("Hypervolume")
ax.set_title(build_plot_title(result_dir))
ax.legend()
plt.savefig(args.output, bbox_inches="tight")
print(f"Saved to {args.output}")
if __name__ == "__main__":
main()
|
|
Could you separate the changes to another PR?
|
|
The current implementation is suboptimal because we kinda hack the existing internal APIs and the constraint handling leaks into the multi-objective routine. Conceptually speaking, we can isolate by separating some routines. Conditional GP listclass _MultiObjectiveConditionalGPRegressor:
"""Conditional GP samplers for each objective, sharing one set of running trials.
``fantasy_samples`` is shaped ``(n_qmc_samples, n_running, n_objectives)`` and
``sample_candidate_posterior`` returns ``(*x.shape[:-1], n_qmc_samples, n_objectives)``.
"""
def __init__(
self,
gpr_list: list[GPRegressor],
X_running: torch.Tensor,
n_qmc_samples: int,
qmc_seed: int,
stabilizing_noise: float,
) -> None:
self._cond_gpr_list = [
ConditionalGPRegressor(
gpr=gpr,
X_running=X_running,
n_qmc_samples=n_qmc_samples,
qmc_seed=qmc_seed + i,
stabilizing_noise=stabilizing_noise,
)
for i, gpr in enumerate(gpr_list)
]
@property
def n_consumed_qmc_seeds(self) -> int:
# Callers that build further ConditionalGPRegressor instances (e.g. for constraints)
# must offset their seeds by this to avoid sharing a Sobol sequence.
return len(self._cond_gpr_list)
@property
def fantasy_samples(self) -> torch.Tensor:
return torch.stack(
[cond_gpr.get_fantasy_samples() for cond_gpr in self._cond_gpr_list], dim=-1
)
def sample_candidate_posterior(self, x: torch.Tensor) -> torch.Tensor:
return torch.stack(
[
cond_gpr.sample_joint_posterior(x, return_fantasy=False)
for cond_gpr in self._cond_gpr_list
],
dim=-1,
)per-sample Pareto baselineclass _PerSampleParetoBaseline:
"""Per-QMC-sample non-dominated box decomposition of ``Y_baseline`` plus fantasy observations.
``fantasy_samples_per_qmc[i]`` holds the values hallucinated for the running trials in the
i-th QMC sample, shaped ``(n_included_running, n_objectives)``. Callers that must exclude
some fantasy points -- e.g. the ones sampled as infeasible under constraints -- drop them
before constructing this object, so the decomposition stays constraint-agnostic.
"""
def __init__(
self, Y_baseline: torch.Tensor, fantasy_samples_per_qmc: list[torch.Tensor]
) -> None:
self.ref_point = _get_reference_point(Y_baseline)
self._Y_baseline = Y_baseline
self._Y_per_qmc = [
torch.cat([Y_baseline, fantasy], dim=0) if fantasy.shape[0] > 0 else Y_baseline
for fantasy in fantasy_samples_per_qmc
]
bounds = [_get_non_dominated_box_bounds(Y, self.ref_point) for Y in self._Y_per_qmc]
self._non_dominated_box_lower_bounds = torch.nn.utils.rnn.pad_sequence(
[lbs for lbs, _ in bounds], batch_first=True
)
self._non_dominated_box_intervals = torch.nn.utils.rnn.pad_sequence(
[(ubs - lbs).clamp_min_(_EPS) for lbs, ubs in bounds],
batch_first=True,
padding_value=_EPS,
)
def compute_per_sample_log_hvi(self, Y_post: torch.Tensor) -> torch.Tensor:
return _per_sample_log_hvi(
Y_post=Y_post,
non_dominated_box_lower_bounds=self._non_dominated_box_lower_bounds,
non_dominated_box_intervals=self._non_dominated_box_intervals,
)
def compute_per_sample_log_fantasy_hvi(self) -> torch.Tensor:
"""Return ``log HVI(fantasy | Y_baseline)`` per QMC sample, constant w.r.t. the candidate.
Computed on demand rather than in ``__init__`` because only the constrained acqf needs
it and it costs one exact hypervolume computation per QMC sample.
"""
baseline_hv = compute_hypervolume(
_dominating_loss_vals(self._Y_baseline, self.ref_point),
self.ref_point,
assume_pareto=False,
)
hvis = (
np.array(
[
compute_hypervolume(
_dominating_loss_vals(Y, self.ref_point),
self.ref_point,
assume_pareto=False,
)
for Y in self._Y_per_qmc
]
)
- baseline_hv
)
log_hvis = np.full_like(hvis, -np.inf)
np.log(hvis, out=log_hvis, where=hvis > 0.0)
return torch.from_numpy(log_hvis) |
|
@nabenabe0928 Thank you for your feedback! I've updated the implementation accordingly. I'd appreciate it if you could review it once more. |
|
Thanks for the review! Everything should be updated now. PTAL! |
Co-authored-by: Kaito Baba <[email protected]>
|
Thank you for the suggestion. I've applied it! |
|
@sawa3030 |
|
Thank you for letting me know. Updated! |
There was a problem hiding this comment.
LGTM (my manual assessment)
Sonnet's Review
Reviewed PR #6804 (add-constrained-qlogehvi → master). Report saved to .claude_workspace/gh-pr-review/2026-09-02-add-qconstrainedlogehvi.md.
Summary: Pass. I traced the tensor shapes through the new _PerSampleParetoBaseline / ListConditionalGPRegressor refactor and the qLogCEHVI math by hand — it's consistent with the existing qLogEHVI/qLogCEI patterns, no correctness bugs found. ruff, ruff format, mypy are clean on the touched files, and all 61 tests in test_acqf.py pass.
- MUST: none
- SHOULD: the new sampler.py branch wiring
qLogCEHVI(lines 568-582) has no sampler-level integration test, only unit-level acqf coverage — though this mirrors a pre-existing gap for sibling branches, not a new regression - NIT: an unnecessary
if fantasy.shape[0] > 0 else Y_baselinebranch in_PerSampleParetoBaseline.__init__(acqf.py:139) thattorch.catalready handles for free
Positive highlights: good de-duplication via the two new helper classes, a genuinely useful "why" comment justifying the marginal-LogPI fallback via the tower property, and careful independent QMC seeding between objectives and constraints.


Motivation
PR #6792 introduced a Monte Carlo-based acquisition function for multi-objective unconstrained optimization in GPSampler. This PR extends the approach to multi-objective constrained optimization.
Description of the changes
qConstrainedLogEHVI.qConstrainedLogEHVIas the default acquisition function for multi-objective optimization with running trials.Remove constant liar strategy