5"""Save and resume ordered MAP-Elites, NSLC, CMA-MAE, and MOME runs."""
7from functools
import partial
8from contextlib
import nullcontext
9from importlib.metadata
import version
10from operator
import index
11from pathlib
import Path
19from qdpy
import __version__, tools
21from qdpy.containers import Container, CVTGrid, Grid, NoveltyArchive, ParetoGrid
22from qdpy.journal import _EvaluationJournal, _JournalInterrupted, _KIND
24from qdpy.simple import RunResult, _coordinator_seed, _positive_int
26__all__ = [
"run_checkpointed"]
28_HEADER = b
"QDpy MAP-Elites checkpoint 1\n"
29_COUNTERS = (
"_nb_suggestions",
"_nb_evaluations",
"_nb_updated")
30_BATCH_COUNTERS = tuple(name +
"_in_iteration" for name
in _COUNTERS)
32 CMAMAE: (
"_completed_generations",
"_strategy",
"_rng",
"_thresholds",
"_search_elites"),
33 MOME: (
"_completed_generations",),
38 """Exit the native schedule after committing a complete batch."""
41def _bounds_signature(bounds):
42 return None if bounds
is None else tuple(map(tuple, bounds))
45def _novelty_settings(archive):
46 """Describe fixed Euclidean novelty and each parent admission policy."""
47 if (archive.novelty_distance !=
"euclidean" or not archive.parents
48 or any(type(parent)
is not Container
or parent.parents
for parent
in archive.parents)):
49 raise ValueError(
"Checkpointed NSLC needs Euclidean novelty with plain parentless Container histories.")
52 archive.k, archive.threshold_novelty, archive.indexed, archive.only_add_accepted_inds_to_parents,
53 tuple((first_slot.setdefault(id(parent), slot), type(parent.items).__name__, parent.capacity,
54 _bounds_signature(parent.fitness_domain), _bounds_signature(parent.features_domain),
55 tuple(parent.fitness_score_names), tuple(parent.features_score_names),
56 None if parent.fitness_weights
is None else tuple(parent.fitness_weights))
57 for slot, parent
in enumerate(archive.parents)),
61def _settings(algorithm):
62 """Describe the search state whose reconstruction is covered by this codec."""
63 if type(algorithm)
not in (RandomSearchMutPolyBounded, CMAMAE, MOME):
64 raise ValueError(
"Checkpointing supports RandomSearchMutPolyBounded, CMAMAE, and MOME.")
65 archive = algorithm.container
66 novelty = type(archive)
is NoveltyArchive
67 if type(algorithm)
is MOME:
68 if type(archive)
is not ParetoGrid
or archive.parents:
69 raise ValueError(
"Checkpointed MOME requires a native parentless ParetoGrid.")
70 elif not novelty
and (type(archive)
not in (Grid, CVTGrid)
or archive.parents
or archive.max_items_per_bin != 1):
71 raise ValueError(
"Use a parentless, best-only Grid or CVTGrid, or a fixed NoveltyArchive.")
72 novelty_settings = _novelty_settings(archive)
if novelty
else ()
73 if algorithm._base_ind_gen
is not None:
74 raise ValueError(
"Checkpointing requires the built-in candidate generator.")
75 algorithm._check_archive_weights()
77 archive.__class__.__name__, ()
if novelty
else tuple(archive.shape), archive.capacity, type(archive.items).__name__,
78 _bounds_signature(archive.fitness_domain), _bounds_signature(archive.features_domain),
79 tuple(archive.fitness_score_names), tuple(archive.features_score_names),
80 tuple(algorithm._fitness_weights),
None if novelty
else archive.discard_random_on_bin_overload,
81 tuple(map(tuple, archive.cluster_centers))
if type(archive)
is CVTGrid
else (),
82 algorithm.dimension, algorithm.batch_size, algorithm.budget,
84 if type(algorithm)
is CMAMAE:
85 return (*common,
"CMAMAE", version(
"cma"), tuple(algorithm.x0), algorithm.sigma0,
86 algorithm.ind_domain, algorithm.threshold_min, algorithm.learning_rate, algorithm.seed)
87 if type(algorithm)
is MOME:
88 return (*common,
"MOME", archive.max_items_per_bin, getattr(archive,
"truncation",
"random"),
89 algorithm.ind_domain, algorithm.iso_sigma, algorithm.line_sigma)
90 selection = algorithm._select_or_initialise_fn
91 if (
not isinstance(selection, partial)
or selection.func
is not tools.sel_or_init
92 or selection.keywords.get(
"sel_fn")
is not tools.sel_random
93 or algorithm._tell_fn
is not None or not algorithm.deepcopy_on_selection):
94 raise ValueError(
"Checkpointing requires built-in parent selection and feedback.")
95 return (*common, tuple(algorithm.ind_domain), algorithm.sel_pb, algorithm.init_pb, algorithm.mut_pb,
96 algorithm.eta, *novelty_settings)
100 return (__version__, platform.python_implementation(), platform.python_version(), np.__version__)
103def _read_checkpoint(path, settings):
104 with path.open(
"rb")
as file:
105 if file.readline(len(_HEADER) + 1) != _HEADER:
106 raise ValueError(
"Unsupported QDpy checkpoint format.")
107 state = pickle.load(file)
108 if state[
"environment"] != _environment()
or state[
"settings"] != settings:
109 raise ValueError(
"Checkpoint settings or Python, NumPy, and QDpy versions differ from this run.")
114def run_checkpointed(algorithm, evaluate, *, checkpoint_path, seed=0,
115 checkpoint_every=10, stop_after=None, resume=False, trusted=False, packed=False,
116 journal_path=None, evaluation_key=None, journal_executor=None, stop_requested=None,
118 """Run MAP-Elites, fixed Euclidean NSLC, CMA-MAE, or MOME with atomic checkpoints.
120 Supply a fresh supported optimiser for either a new run or a resume.
121 Its budget is the total search budget. MOME saves its ordered
122 Pareto fronts and generation count.
123 NSLC checkpoints save the active novelty archive and its plain
124 parent histories. The exact index is rebuilt on the next query.
125 ``checkpoint_every`` counts full batches. ``stop_after`` is a
126 cumulative evaluation count and must be a batch boundary or the
127 total budget. The last completed chunk is also saved.
129 To resume, pass ``resume=True, trusted=True`` with the same optimiser
130 settings, evaluator and runtime. Checkpoints contain the native
131 archive, counters and Python and NumPy global random generator states.
132 Supply only checkpoints you trust. The seed initializes a fresh run
133 and the checkpoint supplies the generator states when resuming.
134 Use one writer per path. External simulator state, callback state,
135 user-owned random generators, and side effects need caller management.
136 With ``packed=True``, the evaluator receives a whole batch and returns
137 one result per candidate in proposal order. It can use remote workers
138 for deterministic measurements or assign stable seeds itself.
139 With ``journal_path``, supply a scalar evaluator taking a numeric
140 individual and a stable seed. Use ``evaluation_key`` to identify the
141 simulator and settings, and optionally a caller-owned ``journal_executor``.
142 The evaluator should use the supplied seed with a local random generator.
143 The journal reuses returned measurements in proposal order on resume.
144 If ``stop_requested()`` returns true, pause at the next completed batch.
145 A signal handler can set the flag that this callable observes.
146 Resume mutates the supplied empty archive in place. The result's
147 evaluation count is the number of attempts in this invocation.
149 if type(packed)
is not bool:
150 raise TypeError(
"packed must be a bool.")
151 if journal_path
is not None:
152 if packed
or not isinstance(evaluation_key, str)
or not evaluation_key.strip():
153 raise ValueError(
"Journal runs need a scalar seeded evaluator and a nonempty evaluation_key.")
154 elif journal_executor
is not None or evaluation_key
is not None:
155 raise ValueError(
"journal_executor and evaluation_key require journal_path.")
156 if stop_requested
is not None and not callable(stop_requested):
157 raise TypeError(
"stop_requested must be callable.")
158 settings = (*_settings(algorithm), packed)
159 fixed_generation = algorithm._fixed_batch_feedback
160 emitter_state = _EMITTER_STATE.get(type(algorithm), ())
161 archive = algorithm.container
162 novelty = type(archive)
is NoveltyArchive
163 if len(algorithm.container)
or any(getattr(algorithm, name)
for name
in _COUNTERS):
164 raise ValueError(
"Supply a fresh optimiser with an empty archive.")
165 total = _positive_int(algorithm.budget,
"budget")
166 batch_size = _positive_int(algorithm.batch_size,
"batch_size")
167 interval = batch_size * _positive_int(checkpoint_every,
"checkpoint_every")
168 limit = total
if stop_after
is None else _positive_int(stop_after,
"stop_after")
169 if limit > total
or (limit < total
and limit % batch_size):
170 raise ValueError(
"stop_after must be a completed batch boundary within the budget.")
171 path = Path(checkpoint_path)
172 if journal_path
is not None and path.resolve() == Path(journal_path).resolve():
173 raise ValueError(
"Use different checkpoint and journal files.")
174 if resume
and not trusted:
175 raise ValueError(
"Resume requires trusted=True for a checkpoint you trust.")
176 if not resume
and (path.exists()
or path.is_symlink()):
177 raise FileExistsError(f
"A checkpoint already exists at {path}.")
178 path.parent.mkdir(parents=
True, exist_ok=
True)
182 state = _read_checkpoint(path, settings)
183 initial = state[
"counters"][
"_nb_evaluations"]
185 raise ValueError(
"stop_after precedes the saved evaluation count.")
186 if _observer
is not None:
187 _observer.check_resume(state.get(
"bundle"), initial)
188 header = state.get(
"journal")
189 if (header
is None) != (journal_path
is None)
or (
190 header
is not None and header[
"evaluation_key"] != evaluation_key):
191 raise ValueError(
"Resume with the checkpoint's journal and evaluation_key.")
192 if header
is not None:
194 for name, count
in state[
"counters"].items():
195 setattr(algorithm, name, count)
196 parents = archive.parents
197 vars(archive).update(vars(state[
"archive"]))
199 for parent, saved
in zip(parents, state[
"novelty_parents"], strict=
True):
200 vars(parent).update(vars(saved))
201 archive.parents = parents
202 for name
in emitter_state:
203 setattr(algorithm, name, state[
"emitter"][name])
204 elif journal_path
is not None:
205 journal_seed = index(seed)
206 if not 0 <= journal_seed < 2**32:
207 raise ValueError(
"Use a journal seed between 0 and 2**32 - 1.")
208 header = {
"kind": _KIND,
"version": 1,
"run": uuid4().hex,
"seed": journal_seed,
209 "evaluation_key": evaluation_key}
212 def save(*, full_batch_callback=False):
213 counts = {name: getattr(algorithm, name)
for name
in _COUNTERS}
214 for name
in _BATCH_COUNTERS:
216 counts[name] = 0
if full_batch_callback
and not fixed_generation
else getattr(algorithm, name)
218 "environment": _environment(),
"settings": settings,
"archive": algorithm.container,
220 "python_rng": random.getstate(),
"numpy_rng": np.random.get_state(),
223 snapshot[
"emitter"] = {name: getattr(algorithm, name)
for name
in emitter_state}
225 snapshot[
"novelty_parents"] = tuple(archive.parents)
226 if journal
is not None:
227 snapshot[
"journal"] = journal.header
228 if _observer
is not None:
229 snapshot[
"bundle"] = _observer.boundary()
230 _write(path, _HEADER + pickle.dumps(snapshot, protocol=pickle.HIGHEST_PROTOCOL))
232 def at_boundary(search, _elapsed):
233 if search.nb_evaluations < limit:
234 pause = stop_requested
is not None and stop_requested()
235 if pause
or search.nb_evaluations % interval == 0:
236 save(full_batch_callback=
True)
238 if not fixed_generation:
239 for name
in _BATCH_COUNTERS:
240 setattr(search, name, 0)
241 raise _PauseAtBoundary
243 def at_finish(_search, _elapsed):
246 def evaluate_batch(batch):
247 return journal.evaluate(evaluate, batch, algorithm.nb_evaluations, journal_executor)
249 observation = (nullcontext()
if _observer
is None
250 else _observer.record(algorithm, state[
"bundle"]
if resume
else None))
251 with _coordinator_seed(0
if resume
else seed), observation:
253 random.setstate(state[
"python_rng"])
254 np.random.set_state(state[
"numpy_rng"])
255 elif journal
is not None or _observer
is not None:
258 algorithm.add_callback(
"iteration", at_boundary)
259 algorithm.add_callback(
"finished_optimisation", at_finish)
261 best = algorithm.optimise(evaluate
if journal
is None else evaluate_batch, budget=limit - initial,
262 send_several_suggestions_to_fn=packed
or journal
is not None,
263 max_nb_suggestions_per_call=batch_size)
264 except _PauseAtBoundary:
265 best = algorithm.best()
266 except _JournalInterrupted
as error:
267 raise error.__cause__
from None
269 algorithm.budget = total
270 algorithm._callbacks.get(
"iteration").remove(at_boundary)
271 algorithm._callbacks.get(
"finished_optimisation").remove(at_finish)
273 best = algorithm.best()
274 return RunResult(algorithm, algorithm.container, best, algorithm.nb_evaluations - initial,
None)
Carry the outcome of one optimiser invocation.