Skip to content

Speed up non-dominated sort - #5302

Merged
not522 merged 17 commits into
optuna:masterfrom
nabenabe0928:enhance/speed-up-non-dominated-sort
May 1, 2024
Merged

not522 merged 17 commits into
optuna:masterfrom
nabenabe0928:enhance/speed-up-non-dominated-sort

Conversation

@nabenabe0928

@nabenabe0928 nabenabe0928 commented Mar 10, 2024 •

Copy link
Copy Markdown
Contributor

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
from __future__ import annotations

from collections import defaultdict
import time

import numpy as np


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):
        nondominated_and_not_top = np.any(loss_values < loss_values[0], axis=1)
        # NOTE: trials[j] cannot dominate trials[j] 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])
    is_value1_min = cummin_value1 == unique_lexsorted_loss_values[:, 1]
    is_value1_new_min = cummin_value1[1:] < cummin_value1[:-1]
    on_front = np.ones(n_trials, dtype=bool)
    on_front[1:] = is_value1_min[1:] & is_value1_new_min
    return on_front


def _is_pareto_front(unique_lexsorted_loss_values: np.ndarray) -> np.ndarray:
    (n_trials, n_objectives) = unique_lexsorted_loss_values.shape
    if n_objectives == 1:
        return unique_lexsorted_loss_values[:, 0] == unique_lexsorted_loss_values[0]
    elif n_objectives == 2:
        return _is_pareto_front_2d(unique_lexsorted_loss_values)
    else:
        return _is_pareto_front_nd(unique_lexsorted_loss_values)


def nd_rank_this_pr(
    loss_values: np.ndarray, *, n_below: int | None = None
) -> np.ndarray:
    if 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
    else:
        # 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]


def nd_rank_original(
    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
    if objective_values.shape[-1] == 1:  # NOTE(nabenabe0928): I changed here for debugging.
        _, ranks = np.unique(objective_values[:, 0], return_inverse=True)
        return ranks, np.max(ranks, initial=0)
    # 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 original(
    objective_values: np.ndarray,
    *,
    penalty: np.ndarray | None = None,
    n_below: int | None = None,
) -> np.ndarray:
    if penalty is None:
        ranks, _ = nd_rank_original(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 = nd_rank_original(
        objective_values[is_feasible], n_below=n_below
    )
    # NOTE(nabenabe0928): I changed here for debugging.
    ranks[ranks == -1] = np.max(ranks, initial=-1) + 1
    # NOTE(nabenabe0928): I changed here for debugging.
    bottom_rank = np.max(ranks, initial=-1)
    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, _ = nd_rank_original(
        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 this_pr(
    loss_values: np.ndarray,
    *,
    penalty: np.ndarray | None = None,
    n_below: int | None = None,
) -> np.ndarray:
    if penalty is None:
        return nd_rank_this_pr(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)}."
        )

    nondomination_rank = np.full(len(loss_values), -1, dtype=int)
    is_penalty_nan = np.isnan(penalty)
    n_below = n_below or len(loss_values)

    # First, we calculate the domination rank for feasible trials.
    is_feasible = np.logical_and(~is_penalty_nan, penalty <= 0)
    nondomination_rank[is_feasible] = nd_rank_this_pr(
        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_in_infeasible = np.max(nondomination_rank[is_feasible], initial=-1) + 1
    is_infeasible = np.logical_and(~is_penalty_nan, penalty > 0)
    n_infeasible = np.count_nonzero(is_infeasible)
    if n_infeasible > 0:
        _, ranks_in_infeas = np.unique(penalty[is_infeasible], return_inverse=True)
        nondomination_rank[is_infeasible] = ranks_in_infeas + top_rank_in_infeasible
        n_below -= n_infeasible

    # Third, we calculate the domination rank for trials with no penalty information.
    top_rank_in_penalty_nan = np.max(nondomination_rank[~is_penalty_nan], initial=-1) + 1
    ranks_in_penalty_nan = nd_rank_this_pr(
        loss_values[is_penalty_nan], n_below=n_below
    )
    nondomination_rank[is_penalty_nan] = ranks_in_penalty_nan + top_rank_in_penalty_nan
    assert np.all(nondomination_rank != -1), "All the rank must be updated."
    return nondomination_rank


def verify(
    seed: int, n_samples: int, n_below: int, n_objectives: int, consider_penalty: bool = True
) -> tuple[float, float]:
    # TODO(nabenabe0928): consider_penalty.
    print(f"Start with {seed=}, {n_samples=}, {n_below=}, {n_objectives=}.")
    rng = np.random.RandomState(seed)
    loss_values = rng.normal(size=(n_samples, n_objectives))
    penalty = 1 - loss_values[:, 0] if consider_penalty else None

    start = time.time()
    output_this_pr = this_pr(loss_values, penalty=penalty, n_below=n_below)
    runtime_this_pr = (time.time() - start) * 1000
    print(f"This PR took {runtime_this_pr:.3f} ms.")

    start = time.time()
    output_original = original(loss_values, penalty=penalty, n_below=n_below)
    runtime_original = (time.time() - start) * 1000
    print(f"Original implementation took {runtime_original:.3f} ms.")

    assert np.allclose(output_original, output_this_pr), (
        f"{n_samples=}, {n_below_div=}, {n_objectives=}, "
        f"{output_original=}, {output_this_pr=}, {penalty=}"
    )
    return runtime_this_pr, runtime_original

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
import pandas as pd
def add_row(results: dict, row: dict) -> None:
    for k, v in row.items():
        results[k].append(v)

n_seeds = 5
n_samples_set = [1000, 10000]
n_objectives_set = [2, 3]
results = {"version": [], "n_objectives": [], "n_samples": [], "runtime": [], "seed": []}
for seed in range(n_seeds):
    for n_samples in n_samples_set:
        for n_objectives in n_objectives_set:
            row = dict(seed=seed, n_samples=n_samples, n_objectives=n_objectives)
            rt_this_pr, rt_original = verify(
                seed, n_samples, n_samples, n_objectives, consider_penalty=False
            )
            row.update(version="original", runtime=rt_original)
            add_row(results, row)
            row.update(version="this_pr", runtime=rt_this_pr)
            add_row(results, row)

posthoc_results = {"n_objectives": [], "n_samples": [], "Original": [], "This PR": []}
df = pd.DataFrame(results)
for n_samples in n_samples_set:
    for n_objectives in n_objectives_set:
        row = dict(n_samples=n_samples, n_objectives=n_objectives)
        cond1 = df["n_samples"] == n_samples
        cond2 = df["n_objectives"] == n_objectives
        df_original = df[cond1 & cond2 & (df["version"] == "original")]
        m = df_original["runtime"].mean()
        ste = df_original["runtime"].std() / np.sqrt(n_seeds)
        row["Original"] = f"{m:.3e} $\pm$ {ste:.3e}"

        df_this_pr = df[cond1 & cond2 & (df["version"] == "this_pr")]
        m = df_this_pr["runtime"].mean()
        ste = df_this_pr["runtime"].std() / np.sqrt(n_seeds)
        row["This PR"] = f"{m:.3e} $\pm$ {ste:.3e}"

        add_row(posthoc_results, row)

print(pd.DataFrame(posthoc_results).to_markdown(index=False))
n_objectives n_samples Original This PR
2 1000 8.497e+01 $\pm$ 1.346e+00 1.167e+00 $\pm$ 3.161e-02
3 1000 6.647e+01 $\pm$ 1.619e+00 8.594e+00 $\pm$ 3.196e-01
2 10000 1.024e+04 $\pm$ 2.006e+02 1.743e+01 $\pm$ 6.119e-01
3 10000 7.322e+03 $\pm$ 1.500e+02 3.592e+02 $\pm$ 7.861e+00

Note

The unit of the runtimes in this table is milliseconds.

@codecov

codecov Bot commented Mar 10, 2024 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 95.00000% with 4 lines in your changes are missing coverage. Please review.

Project coverage is 89.60%. Comparing base (be97dd1) to head (ac582df).
Report is 77 commits behind head on master.

❗ Current head ac582df differs from pull request most recent head 657f8e7. Consider uploading reports for the commit 657f8e7 to get more accurate results

Files Patch % Lines
optuna/study/_multi_objective.py 94.73% 4 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

@nabenabe0928 nabenabe0928 changed the title Enhance/speed up non dominated sort Speed up non dominated sort Mar 11, 2024
@nabenabe0928

nabenabe0928 commented Mar 11, 2024 •

Copy link
Copy Markdown
Contributor Author

I also tried the Kung's algorithm, which is supposed to have the time complexity of $O(N \log^{M-2} N)$, but this algorithm was not really quick in my benchmarking.

Comparison with the Kung's Algorithm
import 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]]
Kung with vectorization: 0.10632514953613281
Kung with loop: 0.11832070350646973
Original: 0.0017082691192626953

@nabenabe0928

Copy link
Copy Markdown
Contributor Author

@contramundum53 @gen740 Could you review this PR?

@nabenabe0928

nabenabe0928 commented Mar 12, 2024 •

Copy link
Copy Markdown
Contributor Author

Here is the verification code:

Important

Please check # NOTE(nabenabe0928): I changed here for debugging. as some parts were just a bug and some parts hindered the reproducibility.

In my environment, the following verification does not fail, which means that I get the identical behavior.

Verification Code
results = {"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
Start with seed=0, n_samples=1, n_below=1, n_objectives=1.
This PR took 0.130 ms.
Original implementation took 0.068 ms.
Start with seed=0, n_samples=1, n_below=1, n_objectives=2.
This PR took 0.135 ms.
Original implementation took 0.079 ms.
Start with seed=0, n_samples=1, n_below=1, n_objectives=3.
This PR took 0.096 ms.
Original implementation took 0.055 ms.
Start with seed=0, n_samples=1, n_below=1, n_objectives=4.
This PR took 0.085 ms.
Original implementation took 0.051 ms.
Start with seed=0, n_samples=1, n_below=1, n_objectives=1.
This PR took 0.037 ms.
Original implementation took 0.038 ms.
Start with seed=0, n_samples=1, n_below=1, n_objectives=2.
This PR took 0.075 ms.
Original implementation took 0.051 ms.
Start with seed=0, n_samples=1, n_below=1, n_objectives=3.
This PR took 0.095 ms.
Original implementation took 0.064 ms.
Start with seed=0, n_samples=1, n_below=1, n_objectives=4.
This PR took 0.091 ms.
Original implementation took 0.059 ms.
Start with seed=0, n_samples=100, n_below=100, n_objectives=1.
This PR took 0.087 ms.
Original implementation took 0.076 ms.
Start with seed=0, n_samples=100, n_below=100, n_objectives=2.
This PR took 0.163 ms.
Original implementation took 0.163 ms.
Start with seed=0, n_samples=100, n_below=100, n_objectives=3.
This PR took 0.233 ms.
Original implementation took 0.160 ms.
Start with seed=0, n_samples=100, n_below=100, n_objectives=4.
This PR took 0.215 ms.
Original implementation took 0.183 ms.
Start with seed=0, n_samples=100, n_below=10, n_objectives=1.
This PR took 3.901 ms.
Original implementation took 0.181 ms.
Start with seed=0, n_samples=100, n_below=10, n_objectives=2.
This PR took 0.227 ms.
Original implementation took 0.243 ms.
Start with seed=0, n_samples=100, n_below=10, n_objectives=3.
This PR took 0.265 ms.
Original implementation took 0.197 ms.
Start with seed=0, n_samples=100, n_below=10, n_objectives=4.
This PR took 0.303 ms.
Original implementation took 0.211 ms.
Start with seed=0, n_samples=10000, n_below=10000, n_objectives=1.
This PR took 1.182 ms.
Original implementation took 3.664 ms.
Start with seed=0, n_samples=10000, n_below=10000, n_objectives=2.
This PR took 2.547 ms.
Original implementation took 200.867 ms.
Start with seed=0, n_samples=10000, n_below=10000, n_objectives=3.
This PR took 15.354 ms.
Original implementation took 145.939 ms.
Start with seed=0, n_samples=10000, n_below=10000, n_objectives=4.
This PR took 15.606 ms.
Original implementation took 122.636 ms.
Start with seed=0, n_samples=10000, n_below=1000, n_objectives=1.
This PR took 0.694 ms.
Original implementation took 0.727 ms.
Start with seed=0, n_samples=10000, n_below=1000, n_objectives=2.
This PR took 1.814 ms.
Original implementation took 193.547 ms.
Start with seed=0, n_samples=10000, n_below=1000, n_objectives=3.
This PR took 11.992 ms.
Original implementation took 148.139 ms.
Start with seed=0, n_samples=10000, n_below=1000, n_objectives=4.
This PR took 12.455 ms.
Original implementation took 128.243 ms.
Start with seed=1, n_samples=1, n_below=1, n_objectives=1.
This PR took 0.066 ms.
Original implementation took 0.038 ms.
Start with seed=1, n_samples=1, n_below=1, n_objectives=2.
This PR took 0.126 ms.
Original implementation took 0.061 ms.
Start with seed=1, n_samples=1, n_below=1, n_objectives=3.
This PR took 0.093 ms.
Original implementation took 0.044 ms.
Start with seed=1, n_samples=1, n_below=1, n_objectives=4.
This PR took 0.075 ms.
Original implementation took 0.042 ms.
Start with seed=1, n_samples=1, n_below=1, n_objectives=1.
This PR took 0.033 ms.
Original implementation took 0.032 ms.
Start with seed=1, n_samples=1, n_below=1, n_objectives=2.
This PR took 0.070 ms.
Original implementation took 0.044 ms.
Start with seed=1, n_samples=1, n_below=1, n_objectives=3.
This PR took 0.069 ms.
Original implementation took 0.042 ms.
Start with seed=1, n_samples=1, n_below=1, n_objectives=4.
This PR took 0.083 ms.
Original implementation took 0.045 ms.
Start with seed=1, n_samples=100, n_below=100, n_objectives=1.
This PR took 0.058 ms.
Original implementation took 0.048 ms.
Start with seed=1, n_samples=100, n_below=100, n_objectives=2.
This PR took 0.127 ms.
Original implementation took 0.167 ms.
Start with seed=1, n_samples=100, n_below=100, n_objectives=3.
This PR took 0.198 ms.
Original implementation took 0.107 ms.
Start with seed=1, n_samples=100, n_below=100, n_objectives=4.
This PR took 0.149 ms.
Original implementation took 0.102 ms.
Start with seed=1, n_samples=100, n_below=10, n_objectives=1.
This PR took 0.046 ms.
Original implementation took 0.066 ms.
Start with seed=1, n_samples=100, n_below=10, n_objectives=2.
This PR took 0.105 ms.
Original implementation took 0.137 ms.
Start with seed=1, n_samples=100, n_below=10, n_objectives=3.
This PR took 0.159 ms.
Original implementation took 0.111 ms.
Start with seed=1, n_samples=100, n_below=10, n_objectives=4.
This PR took 0.152 ms.
Original implementation took 0.114 ms.
Start with seed=1, n_samples=10000, n_below=10000, n_objectives=1.
This PR took 0.799 ms.
Original implementation took 0.792 ms.
Start with seed=1, n_samples=10000, n_below=10000, n_objectives=2.
This PR took 2.530 ms.
Original implementation took 251.135 ms.
Start with seed=1, n_samples=10000, n_below=10000, n_objectives=3.
This PR took 17.972 ms.
Original implementation took 156.764 ms.
Start with seed=1, n_samples=10000, n_below=10000, n_objectives=4.
This PR took 18.817 ms.
Original implementation took 144.427 ms.
Start with seed=1, n_samples=10000, n_below=1000, n_objectives=1.
This PR took 0.712 ms.
Original implementation took 0.750 ms.
Start with seed=1, n_samples=10000, n_below=1000, n_objectives=2.
This PR took 1.917 ms.
Original implementation took 213.424 ms.
Start with seed=1, n_samples=10000, n_below=1000, n_objectives=3.
This PR took 13.443 ms.
Original implementation took 145.106 ms.
Start with seed=1, n_samples=10000, n_below=1000, n_objectives=4.
This PR took 14.069 ms.
Original implementation took 138.788 ms.
Start with seed=2, n_samples=1, n_below=1, n_objectives=1.
This PR took 0.063 ms.
Original implementation took 0.044 ms.
Start with seed=2, n_samples=1, n_below=1, n_objectives=2.
This PR took 0.098 ms.
Original implementation took 0.057 ms.
Start with seed=2, n_samples=1, n_below=1, n_objectives=3.
This PR took 0.072 ms.
Original implementation took 0.047 ms.
Start with seed=2, n_samples=1, n_below=1, n_objectives=4.
This PR took 0.068 ms.
Original implementation took 0.043 ms.
Start with seed=2, n_samples=1, n_below=1, n_objectives=1.
This PR took 0.035 ms.
Original implementation took 0.035 ms.
Start with seed=2, n_samples=1, n_below=1, n_objectives=2.
This PR took 0.061 ms.
Original implementation took 0.041 ms.
Start with seed=2, n_samples=1, n_below=1, n_objectives=3.
This PR took 0.058 ms.
Original implementation took 0.040 ms.
Start with seed=2, n_samples=1, n_below=1, n_objectives=4.
This PR took 0.061 ms.
Original implementation took 0.040 ms.
Start with seed=2, n_samples=100, n_below=100, n_objectives=1.
This PR took 0.049 ms.
Original implementation took 0.042 ms.
Start with seed=2, n_samples=100, n_below=100, n_objectives=2.
This PR took 0.122 ms.
Original implementation took 0.119 ms.
Start with seed=2, n_samples=100, n_below=100, n_objectives=3.
This PR took 0.167 ms.
Original implementation took 0.116 ms.
Start with seed=2, n_samples=100, n_below=100, n_objectives=4.
This PR took 0.155 ms.
Original implementation took 0.105 ms.
Start with seed=2, n_samples=100, n_below=10, n_objectives=1.
This PR took 0.043 ms.
Original implementation took 0.038 ms.
Start with seed=2, n_samples=100, n_below=10, n_objectives=2.
This PR took 0.104 ms.
Original implementation took 0.098 ms.
Start with seed=2, n_samples=100, n_below=10, n_objectives=3.
This PR took 0.132 ms.
Original implementation took 0.089 ms.
Start with seed=2, n_samples=100, n_below=10, n_objectives=4.
This PR took 0.121 ms.
Original implementation took 0.087 ms.
Start with seed=2, n_samples=10000, n_below=10000, n_objectives=1.
This PR took 0.659 ms.
Original implementation took 0.691 ms.
Start with seed=2, n_samples=10000, n_below=10000, n_objectives=2.
This PR took 2.300 ms.
Original implementation took 215.417 ms.
Start with seed=2, n_samples=10000, n_below=10000, n_objectives=3.
This PR took 17.123 ms.
Original implementation took 159.207 ms.
Start with seed=2, n_samples=10000, n_below=10000, n_objectives=4.
This PR took 16.053 ms.
Original implementation took 143.698 ms.
Start with seed=2, n_samples=10000, n_below=1000, n_objectives=1.
This PR took 0.722 ms.
Original implementation took 0.672 ms.
Start with seed=2, n_samples=10000, n_below=1000, n_objectives=2.
This PR took 1.900 ms.
Original implementation took 210.731 ms.
Start with seed=2, n_samples=10000, n_below=1000, n_objectives=3.
This PR took 13.731 ms.
Original implementation took 153.624 ms.
Start with seed=2, n_samples=10000, n_below=1000, n_objectives=4.
This PR took 11.899 ms.
Original implementation took 135.919 ms.
results={'original': [1.7154216766357422, 222.4726676940918, 153.96984418233237, 136.9201342264811], 'this_pr': [0.8801619211832682, 2.458731333414714, 16.816139221191406, 16.825199127197266]} for n_samples=10000

Comment thread optuna/study/_multi_objective.py Resolved
Comment thread optuna/study/_multi_objective.py Resolved
Comment thread optuna/study/_multi_objective.py Resolved
Comment thread optuna/study/_multi_objective.py Resolved
Comment thread optuna/study/_multi_objective.py Resolved
@nabenabe0928
nabenabe0928 force-pushed the enhance/speed-up-non-dominated-sort branch from 153909f to 0bf8a1b Compare March 18, 2024 12:20
@nabenabe0928
nabenabe0928 force-pushed the enhance/speed-up-non-dominated-sort branch from 0bf8a1b to 9714d4a Compare March 18, 2024 12:21
Comment thread optuna/study/_multi_objective.py Resolved
Comment thread optuna/study/_multi_objective.py Resolved
Comment thread optuna/study/_multi_objective.py Resolved
@y0z y0z added the enhancement Change that does not break compatibility and not affect public interfaces, but improves performance. label Mar 27, 2024
@github-actions

github-actions Bot commented Apr 3, 2024

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 3, 2024
@nabenabe0928 nabenabe0928 removed the stale Exempt from stale bot labeling. label Apr 3, 2024
@HideakiImamura

Copy link
Copy Markdown
Member

@not522 Could you review this PR?

@github-actions

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 16, 2024
@not522 not522 removed the stale Exempt from stale bot labeling. label Apr 16, 2024
@nabenabe0928 nabenabe0928 changed the title Speed up non dominated sort Speed up non-dominated sort Apr 17, 2024
@eukaryo eukaryo assigned eukaryo and unassigned gen740 Apr 23, 2024

@eukaryo eukaryo left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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()

@eukaryo eukaryo removed their assignment Apr 25, 2024

@not522 not522 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 except small comments. Could you check them?

Comment thread optuna/study/_multi_objective.py Outdated
Comment on lines +87 to +91
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``.

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.

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?

Comment thread optuna/study/_multi_objective.py Resolved
Co-authored-by: Naoto Mizuno <[email protected]>
@nabenabe0928

Copy link
Copy Markdown
Contributor Author

@not522 ! reflected your suggestions!

@not522 not522 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!

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.

7 participants