Skip to content

Refactor BruteForceSampler - #6645

Merged
not522 merged 15 commits into
optuna:masterfrom
nabenabe0928:refactor-brute-force
May 15, 2026
Merged

not522 merged 15 commits into
optuna:masterfrom
nabenabe0928:refactor-brute-force

Conversation

@nabenabe0928

@nabenabe0928 nabenabe0928 commented May 3, 2026 •

Copy link
Copy Markdown
Contributor

Important

I splited this PR into a few smaller PRs.
This PR is already made small at:

Motivation

Since some variables are created billions times, it is not negligible to refactor BruteForceSampler so that the number of access will be reduced.
This PR is a precursor of subsequent PRs.

Although this PR is mostly a refactoring, this PR makes the sampler slightly quicker (66 seconds --> 58 seconds; ~13% speedup)

Benchmark Script
from argparse import ArgumentParser

import optuna


parser = ArgumentParser()
parser.add_argument("--n_params", type=int, default=5)
parser.add_argument("--n_choices", type=int, default=5)
args = parser.parse_args()
n_params = args.n_params
n_choices = args.n_choices
search_space = {f"c{i}": [str(i) for i in range(n_choices)] for i in range(n_params)}


def objective(trial: optuna.Trial) -> float:
    for k, v in search_space.items():
        trial.suggest_categorical(k, v)
    return 0.0


def experiment(
    n_trials: int | None = None, skip_grid: bool = False
) -> tuple[list[float], list[float]]:
    study = optuna.create_study(sampler=optuna.samplers.BruteForceSampler(seed=0))
    study.optimize(objective, n_trials=n_trials)
    start = study.trials[0].datetime_start
    runtime_brute_force = [(t.datetime_complete - start).total_seconds() for t in study.trials]
    if skip_grid:
        return runtime_brute_force, []

    study = optuna.create_study(sampler=optuna.samplers.GridSampler(search_space=search_space, seed=0))
    study.optimize(objective, n_trials=n_trials)
    start = study.trials[0].datetime_start
    runtime_grid = [(t.datetime_complete - start).total_seconds() for t in study.trials]
    return runtime_brute_force, runtime_grid


if __name__ == "__main__":
    # plot()
    res, _ = experiment(3000, True)
    print(res[::100])

Description of the changes

  • _TreeNode.expand() now returns dict[float, _TreeNode]: This eliminates the need for callers to access .children separately and assert it's not None
  • Extracted _get_non_waiting_trials_and_current_trial_index()
  • Simplified sample_independent(): Uses the new helper to get trials and pops the current trial by index, replacing the inline storage query and the generator expression that filtered by t.number != trial.number.
  • Simplified after_trial(): Uses the new helper, then replaces the current trial in-place at its index with a create_trial(...) call, instead of using a complex generator expression with an inline ternary. The _populate_tree call is now a clean one-liner over the modified list.
  • Add slots to dataclass: This reduces the overhead in instantiation.

@c-bata c-bata left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM with a nit.

Comment on lines -31 to -36
# This is a class to represent the tree of search space.
"""
This is a class to represent the tree of search space.

A tree node has three states:
1. Unexpanded. This is represented by children=None.
2. Leaf. This is represented by children={} and param_name=None.
3. Normal node. It has a param_name and non-empty children.

# A tree node has three states:
# 1. Unexpanded. This is represented by children=None.
# 2. Leaf. This is represented by children={} and param_name=None.
# 3. Normal node. It has a param_name and non-empty children.

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.

I’m not sure about the motivation for turning this comment into a docstring. Since it is just an internal explanatory comment, it does not seem necessary to include it in __doc__. This change is harmless, but would you mind keeping it as a regular comment to reduce unnecessary diff?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I slightly changed the doc-string.

@c-bata c-bata added the enhancement Change that does not break compatibility and not affect public interfaces, but improves performance. label May 11, 2026
@c-bata c-bata self-assigned this May 11, 2026
@nabenabe0928

Copy link
Copy Markdown
Contributor Author

The test fail is unrelated to this PR.

@c-bata c-bata left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM!

@c-bata c-bata removed their assignment May 11, 2026
@not522 not522 self-assigned this May 12, 2026

@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

@not522
not522 merged commit b4f2f79 into optuna:master May 15, 2026
12 checks passed
@c-bata c-bata added this to the v4.9.0 milestone May 15, 2026
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.

3 participants