Skip to content

Commit

Permalink
Follow the Optuna convention
Browse files Browse the repository at this point in the history
  • Loading branch information
nabenabe0928 committed Nov 25, 2024
1 parent 04f3d9f commit 82e866e
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 31 deletions.
26 changes: 12 additions & 14 deletions package/samplers/cmamae/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ quality diversity algorithms using pyribs.

- CmaMaeSampler

Please take a look at:

- [GridArchive](https://docs.pyribs.org/en/stable/api/ribs.archives.GridArchive.html), and
- [EvolutionStrategyEmitter](https://docs.pyribs.org/en/stable/api/ribs.emitters.EvolutionStrategyEmitter.html)
for the details of each argument.

## Installation

```shell
Expand All @@ -42,22 +48,24 @@ $ pip install ribs
```python
import optuna
import optunahub
from optuna.study import StudyDirection

module = optunahub.load_module("samplers/cmamae")
CmaMaeSampler = module.CmaMaeSampler


def objective(trial: optuna.trial.Trial) -> tuple[float, float, float]:
def objective(trial: optuna.trial.Trial) -> float:
"""Returns an objective followed by two measures."""
x = trial.suggest_float("x", -10, 10)
y = trial.suggest_float("y", -10, 10)
return x**2 + y**2, x, y
trial.set_user_attr("x", x)
trial.set_user_attr("y", y)
return x**2 + y**2


if __name__ == "__main__":
sampler = CmaMaeSampler(
param_names=["x", "y"],
measure_names=["x", "y"],
archive_dims=[20, 20],
archive_ranges=[(-1, 1), (-1, 1)],
archive_learning_rate=0.1,
Expand All @@ -70,17 +78,7 @@ if __name__ == "__main__":
emitter_sigma0=0.1,
emitter_batch_size=20,
)
study = optuna.create_study(
sampler=sampler,
directions=[
StudyDirection.MINIMIZE,
# The remaining directions are for the measures, which do not have
# an optimization direction. However, we set MINIMIZE as a
# placeholder direction.
StudyDirection.MINIMIZE,
StudyDirection.MINIMIZE,
],
)
study = optuna.create_study(sampler=sampler)
study.optimize(objective, n_trials=10000)
```

Expand Down
20 changes: 6 additions & 14 deletions package/samplers/cmamae/example.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
import optuna
from optuna.study import StudyDirection
import optunahub


module = optunahub.load_module("samplers/cmamae")
CmaMaeSampler = module.CmaMaeSampler


def objective(trial: optuna.trial.Trial) -> tuple[float, float, float]:
def objective(trial: optuna.trial.Trial) -> float:
"""Returns an objective followed by two measures."""
x = trial.suggest_float("x", -10, 10)
y = trial.suggest_float("y", -10, 10)
return x**2 + y**2, x, y
trial.set_user_attr("x", x)
trial.set_user_attr("y", y)
return x**2 + y**2


if __name__ == "__main__":
sampler = CmaMaeSampler(
param_names=["x", "y"],
measure_names=["x", "y"],
archive_dims=[20, 20],
archive_ranges=[(-1, 1), (-1, 1)],
archive_learning_rate=0.1,
Expand All @@ -29,15 +31,5 @@ def objective(trial: optuna.trial.Trial) -> tuple[float, float, float]:
emitter_sigma0=0.1,
emitter_batch_size=20,
)
study = optuna.create_study(
sampler=sampler,
directions=[
StudyDirection.MINIMIZE,
# The remaining directions are for the measures, which do not have
# an optimization direction. However, we set MINIMIZE as a
# placeholder direction.
StudyDirection.MINIMIZE,
StudyDirection.MINIMIZE,
],
)
study = optuna.create_study(sampler=sampler)
study.optimize(objective, n_trials=10000)
25 changes: 22 additions & 3 deletions package/samplers/cmamae/sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ def __init__(
self,
*,
param_names: list[str],
measure_names: list[str],
archive_dims: list[int],
archive_ranges: list[tuple[float, float]],
archive_learning_rate: float,
Expand All @@ -77,7 +78,8 @@ def __init__(
emitter_batch_size: int,
) -> None:
self._validate_params(param_names, emitter_x0)
self._param_names = param_names[:]
self._param_names = param_names.copy()
self._measure_names = measure_names.copy()

# NOTE: SimpleBaseSampler must know Optuna search_space information.
search_space = {name: FloatDistribution(-1e9, 1e9) for name in self._param_names}
Expand Down Expand Up @@ -182,8 +184,25 @@ def after_trial(
# Store the trial result.
direction0 = study.directions[0]
minimize_in_optuna = direction0 == StudyDirection.MINIMIZE
assert values is not None, "MyPy redefinition."
modified_values = list([float(v) for v in values])
if values is None:
raise RuntimeError(
f"{self.__class__.__name__} does not support Failed trials, "
f"but trial#{trial.number} failed."
)
user_attrs = trial.user_attrs
if any(measure_name not in user_attrs for measure_name in self._measure_names):
raise KeyError(
f"All of measure in measure_names={self._measure_names} must be set to "
"trial.user_attrs. Please call trial.set_user_attr(<measure_name>, <value>) "
"for each measure."
)

self._raise_error_if_multi_objective(study)
modified_values = [
float(values[0]),
float(user_attrs[self._measure_names[0]]),
float(user_attrs[self._measure_names[1]]),
]
if minimize_in_optuna:
# The direction of the first objective (pyribs maximizes).
modified_values[0] = -values[0]
Expand Down

0 comments on commit 82e866e

Please sign in to comment.