QDpy
Loading...
Searching...
No Matches
resume_map_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Resume a trusted MAP-Elites, NSLC, CMA-MAE, or MOME checkpoint."""
6
7import argparse
8from contextlib import nullcontext
9from pathlib import Path
10import signal
11
12from qdpy.algorithms import CMAMAE, MOME, RandomSearchMutPolyBounded
13from qdpy.base import ParallelismManager
14from qdpy.benchmarks import illumination_rastrigin_normalised
15from qdpy.checkpoints import run_checkpointed
16from qdpy.containers import CVTGrid, Grid, ParetoGrid
17from qdpy.journal import read_evaluation_journal
18from qdpy.results import export_grid, grid_to_dataframe, load_grid
19from qdpy.simple import map_elites, nslc
20
21
22def create_search(kind, budget, *, method="map", seed=17):
23 """Recreate the search settings in both processes."""
24 unit = (0.0, 1.0)
25 settings = dict(dimension=3, batch_size=8, budget=budget)
26 bounds = dict(fitness_domain=(unit,), features_domain=(unit, unit))
27 if method == "mome":
28 if kind != "grid":
29 raise ValueError("MOME uses a rectangular ParetoGrid. Choose --kind grid.")
30 archive = ParetoGrid(shape=(2, 2), max_items_per_bin=4, fitness_domain=(unit, unit),
31 features_domain=(unit, unit), truncation="crowding")
32 return MOME(archive, **settings)
33 if method == "nslc":
34 search = nslc(threshold_novelty=0.12, k=5, **bounds, **settings)
35 search.container.indexed = True
36 return search
37 if kind == "grid" and method == "map":
38 return map_elites(shape=(2, 2), **bounds, **settings)
39 # Fixed centroids avoid fitting a new tessellation while resuming.
40 centroids = [(0.15, 0.20), (0.45, 0.75), (0.75, 0.25), (0.90, 0.80)]
41 grid = Grid(shape=(2, 2), **bounds) if kind == "grid" else CVTGrid(shape=4, centroids=centroids, **bounds)
42 if method == "cma-mae":
43 return CMAMAE(grid, budget=budget, x0=[0.5] * 3, sigma0=0.15, threshold_min=-1.0,
44 batch_size=8, ind_domain=unit, seed=seed)
45 return RandomSearchMutPolyBounded(grid, **settings)
46
47
48def seeded_rastrigin(genome, _seed):
49 """Evaluate deterministic Rastrigin through the seeded journal interface."""
50 return illumination_rastrigin_normalised(genome)
51
52
53def evaluate_tradeoff(genome, _seed=None):
54 """Evaluate two competing costs and use the remaining genes as descriptors."""
55 x, y, z = genome
56 return (x**2, (1. - x)**2), (y, z)
57
58
59def main(argv=None):
60 """Read CLI settings and publish a portable result at the chosen boundary."""
61 parser = argparse.ArgumentParser(description=__doc__)
62 parser.add_argument("output", type=Path)
63 parser.add_argument("--kind", choices=("grid", "cvt"), default="grid")
64 parser.add_argument("--method", choices=("map", "nslc", "cma-mae", "mome"), default="map")
65 parser.add_argument("--budget", type=int, default=67)
66 parser.add_argument("--seed", type=int, default=17, help="Coordinator seed for a fresh search.")
67 parser.add_argument("--stop-after", type=int)
68 parser.add_argument("--resume-trusted", action="store_true")
69 parser.add_argument("--ray-address", help="Use ordered Ray evaluations. Pass local for a local runtime.")
70 parser.add_argument("--workers", type=int, default=2, help="Number of workers for local Ray.")
71 parser.add_argument("--journal", action="store_true", help="Keep a durable evaluation journal.")
72 parser.add_argument("--slurm-signal", action="store_true", help="Checkpoint and pause after SIGUSR1.")
73 args = parser.parse_args(argv)
74 try:
75 search = create_search(args.kind, args.budget, method=args.method, seed=args.seed)
76 except ValueError as error:
77 parser.error(str(error))
78 evaluate = evaluate_tradeoff if args.method == "mome" else illumination_rastrigin_normalised
79 stop = False
80
81 def on_time_limit(_signum, _frame):
82 nonlocal stop
83 stop = True
84
85 if args.slurm_signal:
86 signal.signal(signal.SIGUSR1, on_time_limit)
87 manager = (nullcontext() if args.ray_address is None
88 else ParallelismManager("ray", max_workers=args.workers, ray_address=args.ray_address))
89 with manager as parallelism:
90 def evaluate_batch(batch):
91 return list(parallelism.executor.map(evaluate, batch))
92
93 evaluator = evaluate if parallelism is None else evaluate_batch
94 options = {"packed": parallelism is not None}
95 if args.journal:
96 evaluator = evaluate_tradeoff if args.method == "mome" else seeded_rastrigin
97 evaluation_key = "mome-tradeoff-v1" if args.method == "mome" else "rastrigin-v1"
98 options = {"journal_path": args.output / "evaluations.jsonl", "evaluation_key": evaluation_key,
99 "journal_executor": None if parallelism is None else parallelism.executor}
100 result = run_checkpointed(search, evaluator,
101 checkpoint_path=args.output / "checkpoint.pkl", checkpoint_every=2,
102 stop_after=args.stop_after, seed=args.seed, resume=args.resume_trusted,
103 trusted=args.resume_trusted, stop_requested=lambda: stop, **options)
104 if args.method == "nslc":
105 print(f"{result.evaluations} new evaluations, {search.nb_evaluations} total, "
106 f"{len(result.archive)} active, {len(result.archive.parents[0])} parent entries")
107 else:
108 path = args.output / "archive.json"
109 digest = export_grid(result.archive, path)
110 archive = load_grid(path, expected_sha256=digest)
111 print(f"{result.evaluations} new evaluations, {search.nb_evaluations} total, SHA-256 {digest}")
112 print(grid_to_dataframe(archive)[["cell", "fitness", "descriptors"]].to_string(index=False))
113 if args.journal:
114 journal = read_evaluation_journal(args.output / "evaluations.jsonl")
115 print(f"{journal['returned_calls']} returned calls, {journal['failed_calls']} failed, "
116 f"{journal['uncertain_calls']} uncertain dispatches")
117
118
119if __name__ == "__main__":
120 main()