Source code for qdpy.checkpoints

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Batch-boundary restart for native MAP-Elites with ordered feedback.

"""Save and resume ordered MAP-Elites, NSLC, CMA-MAE, and MOME runs."""

from functools import partial
from contextlib import nullcontext
from importlib.metadata import version
from operator import index
from pathlib import Path
import pickle
import platform
import random
from uuid import uuid4

import numpy as np

from qdpy import __version__, tools
from qdpy.algorithms import CMAMAE, MOME, RandomSearchMutPolyBounded
from qdpy.containers import Container, CVTGrid, Grid, NoveltyArchive, ParetoGrid
from qdpy.journal import _EvaluationJournal, _JournalInterrupted, _KIND
from qdpy.results import _write
from qdpy.simple import RunResult, _coordinator_seed, _positive_int

__all__ = ["run_checkpointed"]

_HEADER = b"QDpy MAP-Elites checkpoint 1\n"
_COUNTERS = ("_nb_suggestions", "_nb_evaluations", "_nb_updated")
_BATCH_COUNTERS = tuple(name + "_in_iteration" for name in _COUNTERS)
_EMITTER_STATE = {
    CMAMAE: ("_completed_generations", "_strategy", "_rng", "_thresholds", "_search_elites"),
    MOME: ("_completed_generations",),
}


class _PauseAtBoundary(BaseException):
    """Exit the native schedule after committing a complete batch."""


def _bounds_signature(bounds):
    return None if bounds is None else tuple(map(tuple, bounds))


def _novelty_settings(archive):
    """Describe fixed Euclidean novelty and each parent admission policy."""
    if (archive.novelty_distance != "euclidean" or not archive.parents
            or any(type(parent) is not Container or parent.parents for parent in archive.parents)):
        raise ValueError("Checkpointed NSLC needs Euclidean novelty with plain parentless Container histories.")
    first_slot = {}
    return (
        archive.k, archive.threshold_novelty, archive.indexed, archive.only_add_accepted_inds_to_parents,
        tuple((first_slot.setdefault(id(parent), slot), type(parent.items).__name__, parent.capacity,
               _bounds_signature(parent.fitness_domain), _bounds_signature(parent.features_domain),
               tuple(parent.fitness_score_names), tuple(parent.features_score_names),
               None if parent.fitness_weights is None else tuple(parent.fitness_weights))
              for slot, parent in enumerate(archive.parents)),
    )


def _settings(algorithm):
    """Describe the search state whose reconstruction is covered by this codec."""
    if type(algorithm) not in (RandomSearchMutPolyBounded, CMAMAE, MOME):
        raise ValueError("Checkpointing supports RandomSearchMutPolyBounded, CMAMAE, and MOME.")
    archive = algorithm.container
    novelty = type(archive) is NoveltyArchive
    if type(algorithm) is MOME:
        if type(archive) is not ParetoGrid or archive.parents:
            raise ValueError("Checkpointed MOME requires a native parentless ParetoGrid.")
    elif not novelty and (type(archive) not in (Grid, CVTGrid) or archive.parents or archive.max_items_per_bin != 1):
        raise ValueError("Use a parentless, best-only Grid or CVTGrid, or a fixed NoveltyArchive.")
    novelty_settings = _novelty_settings(archive) if novelty else ()
    if algorithm._base_ind_gen is not None:
        raise ValueError("Checkpointing requires the built-in candidate generator.")
    algorithm._check_archive_weights()
    common = (
        archive.__class__.__name__, () if novelty else tuple(archive.shape), archive.capacity, type(archive.items).__name__,
        _bounds_signature(archive.fitness_domain), _bounds_signature(archive.features_domain),
        tuple(archive.fitness_score_names), tuple(archive.features_score_names),
        tuple(algorithm._fitness_weights), None if novelty else archive.discard_random_on_bin_overload,
        tuple(map(tuple, archive.cluster_centers)) if type(archive) is CVTGrid else (),
        algorithm.dimension, algorithm.batch_size, algorithm.budget,
    )
    if type(algorithm) is CMAMAE:
        return (*common, "CMAMAE", version("cma"), tuple(algorithm.x0), algorithm.sigma0,
                algorithm.ind_domain, algorithm.threshold_min, algorithm.learning_rate, algorithm.seed)
    if type(algorithm) is MOME:
        return (*common, "MOME", archive.max_items_per_bin, getattr(archive, "truncation", "random"),
                algorithm.ind_domain, algorithm.iso_sigma, algorithm.line_sigma)
    selection = algorithm._select_or_initialise_fn
    if (not isinstance(selection, partial) or selection.func is not tools.sel_or_init
            or selection.keywords.get("sel_fn") is not tools.sel_random
            or algorithm._tell_fn is not None or not algorithm.deepcopy_on_selection):
        raise ValueError("Checkpointing requires built-in parent selection and feedback.")
    return (*common, tuple(algorithm.ind_domain), algorithm.sel_pb, algorithm.init_pb, algorithm.mut_pb,
            algorithm.eta, *novelty_settings)


def _environment():
    return (__version__, platform.python_implementation(), platform.python_version(), np.__version__)


def _read_checkpoint(path, settings):
    with path.open("rb") as file:
        if file.readline(len(_HEADER) + 1) != _HEADER:
            raise ValueError("Unsupported QDpy checkpoint format.")
        state = pickle.load(file)
    if state["environment"] != _environment() or state["settings"] != settings:
        raise ValueError("Checkpoint settings or Python, NumPy, and QDpy versions differ from this run.")
    return state


## @brief Run to a batch boundary and optionally continue a previous search.
[docs] def run_checkpointed(algorithm, evaluate, *, checkpoint_path, seed=0, checkpoint_every=10, stop_after=None, resume=False, trusted=False, packed=False, journal_path=None, evaluation_key=None, journal_executor=None, stop_requested=None, _observer=None): """Run MAP-Elites, fixed Euclidean NSLC, CMA-MAE, or MOME with atomic checkpoints. Supply a fresh supported optimiser for either a new run or a resume. Its budget is the total search budget. MOME saves its ordered Pareto fronts and generation count. NSLC checkpoints save the active novelty archive and its plain parent histories. The exact index is rebuilt on the next query. ``checkpoint_every`` counts full batches. ``stop_after`` is a cumulative evaluation count and must be a batch boundary or the total budget. The last completed chunk is also saved. To resume, pass ``resume=True, trusted=True`` with the same optimiser settings, evaluator and runtime. Checkpoints contain the native archive, counters and Python and NumPy global random generator states. Supply only checkpoints you trust. The seed initializes a fresh run and the checkpoint supplies the generator states when resuming. Use one writer per path. External simulator state, callback state, user-owned random generators, and side effects need caller management. With ``packed=True``, the evaluator receives a whole batch and returns one result per candidate in proposal order. It can use remote workers for deterministic measurements or assign stable seeds itself. With ``journal_path``, supply a scalar evaluator taking a numeric individual and a stable seed. Use ``evaluation_key`` to identify the simulator and settings, and optionally a caller-owned ``journal_executor``. The evaluator should use the supplied seed with a local random generator. The journal reuses returned measurements in proposal order on resume. If ``stop_requested()`` returns true, pause at the next completed batch. A signal handler can set the flag that this callable observes. Resume mutates the supplied empty archive in place. The result's evaluation count is the number of attempts in this invocation. """ if type(packed) is not bool: raise TypeError("packed must be a bool.") if journal_path is not None: if packed or not isinstance(evaluation_key, str) or not evaluation_key.strip(): raise ValueError("Journal runs need a scalar seeded evaluator and a nonempty evaluation_key.") elif journal_executor is not None or evaluation_key is not None: raise ValueError("journal_executor and evaluation_key require journal_path.") if stop_requested is not None and not callable(stop_requested): raise TypeError("stop_requested must be callable.") settings = (*_settings(algorithm), packed) fixed_generation = algorithm._fixed_batch_feedback emitter_state = _EMITTER_STATE.get(type(algorithm), ()) archive = algorithm.container novelty = type(archive) is NoveltyArchive if len(algorithm.container) or any(getattr(algorithm, name) for name in _COUNTERS): raise ValueError("Supply a fresh optimiser with an empty archive.") total = _positive_int(algorithm.budget, "budget") batch_size = _positive_int(algorithm.batch_size, "batch_size") interval = batch_size * _positive_int(checkpoint_every, "checkpoint_every") limit = total if stop_after is None else _positive_int(stop_after, "stop_after") if limit > total or (limit < total and limit % batch_size): raise ValueError("stop_after must be a completed batch boundary within the budget.") path = Path(checkpoint_path) if journal_path is not None and path.resolve() == Path(journal_path).resolve(): raise ValueError("Use different checkpoint and journal files.") if resume and not trusted: raise ValueError("Resume requires trusted=True for a checkpoint you trust.") if not resume and (path.exists() or path.is_symlink()): raise FileExistsError(f"A checkpoint already exists at {path}.") path.parent.mkdir(parents=True, exist_ok=True) initial = 0 journal = None if resume: state = _read_checkpoint(path, settings) initial = state["counters"]["_nb_evaluations"] if initial > limit: raise ValueError("stop_after precedes the saved evaluation count.") if _observer is not None: _observer.check_resume(state.get("bundle"), initial) header = state.get("journal") if (header is None) != (journal_path is None) or ( header is not None and header["evaluation_key"] != evaluation_key): raise ValueError("Resume with the checkpoint's journal and evaluation_key.") if header is not None: journal = _EvaluationJournal(journal_path, header, resume=True) for name, count in state["counters"].items(): setattr(algorithm, name, count) parents = archive.parents vars(archive).update(vars(state["archive"])) if novelty: for parent, saved in zip(parents, state["novelty_parents"], strict=True): vars(parent).update(vars(saved)) archive.parents = parents for name in emitter_state: setattr(algorithm, name, state["emitter"][name]) elif journal_path is not None: journal_seed = index(seed) if not 0 <= journal_seed < 2**32: raise ValueError("Use a journal seed between 0 and 2**32 - 1.") header = {"kind": _KIND, "version": 1, "run": uuid4().hex, "seed": journal_seed, "evaluation_key": evaluation_key} journal = _EvaluationJournal(journal_path, header, resume=False) def save(*, full_batch_callback=False): counts = {name: getattr(algorithm, name) for name in _COUNTERS} for name in _BATCH_COUNTERS: # The native scheduler clears the iteration counters after callbacks. counts[name] = 0 if full_batch_callback and not fixed_generation else getattr(algorithm, name) snapshot = { "environment": _environment(), "settings": settings, "archive": algorithm.container, "counters": counts, "python_rng": random.getstate(), "numpy_rng": np.random.get_state(), } if emitter_state: snapshot["emitter"] = {name: getattr(algorithm, name) for name in emitter_state} if novelty: snapshot["novelty_parents"] = tuple(archive.parents) if journal is not None: snapshot["journal"] = journal.header if _observer is not None: snapshot["bundle"] = _observer.boundary() _write(path, _HEADER + pickle.dumps(snapshot, protocol=pickle.HIGHEST_PROTOCOL)) def at_boundary(search, _elapsed): if search.nb_evaluations < limit: pause = stop_requested is not None and stop_requested() if pause or search.nb_evaluations % interval == 0: save(full_batch_callback=True) if pause: if not fixed_generation: for name in _BATCH_COUNTERS: setattr(search, name, 0) raise _PauseAtBoundary def at_finish(_search, _elapsed): save() def evaluate_batch(batch): return journal.evaluate(evaluate, batch, algorithm.nb_evaluations, journal_executor) observation = (nullcontext() if _observer is None else _observer.record(algorithm, state["bundle"] if resume else None)) with _coordinator_seed(0 if resume else seed), observation: if resume: random.setstate(state["python_rng"]) np.random.set_state(state["numpy_rng"]) elif journal is not None or _observer is not None: save() if initial < limit: algorithm.add_callback("iteration", at_boundary) algorithm.add_callback("finished_optimisation", at_finish) try: best = algorithm.optimise(evaluate if journal is None else evaluate_batch, budget=limit - initial, send_several_suggestions_to_fn=packed or journal is not None, max_nb_suggestions_per_call=batch_size) except _PauseAtBoundary: best = algorithm.best() except _JournalInterrupted as error: raise error.__cause__ from None finally: algorithm.budget = total algorithm._callbacks.get("iteration").remove(at_boundary) algorithm._callbacks.get("finished_optimisation").remove(at_finish) else: best = algorithm.best() return RunResult(algorithm, algorithm.container, best, algorithm.nb_evaluations - initial, None)