Repository navigation
Speed up non-dominated sort - #5302
Conversation
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #5302 +/- ##
==========================================
+ Coverage 89.33% 89.60% +0.26%
==========================================
Files 196 210 +14
Lines 12653 13288 +635
==========================================
+ Hits 11304 11907 +603
- Misses 1349 1381 +32 ☔ View full report in Codecov by Sentry. |
|
I also tried the Kung's algorithm, which is supposed to have the time complexity of Comparison with the Kung's Algorithmimport time
import numpy as np
def kung(unique_lexsorted_loss_values: np.ndarray, vectorization: bool) -> np.ndarray:
if unique_lexsorted_loss_values.shape[0] == 1:
return np.array([0])
n_points = unique_lexsorted_loss_values.shape[0]
mid = n_points // 2
top_non_dominated_indices = kung(unique_lexsorted_loss_values[:mid], vectorization)
bottom_non_dominated_indices = kung(unique_lexsorted_loss_values[mid:], vectorization)
top_non_dominated_values = unique_lexsorted_loss_values[:mid][top_non_dominated_indices]
bottom_non_dominated_values = unique_lexsorted_loss_values[mid:][bottom_non_dominated_indices]
bottom_non_dominated_by_top_indices = np.arange(n_points - mid)[bottom_non_dominated_indices]
if vectorization:
non_dominated = np.all(
np.any(
bottom_non_dominated_values[:, np.newaxis] < top_non_dominated_values,
axis=-1,
), axis=-1
)
bottom_non_dominated_by_top_indices = bottom_non_dominated_by_top_indices[non_dominated]
else:
for loss_values in top_non_dominated_values:
non_dominated = np.any(bottom_non_dominated_values < loss_values, axis=-1)
bottom_non_dominated_values = bottom_non_dominated_values[non_dominated]
bottom_non_dominated_by_top_indices = bottom_non_dominated_by_top_indices[
non_dominated
]
pareto_indices = np.hstack([
top_non_dominated_indices,
mid + bottom_non_dominated_by_top_indices,
])
return pareto_indices
if __name__ == "__main__":
rng = np.random.RandomState(42)
x = rng.normal(size=(10000, 3))
y = np.unique(x, axis=0)
start = time.time()
pareto_indices = kung(y, vectorization=True)
print(f"Kung with vectorization: {time.time() - start}")
start = time.time()
pareto_indices = kung(y, vectorization=False)
print(f"Kung with loop: {time.time() - start}")
start = time.time()
ans = is_pareto_front_nd(y)
print(f"Original: {time.time() - start}")
output = np.zeros(y.shape[0], dtype=bool)
output[pareto_indices] = True
assert np.all(output == ans), y[np.where(output != ans)[0]]
|
|
@contramundum53 @gen740 Could you review this PR? |
|
Here is the verification code: Important Please check In my environment, the following verification does not fail, which means that I get the identical behavior. Verification Coderesults = {"original": [0.0] * 4, "this_pr": [0.0] * 4}
n_seeds = 3
for seed in range(n_seeds):
for n_samples in [1, 100, 10000]:
for n_below_div in [1, 10]:
n_below = (n_samples + n_below_div - 1) // n_below_div
for n_objectives in [1, 2, 3, 4]:
rt_this_pr, rt_original = verify(seed, n_samples, n_below, n_objectives)
if n_samples == 10000 and n_below_div == 1:
results["original"][n_objectives - 1] += rt_original / n_seeds
results["this_pr"][n_objectives - 1] += rt_this_pr / n_seeds
print(f"{results=} for n_samples=10000")Running Log |
153909f to
0bf8a1b
Compare
Co-authored-by: contramundum53 <[email protected]>
0bf8a1b to
9714d4a
Compare
…non-dominated-sort
Co-authored-by: Gen <[email protected]>
|
This pull request has not seen any recent activity. |
|
@not522 Could you review this PR? |
|
This pull request has not seen any recent activity. |
There was a problem hiding this comment.
LGTM. I followed discussion and reviewed the code. Additionally I independently implemented a program to test, and no error was detected.
Used Implementations
from __future__ import annotations
from collections import defaultdict
from collections.abc import Sequence
import numpy as np
import optuna
from optuna.study._study_direction import StudyDirection
from optuna.trial import FrozenTrial
from optuna.trial import TrialState
_CONSTRAINTS_KEY = "constraints"
def _get_feasible_trials(trials: Sequence[FrozenTrial]) -> list[FrozenTrial]:
feasible_trials = []
for trial in trials:
constraints = trial.system_attrs.get(_CONSTRAINTS_KEY)
if constraints is None or all([x <= 0.0 for x in constraints]):
feasible_trials.append(trial)
return feasible_trials
def _get_pareto_front_trials_2d(
trials: Sequence[FrozenTrial],
directions: Sequence[StudyDirection],
consider_constraint: bool = False,
) -> list[FrozenTrial]:
trials = [t for t in trials if t.state == TrialState.COMPLETE]
if consider_constraint:
trials = _get_feasible_trials(trials)
n_trials = len(trials)
if n_trials == 0:
return []
trials.sort(
key=lambda trial: (
_normalize_value(trial.values[0], directions[0]),
_normalize_value(trial.values[1], directions[1]),
),
)
last_nondominated_trial = trials[0]
pareto_front = [last_nondominated_trial]
for i in range(1, n_trials):
trial = trials[i]
if _dominates(last_nondominated_trial, trial, directions):
continue
pareto_front.append(trial)
last_nondominated_trial = trial
pareto_front.sort(key=lambda trial: trial.number)
return pareto_front
def _get_pareto_front_trials_nd(
trials: Sequence[FrozenTrial],
directions: Sequence[StudyDirection],
consider_constraint: bool = False,
) -> list[FrozenTrial]:
pareto_front = []
trials = [t for t in trials if t.state == TrialState.COMPLETE]
if consider_constraint:
trials = _get_feasible_trials(trials)
# TODO(vincent): Optimize (use the fast non dominated sort defined in the NSGA-II paper).
for trial in trials:
dominated = False
for other in trials:
if _dominates(other, trial, directions):
dominated = True
break
if not dominated:
pareto_front.append(trial)
return pareto_front
def _get_pareto_front_trials_by_trials_old(
trials: Sequence[FrozenTrial],
directions: Sequence[StudyDirection],
consider_constraint: bool = False,
) -> list[FrozenTrial]:
if len(directions) == 2:
return _get_pareto_front_trials_2d(
trials, directions, consider_constraint
) # Log-linear in number of trials.
return _get_pareto_front_trials_nd(
trials, directions, consider_constraint
) # Quadratic in number of trials.
def _get_pareto_front_trials_old(
study: "optuna.study.Study", consider_constraint: bool = False
) -> list[FrozenTrial]:
return _get_pareto_front_trials_by_trials_old(
study.trials, study.directions, consider_constraint
)
def _fast_non_dominated_sort_old(
objective_values: np.ndarray,
*,
penalty: np.ndarray | None = None,
n_below: int | None = None,
) -> np.ndarray:
"""Perform the fast non-dominated sort algorithm.
The fast non-dominated sort algorithm assigns a rank to each trial based on the dominance
relationship of the trials, determined by the objective values and the penalty values. The
algorithm is based on `the constrained NSGA-II algorithm
<https://doi.org/10.1109/4235.99601>`_, but the handling of the case when penalty
values are None is different. The algorithm assigns the rank according to the following
rules:
1. Feasible trials: First, the algorithm assigns the rank to feasible trials, whose penalty
values are less than or equal to 0, according to unconstrained version of fast non-
dominated sort.
2. Infeasible trials: Next, the algorithm assigns the rank from the minimum penalty value of to
the maximum penalty value.
3. Trials with no penalty information (constraints value is None): Finally, The algorithm
assigns the rank to trials with no penalty information according to unconstrained version
of fast non-dominated sort. Note that only this step is different from the original
constrained NSGA-II algorithm.
Plus, the algorithm terminates whenever the number of sorted trials reaches n_below.
Args:
objective_values:
Objective values of each trials.
penalty:
Constraints values of each trials. Defaults to None.
n_below: The minimum number of top trials required to be sorted. The algorithm will
terminate when the number of sorted trials reaches n_below. Defaults to None.
Returns:
An ndarray in the shape of (n_trials,), where each element is the non-dominated rank of
each trial. The rank is 0-indexed and rank -1 means that the algorithm terminated before
the trial was sorted.
"""
if penalty is None:
ranks, _ = _calculate_nondomination_rank_old(objective_values, n_below=n_below)
return ranks
if len(penalty) != len(objective_values):
raise ValueError(
"The length of penalty and objective_values must be same, but got "
"len(penalty)={} and len(objective_values)={}.".format(
len(penalty), len(objective_values)
)
)
nondomination_rank = np.full(len(objective_values), -1)
is_penalty_nan = np.isnan(penalty)
n_below = n_below or len(objective_values)
# First, we calculate the domination rank for feasible trials.
is_feasible = np.logical_and(~is_penalty_nan, penalty <= 0)
ranks, bottom_rank = _calculate_nondomination_rank_old(
objective_values[is_feasible], n_below=n_below
)
nondomination_rank[is_feasible] += 1 + ranks
n_below -= np.count_nonzero(is_feasible)
# Second, we calculate the domination rank for infeasible trials.
is_infeasible = np.logical_and(~is_penalty_nan, penalty > 0)
num_infeasible_trials = np.count_nonzero(is_infeasible)
if num_infeasible_trials > 0:
_, ranks = np.unique(penalty[is_infeasible], return_inverse=True)
ranks += 1
nondomination_rank[is_infeasible] += 1 + bottom_rank + ranks
bottom_rank += np.max(ranks)
n_below -= num_infeasible_trials
# Third, we calculate the domination rank for trials with no penalty information.
ranks, _ = _calculate_nondomination_rank_old(
objective_values[is_penalty_nan], n_below=n_below, base_rank=bottom_rank + 1
)
nondomination_rank[is_penalty_nan] += 1 + ranks
return nondomination_rank
def _calculate_nondomination_rank_old(
objective_values: np.ndarray,
*,
n_below: int | None = None,
base_rank: int = 0,
) -> tuple[np.ndarray, int]:
if n_below is not None and n_below <= 0:
return np.full(len(objective_values), -1), base_rank
# Normalize n_below.
n_below = n_below or len(objective_values)
n_below = min(n_below, len(objective_values))
# The ndarray `domination_mat` is a boolean 2d matrix where
# `domination_mat[i, j] == True` means that the j-th trial dominates the i-th trial in the
# given multi objective minimization problem.
domination_mat = np.all(
objective_values[:, np.newaxis, :] >= objective_values[np.newaxis, :, :], axis=2
) & np.any(
objective_values[:, np.newaxis, :] > objective_values[np.newaxis, :, :], axis=2
)
domination_list = np.nonzero(domination_mat)
domination_map = defaultdict(list)
for dominated_idx, dominating_idx in zip(*domination_list):
domination_map[dominating_idx].append(dominated_idx)
ranks = np.full(len(objective_values), -1)
dominated_count = np.sum(domination_mat, axis=1)
rank = base_rank - 1
ranked_idx_num = 0
while ranked_idx_num < n_below:
# Find the non-dominated trials and assign the rank.
(non_dominated_idxs,) = np.nonzero(dominated_count == 0)
ranked_idx_num += len(non_dominated_idxs)
rank += 1
ranks[non_dominated_idxs] = rank
# Update the dominated count.
dominated_count[non_dominated_idxs] = -1
for non_dominated_idx in non_dominated_idxs:
dominated_count[domination_map[non_dominated_idx]] -= 1
return ranks, rank
def _dominates(
trial0: FrozenTrial, trial1: FrozenTrial, directions: Sequence[StudyDirection]
) -> bool:
values0 = trial0.values
values1 = trial1.values
if trial0.state != TrialState.COMPLETE:
return False
if trial1.state != TrialState.COMPLETE:
return True
assert values0 is not None
assert values1 is not None
if len(values0) != len(values1):
raise ValueError(
"Trials with different numbers of objectives cannot be compared."
)
if len(values0) != len(directions):
raise ValueError(
"The number of the values and the number of the objectives are mismatched."
)
normalized_values0 = [_normalize_value(v, d) for v, d in zip(values0, directions)]
normalized_values1 = [_normalize_value(v, d) for v, d in zip(values1, directions)]
if normalized_values0 == normalized_values1:
return False
return all(v0 <= v1 for v0, v1 in zip(normalized_values0, normalized_values1))
def _normalize_value(value: float | None, direction: StudyDirection) -> float:
if value is None:
value = float("inf")
if direction is StudyDirection.MAXIMIZE:
value = -value
return value
#######################################
# new code:
def _get_pareto_front_trials_by_trials(
trials: Sequence[FrozenTrial],
directions: Sequence[StudyDirection],
consider_constraint: bool = False,
) -> list[FrozenTrial]:
# NOTE(nabenabe0928): Vectorization relies on all the trials being complete.
trials = [t for t in trials if t.state == TrialState.COMPLETE]
if consider_constraint:
trials = _get_feasible_trials(trials)
if len(trials) == 0:
return []
if any(len(t.values) != len(directions) for t in trials):
raise ValueError(
"The number of the values and the number of the objectives must be identical."
)
loss_values = np.asarray(
[[_normalize_value(v, d) for v, d in zip(t.values, directions)] for t in trials]
)
on_front = _is_pareto_front(loss_values, assume_unique_lexsorted=False)
return [t for t, is_pareto in zip(trials, on_front) if is_pareto]
def _get_pareto_front_trials(
study: "optuna.study.Study", consider_constraint: bool = False
) -> list[FrozenTrial]:
return _get_pareto_front_trials_by_trials(
study.trials, study.directions, consider_constraint
)
def _fast_non_domination_rank(
loss_values: np.ndarray,
*,
penalty: np.ndarray | None = None,
n_below: int | None = None,
) -> np.ndarray:
"""Calculate non-domination rank based on the fast non-dominated sort algorithm.
The fast non-dominated sort algorithm assigns a rank to each trial based on the dominance
relationship of the trials, determined by the objective values and the penalty values. The
algorithm is based on `the constrained NSGA-II algorithm
<https://doi.org/10.1109/4235.99601>`_, but the handling of the case when penalty
values are None is different. The algorithm assigns the rank according to the following
rules:
1. Feasible trials: First, the algorithm assigns the rank to feasible trials, whose penalty
values are less than or equal to 0, according to unconstrained version of fast non-
dominated sort.
2. Infeasible trials: Next, the algorithm assigns the rank from the minimum penalty value of to
the maximum penalty value.
3. Trials with no penalty information (constraints value is None): Finally, The algorithm
assigns the rank to trials with no penalty information according to unconstrained version
of fast non-dominated sort. Note that only this step is different from the original
constrained NSGA-II algorithm.
Plus, the algorithm terminates whenever the number of sorted trials reaches n_below.
Args:
loss_values:
Objective values, which is better when it is lower, of each trials.
penalty:
Constraints values of each trials. Defaults to None.
n_below: The minimum number of top trials required to be sorted. The algorithm will
terminate when the number of sorted trials reaches n_below. Defaults to None.
Returns:
An ndarray in the shape of (n_trials,), where each element is the non-domination rank of
each trial. The rank is 0-indexed. This function guarantees the correctness of the ranks
only up to the top-``n_below`` solutions. If a solution's rank is worse than the
top-``n_below`` solution, its rank is not necessarily correct. If you would like to ensure
the correctness, use ``n_below=None``.
"""
n_below = n_below or len(loss_values)
assert n_below >= 0, "n_below must be a non-negative integer."
if penalty is None:
return _calculate_nondomination_rank(loss_values, n_below=n_below)
if len(penalty) != len(loss_values):
raise ValueError(
"The length of penalty and loss_values must be same, but got "
f"len(penalty)={len(penalty)} and len(loss_values)={len(loss_values)}."
)
ranks = np.full(len(loss_values), -1, dtype=int)
is_penalty_nan = np.isnan(penalty)
is_feasible = np.logical_and(~is_penalty_nan, penalty <= 0)
is_infeasible = np.logical_and(~is_penalty_nan, penalty > 0)
# First, we calculate the domination rank for feasible trials.
ranks[is_feasible] = _calculate_nondomination_rank(
loss_values[is_feasible], n_below=n_below
)
n_below -= np.count_nonzero(is_feasible)
# Second, we calculate the domination rank for infeasible trials.
top_rank_infeasible = np.max(ranks[is_feasible], initial=-1) + 1
ranks[is_infeasible] = top_rank_infeasible + _calculate_nondomination_rank(
penalty[is_infeasible][:, np.newaxis], n_below=n_below
)
n_below -= np.count_nonzero(is_infeasible)
# Third, we calculate the domination rank for trials with no penalty information.
top_rank_penalty_nan = np.max(ranks[~is_penalty_nan], initial=-1) + 1
ranks[is_penalty_nan] = top_rank_penalty_nan + _calculate_nondomination_rank(
loss_values[is_penalty_nan], n_below=n_below
)
assert np.all(ranks != -1), "All the rank must be updated."
return ranks
def _is_pareto_front_nd(unique_lexsorted_loss_values: np.ndarray) -> np.ndarray:
# NOTE(nabenabe0928): I tried the Kung's algorithm below, but it was not really quick.
# https://github.com/optuna/optuna/pull/5302#issuecomment-1988665532
loss_values = unique_lexsorted_loss_values.copy()
n_trials = loss_values.shape[0]
on_front = np.zeros(n_trials, dtype=bool)
nondominated_indices = np.arange(n_trials)
while len(loss_values):
# The following judges `np.any(loss_values[i] < loss_values[0])` for each `i`.
nondominated_and_not_top = np.any(loss_values < loss_values[0], axis=1)
# NOTE: trials[j] cannot dominate trials[i] for i < j because of lexsort.
# Therefore, nondominated_indices[0] is always non-dominated.
on_front[nondominated_indices[0]] = True
loss_values = loss_values[nondominated_and_not_top]
nondominated_indices = nondominated_indices[nondominated_and_not_top]
return on_front
def _is_pareto_front_2d(unique_lexsorted_loss_values: np.ndarray) -> np.ndarray:
n_trials = unique_lexsorted_loss_values.shape[0]
cummin_value1 = np.minimum.accumulate(unique_lexsorted_loss_values[:, 1])
on_front = np.ones(n_trials, dtype=bool)
on_front[1:] = (
cummin_value1[1:] < cummin_value1[:-1]
) # True if cummin value1 is new minimum.
return on_front
def _is_pareto_front_for_unique_sorted(
unique_lexsorted_loss_values: np.ndarray,
) -> np.ndarray:
(n_trials, n_objectives) = unique_lexsorted_loss_values.shape
if n_objectives == 1:
on_front = np.zeros(len(unique_lexsorted_loss_values), dtype=bool)
on_front[0] = True # Only the first element is Pareto optimal.
return on_front
elif n_objectives == 2:
return _is_pareto_front_2d(unique_lexsorted_loss_values)
else:
return _is_pareto_front_nd(unique_lexsorted_loss_values)
def _is_pareto_front(
loss_values: np.ndarray, assume_unique_lexsorted: bool = True
) -> np.ndarray:
if assume_unique_lexsorted:
return _is_pareto_front_for_unique_sorted(loss_values)
unique_lexsorted_loss_values, order_inv = np.unique(
loss_values, axis=0, return_inverse=True
)
on_front = _is_pareto_front_for_unique_sorted(unique_lexsorted_loss_values)
return on_front[order_inv]
def _calculate_nondomination_rank(
loss_values: np.ndarray, *, n_below: int | None = None
) -> np.ndarray:
if len(loss_values) == 0 or (n_below is not None and n_below <= 0):
return np.zeros(len(loss_values), dtype=int)
(n_trials, n_objectives) = loss_values.shape
if n_objectives == 1:
_, ranks = np.unique(loss_values[:, 0], return_inverse=True)
return ranks
# It ensures that trials[j] will not dominate trials[i] for i < j.
# np.unique does lexsort.
unique_lexsorted_loss_values, order_inv = np.unique(
loss_values, return_inverse=True, axis=0
)
n_unique = unique_lexsorted_loss_values.shape[0]
# Clip n_below.
n_below = min(
n_below or len(unique_lexsorted_loss_values), len(unique_lexsorted_loss_values)
)
ranks = np.zeros(n_unique, dtype=int)
rank = 0
indices = np.arange(n_unique)
while n_unique - indices.size < n_below:
on_front = _is_pareto_front(unique_lexsorted_loss_values)
ranks[indices[on_front]] = rank
# Remove the recent Pareto solutions.
indices = indices[~on_front]
unique_lexsorted_loss_values = unique_lexsorted_loss_values[~on_front]
rank += 1
ranks[indices] = (
rank # Rank worse than the top n_below is defined as the worst rank.
)
return ranks[order_inv]
#############################################
# verification code
def check(
seed=0,
iter=10000,
num_trial=[1, 2, 3, 4, 5, 10, 20, 40, 100],
dim=list(range(2, 8)),
):
rng = np.random.default_rng(seed)
for it in range(iter):
print(f"iter={it}")
number_trials = rng.choice(num_trial)
dimension = rng.choice(dim)
lvals = np.array(
[
[rng.uniform(0.0, 100.0) for _ in range(dimension)]
for _ in range(number_trials)
]
)
if it % 2 == 0:
for i in range(len(lvals)):
for j in range(len(lvals[i])):
if lvals[i][j] < 10.0:
lvals[i][j] = float("-inf")
elif lvals[i][j] > 90.0:
lvals[i][j] = float("inf")
for pena in [True, False]:
penalty = None
if pena:
penalty = np.array(
[rng.uniform(-1.0, 1.0) for _ in range(number_trials)]
)
for n_below in range(1, number_trials + 1):
nondomination_ranks_old = _fast_non_dominated_sort_old(
lvals, penalty=penalty, n_below=None
) # reference impl, "ground truth"
nondomination_ranks_old -= min(nondomination_ranks_old)
nondomination_ranks = _fast_non_domination_rank(
lvals, penalty=penalty, n_below=n_below
)
correct_answer_rank_max = -1
wrong_answer_rank_min = number_trials + 1
correct_answer_population = 0
for i in range(number_trials):
if nondomination_ranks_old[i] == nondomination_ranks[i]:
correct_answer_rank_max = max(
correct_answer_rank_max, nondomination_ranks[i]
)
correct_answer_population += 1
else:
wrong_answer_rank_min = min(
wrong_answer_rank_min, nondomination_ranks_old[i]
)
wrong_answer_rank_min = min(
wrong_answer_rank_min, nondomination_ranks[i]
)
assert correct_answer_population >= n_below
assert (
sorted(nondomination_ranks_old)[n_below - 1]
<= wrong_answer_rank_min
)
study = optuna.create_study(
directions=[rng.choice(["minimize", "maximize"]) for _ in range(dimension)]
)
for x in lvals:
study.add_trial(
optuna.trial.create_trial(
params={f"x{n}": rng.uniform(0.0, 100.0) for n in range(dimension)},
distributions={
f"x{n}": optuna.distributions.FloatDistribution(0.0, 100.0)
for n in range(dimension)
},
values=x,
system_attrs={"constraints": [rng.uniform(-1.0, 1.0)]},
)
)
for pena in [True, False]:
pareto_front_trials_list_old = _get_pareto_front_trials_old(study, pena)
pareto_front_trials_list = _get_pareto_front_trials(study, pena)
assert set([t._trial_id for t in pareto_front_trials_list_old]) == set(
[t._trial_id for t in pareto_front_trials_list]
)
check()
not522
left a comment
There was a problem hiding this comment.
LGTM except small comments. Could you check them?
| An ndarray in the shape of (n_trials,), where each element is the non-domination rank of | ||
| each trial. The rank is 0-indexed. This function guarantees the correctness of the ranks | ||
| only up to the top-``n_below`` solutions. If a solution's rank is worse than the | ||
| top-``n_below`` solution, its rank is not necessarily correct. If you would like to ensure | ||
| the correctness, use ``n_below=None``. |
There was a problem hiding this comment.
In this description, it looks like an incorrect value could be confusing values like 0. How about specifying that it is greater than the n_below solutions' rank?
Co-authored-by: Naoto Mizuno <[email protected]>
|
@not522 ! reflected your suggestions! |
Motivation
This PR relates to:
This PR is a follow-up of
I specifically addressed:
Description of the changes
By this PR, the non-dominated sort speeds up:
For the verification, I copied the implementations from the repo:
Used Implementations
Important
Please check
# NOTE(nabenabe0928): I changed here for debugging.as some parts were just a bug and some parts hindered the reproducibility.Code to Generate the Table
Note
The unit of the runtimes in this table is milliseconds.