QDpy
Loading...
Searching...
No Matches
mc_aurora.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# SPDX-License-Identifier: LGPL-3.0-or-later
3
4
6
7"""Explore several learned grids using a shared depot of observations."""
8
9import argparse
10from dataclasses import asdict
11from functools import partial
12from hashlib import sha256
13import json
14import math
15from pathlib import Path
16import random
17from time import perf_counter
18
19import numpy as np
20
21from qdpy.algorithms import AlternatingAlgWrapper, CuriosityMutPolyBounded, RandomSearchMutPolyBounded
22from qdpy.base import ParallelismManager
23from qdpy.benchmarks.artificial_landscapes import rastrigin_normalised
24from qdpy.containers import Container, Grid, MCAurora
25from qdpy.metrics import archive_originality, archive_overlap, pairwise_kl_coverage
26from qdpy.phenotype import Individual
27
28
29
33def evaluate(individual, *, task):
34 if task == "rastrigin":
35 observation = np.array(individual, dtype=np.float32)
36 return rastrigin_normalised(individual), tuple(individual[:2]), {"observation": observation}
37
38 # Dimensionless motion of a ball until it returns to ground level.
39 speed = 0.15 + 0.75 * individual[0]
40 angle = math.pi * (0.05 + 0.4 * individual[1])
41 vx, vy = speed * math.cos(angle), speed * math.sin(angle)
42 gravity = 2.2
43 flight_time = 2 * vy / gravity
44 times = np.minimum(np.linspace(0, 1, 64), flight_time)
45 observation = np.stack((vx * times, np.maximum(0.0, vy * times - gravity * times**2 / 2)))
46 landing_range = vx * flight_time
47 apex = vy**2 / (2 * gravity)
48 return (abs(landing_range - 0.28),), (landing_range, apex), {"observation": observation}
49
50
51
52def evaluate_pack(candidates, *, task):
53 return [evaluate(ind, task=task) for ind in candidates]
54
55
56
58def run(args):
59 try:
60 import torch
61 except ImportError as error:
62 raise SystemExit("Install PyTorch before running this example (python -m pip install torch).") from error
63 torch.set_num_threads(args.torch_threads)
64 random.seed(args.seed)
65 np.random.seed(args.seed)
66
67 dimension = 8 if args.task == "rastrigin" else 2
68 unit_square = ((0., 1.),) * 2
69 depot = Container(fitness_domain=((0., 1.),), fitness_weights=(-1.,), storage_type="orderedset")
70 grids = [Grid(shape=(args.bins, args.bins), features_domain=unit_square,
71 fitness_domain=((0., 1.),), storage_type="orderedset") for _ in range(args.archives)]
72
73 # The grids learn different descriptors from the same evaluated records.
74 aurora = MCAurora(grids, depot, observation_score="observation", training_period=args.training_period,
75 epochs=args.epochs, batch_size=args.training_batch_size, diversity=args.diversity,
76 diversity_weight=args.diversity_weight, rebuild_from=args.rebuild_from,
77 max_training_samples=args.max_training_samples, seed=args.seed)
78 start = perf_counter()
79 for _ in range(args.warmup):
80 ind = Individual(random.random() for _ in range(dimension))
81 fitness, features, scores = evaluate(ind, task=args.task)
82 ind.fitness.values, ind.features.values, ind.scores = fitness, features, scores
83 depot.add(ind)
84 aurora.fit()
85
86 emitter = CuriosityMutPolyBounded if args.selection == "curiosity" else RandomSearchMutPolyBounded
87 selection = {"init_pb": 0.1}
88 if emitter is RandomSearchMutPolyBounded:
89 selection["sel_pb"] = 0.9
90 algorithms = [emitter(grid, budget=args.budget, batch_size=args.batch_size, dimension=dimension,
91 mut_pb=1 / dimension, **selection) for grid in aurora.archives]
92 search = AlternatingAlgWrapper(algorithms, budget=args.budget, batch_size=args.batch_size,
93 tell_all=args.tell_all)
94 aurora.attach(search)
95
96 evaluate_fn = evaluate_pack if args.pack_size > 1 else evaluate
97 with ParallelismManager(args.executor, max_workers=args.workers) as parallel:
98 search.optimise(partial(evaluate_fn, task=args.task), executor=parallel.executor,
99 send_several_suggestions_to_fn=args.pack_size > 1,
100 max_nb_suggestions_per_call=args.pack_size)
101 elapsed = perf_counter() - start
102 if sum(alg.nb_suggestions for alg in algorithms) != search.nb_evaluations:
103 raise RuntimeError("The search did not complete its evaluation budget.")
104 if sum(alg.nb_evaluations for alg in algorithms) != search.nb_evaluations * (len(grids) if args.tell_all else 1):
105 raise RuntimeError("At least one evaluation failed to reach its archive.")
106 elites = {tuple(ind): ind for grid in grids for ind in grid}
107 return {
108 "task": args.task, "seed": args.seed, "selection": args.selection, "executor": args.executor,
109 "workers": args.workers, "tell_all": args.tell_all, "rebuild_from": args.rebuild_from,
110 "diversity_term": args.diversity, "diversity_weight": args.diversity_weight,
111 "warmup_evaluations": args.warmup, "search_evaluations": search.nb_evaluations,
112 "elapsed_seconds": elapsed, "depot_size": len(depot), "unique_elites": len(elites),
113 "filled_bins": [grid.filled_bins for grid in grids],
114 "qd_scores": [grid.qd_score() for grid in grids],
115 "best_fitness": min(grid.best_fitness.values[0] for grid in grids if grid.best is not None),
116 "originality": archive_originality(grids), "overlap": archive_overlap(grids).tolist(),
117 "reference_kl": pairwise_kl_coverage([tuple(ind.features) for ind in depot],
118 [tuple(ind.features) for ind in elites.values()],
119 ranges=unit_square),
120 "elite_fingerprint": sha256(json.dumps([sorted(tuple(ind) for ind in grid)
121 for grid in grids]).encode()).hexdigest(),
122 "training": [asdict(record) for record in aurora.training_history],
123 }
124
125
126
127def parse_args():
128 parser = argparse.ArgumentParser(description=__doc__)
129 parser.add_argument("--task", choices=("rastrigin", "trajectory"), default="rastrigin")
130 parser.add_argument("--seed", type=int, default=42)
131 parser.add_argument("--warmup", type=int, default=128, help="Random evaluations before search")
132 parser.add_argument("--budget", type=int, default=1024, help="Number of search evaluations")
133 parser.add_argument("--archives", type=int, default=2, help="Number of learned grids")
134 parser.add_argument("--bins", type=int, default=16, help="Bins per axis in each grid")
135 parser.add_argument("--training-period", type=int, default=256, help="Depot growth between refits")
136 parser.add_argument("--epochs", type=int, default=5, help="Training epochs per refit")
137 parser.add_argument("--training-batch-size", type=int, default=128)
138 parser.add_argument("--max-training-samples", type=int, default=4096)
139 parser.add_argument("--diversity", choices=("none", "outputs", "covariance", "correlation"), default="none")
140 parser.add_argument("--diversity-weight", type=float, default=0.1)
141 parser.add_argument("--rebuild-from", choices=("elites", "depot"), default="elites")
142 parser.add_argument("--tell-all", action="store_true", help="Offer each evaluation to every grid")
143 parser.add_argument("--selection", choices=("curiosity", "uniform"), default="curiosity")
144 parser.add_argument("--batch-size", type=int, default=64, help="Evaluations per search iteration")
145 parser.add_argument("--pack-size", type=int, default=1, help="Evaluations per worker call")
146 parser.add_argument("--executor", choices=("sequential", "multithreading", "concurrent"), default="sequential")
147 parser.add_argument("--workers", type=int, default=4)
148 parser.add_argument("--torch-threads", type=int, default=1)
149 parser.add_argument("--output", type=Path, help="Optional path for the JSON report")
150 args = parser.parse_args()
151 if min(args.warmup, args.archives) < 2 or min(args.budget, args.bins, args.batch_size, args.pack_size,
152 args.torch_threads, args.workers) < 1:
153 parser.error("Use at least two warmup evaluations and archives, and positive sizes and worker counts.")
154 return args
155
156
157if __name__ == "__main__":
158 settings = parse_args()
159 report = json.dumps(run(settings), indent=2, allow_nan=False)
160 if settings.output:
161 settings.output.write_text(report + "\n", encoding="utf-8")
162 print(report)