File: optuna_solver.py

package info (click to toggle)
python-cmaes 0.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 544 kB
  • sloc: python: 5,136; sh: 88; makefile: 4
file content (153 lines) | stat: -rw-r--r-- 5,019 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import argparse
import optuna
import warnings

from kurobako import solver
from kurobako.solver.optuna import OptunaSolverFactory

warnings.filterwarnings(
    "ignore",
    category=optuna.exceptions.ExperimentalWarning,
    module="optuna.samplers._cmaes",
)

parser = argparse.ArgumentParser()
parser.add_argument(
    "sampler",
    choices=["cmaes", "sep-cmaes", "ipop-cmaes", "ipop-sep-cmaes", "pycma", "ws-cmaes"],
)
parser.add_argument(
    "--loglevel", choices=["debug", "info", "warning", "error"], default="warning"
)
parser.add_argument("--warm-starting-trials", type=int, default=0)
args = parser.parse_args()

if args.loglevel == "debug":
    optuna.logging.set_verbosity(optuna.logging.DEBUG)
elif args.loglevel == "info":
    optuna.logging.set_verbosity(optuna.logging.INFO)
elif args.loglevel == "warning":
    optuna.logging.set_verbosity(optuna.logging.WARNING)
elif args.loglevel == "error":
    optuna.logging.set_verbosity(optuna.logging.ERROR)


def create_cmaes_study(seed):
    sampler = optuna.samplers.CmaEsSampler(seed=seed, warn_independent_sampling=True)
    return optuna.create_study(sampler=sampler, pruner=optuna.pruners.NopPruner())


def create_sep_cmaes_study(seed):
    sampler = optuna.samplers.CmaEsSampler(
        seed=seed, warn_independent_sampling=True, use_separable_cma=True
    )
    return optuna.create_study(sampler=sampler, pruner=optuna.pruners.NopPruner())


def create_ipop_cmaes_study(seed):
    sampler = optuna.samplers.CmaEsSampler(
        seed=seed,
        warn_independent_sampling=True,
        restart_strategy="ipop",
        inc_popsize=2,
    )
    return optuna.create_study(sampler=sampler, pruner=optuna.pruners.NopPruner())


def create_ipop_sep_cmaes_study(seed):
    sampler = optuna.samplers.CmaEsSampler(
        seed=seed,
        warn_independent_sampling=True,
        restart_strategy="ipop",
        inc_popsize=2,
        use_separable_cma=True,
    )
    return optuna.create_study(sampler=sampler, pruner=optuna.pruners.NopPruner())


def create_pycma_study(seed):
    sampler = optuna.integration.PyCmaSampler(
        seed=seed,
        warn_independent_sampling=True,
    )
    return optuna.create_study(sampler=sampler, pruner=optuna.pruners.NopPruner())


class WarmStartingCmaEsSampler(optuna.samplers.BaseSampler):
    def __init__(self, seed, warm_starting_trials: int) -> None:
        self._seed = seed
        self._warm_starting = True
        self._warm_starting_trials = warm_starting_trials
        self._sampler = optuna.samplers.RandomSampler(seed=seed)
        self._source_trials = []

    def infer_relative_search_space(self, study, trial):
        return self._sampler.infer_relative_search_space(study, trial)

    def sample_relative(
        self,
        study,
        trial,
        search_space,
    ):
        return self._sampler.sample_relative(study, trial, search_space)

    def sample_independent(self, study, trial, param_name, param_distribution):
        return self._sampler.sample_independent(
            study, trial, param_name, param_distribution
        )

    def after_trial(
        self,
        study,
        trial,
        state,
        values,
    ):
        if not self._warm_starting:
            return self._sampler.after_trial(study, trial, state, values)

        if len(self._source_trials) < self._warm_starting_trials:
            assert state == optuna.trial.TrialState.PRUNED

            self._source_trials.append(
                optuna.create_trial(
                    params=trial.params,
                    distributions=trial.distributions,
                    values=values,
                )
            )
        if len(self._source_trials) == self._warm_starting_trials:
            self._sampler = optuna.samplers.CmaEsSampler(
                seed=self._seed + 1, source_trials=self._source_trials or None
            )
            self._warm_starting = False
        else:
            return self._sampler.after_trial(study, trial, state, values)


def create_warm_start_study(seed):
    sampler = WarmStartingCmaEsSampler(seed, args.warm_starting_trials)
    return optuna.create_study(sampler=sampler, pruner=optuna.pruners.NopPruner())


if __name__ == "__main__":
    if args.sampler == "cmaes":
        factory = OptunaSolverFactory(create_cmaes_study)
    elif args.sampler == "sep-cmaes":
        factory = OptunaSolverFactory(create_sep_cmaes_study)
    elif args.sampler == "ipop-cmaes":
        factory = OptunaSolverFactory(create_ipop_cmaes_study)
    elif args.sampler == "ipop-sep-cmaes":
        factory = OptunaSolverFactory(create_ipop_sep_cmaes_study)
    elif args.sampler == "pycma":
        factory = OptunaSolverFactory(create_pycma_study)
    elif args.sampler == "ws-cmaes":
        factory = OptunaSolverFactory(
            create_warm_start_study, warm_starting_trials=args.warm_starting_trials
        )
    else:
        raise ValueError("unsupported sampler")

    runner = solver.SolverRunner(factory)
    runner.run()