QDpy
Loading...
Searching...
No Matches
archive_reuse.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Seeded CPU controls for archive repair, ensemble selection, and exploration."""
6
7import argparse
8from copy import deepcopy
9import json
10from pathlib import Path
11import random
12from time import perf_counter
13
14import numpy as np
15
16from qdpy.algorithms import ARIA, NoveltySurpriseSearchLC, QDOES, SurpriseSearchLC, reevaluate_archive
17from qdpy.containers import Grid
18from qdpy.phenotype import Features, Fitness, Individual
19from qdpy.simple import nslc
20
21
22def _noisy(individual, seed):
23 position, sensitivity = individual
24 rng = np.random.default_rng(seed)
25 return (1. + .3 * sensitivity + rng.normal(scale=.02),), (
26 position + rng.normal(scale=.012 + .16 * sensitivity),)
27
28
29def _grid(shape, domain, best=2.):
30 return Grid(shape=shape, features_domain=domain, fitness_domain=((0., best),), fitness_weights=(1.,))
31
32
33def _offer(archive, vector, fitness, descriptor):
34 if archive.in_bounds(descriptor, archive.features_domain):
35 archive.add(Individual(list(vector), fitness=Fitness(fitness, weights=(1.,)), features=Features(descriptor)))
36
37
38
39def aria_trial(seed, budget):
40 """Start from the same three noisy elites and hold audit rollouts out."""
41 source = _grid((9,), ((0., 1.),))
42 for position in (.17, .5, .83):
43 _offer(source, [position, .65], (1.195,), (position,))
44 for method in ("aria", "continue"):
45 start = perf_counter()
46 if method == "aria":
47 result = ARIA(source, steps=5, population_size=12, samples=12,
48 sigma=.12, learning_rate=.09, ind_domain=(0., 1.), seed=seed).run(_noisy, budget)
49 archive, evaluations = result.archive, result.rollouts
50 completion = result.completion_cells
51 failed = result.failed_rollouts
52 else:
53 rng = np.random.default_rng(seed)
54 archive = deepcopy(source)
55 # Match the attempted rollout budget ARIA can use on this geometry.
56 evaluations = min(budget // 72, 9) * 72
57 completion = failed = 0
58 for _ in range(evaluations):
59 parent = archive[rng.integers(len(archive))]
60 vector = np.clip(parent + rng.normal(scale=.12, size=2), 0., 1.)
61 _offer(archive, vector, *_noisy(vector, int(rng.integers(2**32))))
62 audit = reevaluate_archive(archive, _noisy, samples=64, seed=10_000 + seed, estimator="mean")
63 yield dict(method=method, seed=seed, rollouts=evaluations, failed=failed, completion=completion,
64 audit_rollouts=audit.rollouts, retention=1. - audit.rollout_cell_change,
65 coverage=audit.corrected_coverage, qd_score=audit.corrected_qd_score,
66 elapsed_s=perf_counter() - start)
67
68
69def _classification_pool(seed):
70 rng = np.random.default_rng(seed)
71 slopes = np.linspace(-.3, .3, 12)
72 config = [{"family": "A" if i % 2 else "B", "offset": float(slope)}
73 for i, slope in enumerate(slopes)]
74
75 def sample(size):
76 x, y = rng.normal(size=(2, size))
77 labels = (x + .6 * y + rng.normal(scale=.4, size=size) > 0).astype(int)
78 logits = 2.5 * x + (1.5 + slopes[:, None]) * y + 4 * slopes[:, None]
79 logits += rng.normal(scale=.9, size=logits.shape)
80 probability = 1. / (1. + np.exp(-logits))
81 return np.stack((1 - probability, probability), axis=2), labels
82
83 return sample(120), sample(512), config
84
85
86
87def ensemble_trial(seed, budget):
88 """Use the same model pool and the same number of scored ensembles per method."""
89 (validation, labels), (test, test_labels), config = _classification_pool(seed)
90 for mode in ("qdo", "quality", "greedy"):
91 start = perf_counter()
92 result = QDOES(validation, labels, configurations=config, bins=4, batch_size=12,
93 remap_frequency=24, seed=seed).fit(budget, mode=mode)
94 test_predictions = result.predict_proba(test)
95 test_loss = -np.log(test_predictions[np.arange(len(test_labels)), test_labels]).mean()
96 yield dict(method=mode, seed=seed, evaluations=result.evaluations, validation=result.validation_loss,
97 test=float(test_loss), active=int(np.count_nonzero(result.counts)),
98 bins=None if result.archive is None else result.archive.filled_bins,
99 elapsed_s=perf_counter() - start)
100
101
102def _maze(individual, seed, gaps=(4, 1)):
103 position = np.array([0, 0])
104 directions = np.array([[1, 0], [0, 1], [-1, 0], [0, -1]])
105 for gene in individual:
106 candidate = np.clip(position + directions[min(3, int(4 * gene))], 0, 6)
107 x, y = candidate
108 if (x != 2 or y == gaps[0]) and (x != 4 or y == gaps[1]):
109 position = candidate
110 return (1. - np.linalg.norm(position - 6) / np.sqrt(72.),), tuple(position / 6.)
111
112
113
114def surprise_trial(seed, budget):
115 """Expose the same 7-by-7 reporting geometry to both navigation runs."""
116 for method in ("surprise", "nslc"):
117 start = perf_counter()
118 archive = _grid((7, 7), ((0., 1.),) * 2, 1.)
119 if method == "surprise":
120 result = SurpriseSearchLC(archive, 20, population_size=24, clusters=8, seed=seed).run(_maze, budget)
121 evaluations, forecasts = result.evaluations, result.forecasts
122 else:
123 random.seed(seed)
124 np.random.seed(seed)
125 algorithm = nslc(dimension=20, budget=budget, fitness_domain=((0., 1.),),
126 features_domain=((0., 1.),) * 2, threshold_novelty=.13,
127 k=5, optimisation_task="maximisation")
128 for step in range(budget):
129 candidate = algorithm.ask()
130 fitness, descriptor = _maze(candidate, step)
131 algorithm.tell(candidate, fitness, descriptor)
132 _offer(archive, candidate, fitness, descriptor)
133 evaluations, forecasts = budget, 0
134 yield dict(method=method, seed=seed, evaluations=evaluations, forecasts=forecasts,
135 coverage=archive.filled_bins / 49, qd_score=archive.qd_score(),
136 best=archive.best.fitness.values[0], elapsed_s=perf_counter() - start)
137
138
139
140def surprise_hybrid_trials(seed, budget):
141 """Report measured endpoints in the same grid for every search."""
142 for maze, gaps in enumerate(((4, 1), (3, 5), (5, 2))):
143 def evaluate(individual, evaluation_seed):
144 return _maze(individual, evaluation_seed, gaps)
145
146 for method in ("nslc", "ss-lc", "nss-lc", "ns-ss-lc"):
147 archive = _grid((7, 7), ((0., 1.),) * 2, 1.)
148 if method == "nslc":
149 random.seed(seed)
150 np.random.seed(seed)
151 search = nslc(dimension=40, budget=budget, fitness_domain=((0., 1.),),
152 features_domain=((0., 1.),) * 2, threshold_novelty=.13,
153 k=5, optimisation_task="maximisation")
154 for index in range(budget):
155 candidate = search.ask()
156 quality, behavior = evaluate(candidate, index)
157 search.tell(candidate, quality, behavior)
158 _offer(archive, candidate, quality, behavior)
159 evaluations, forecasts, failures = budget, 0, 0
160 else:
161 options = dict(population_size=24, clusters=8, seed=seed)
162 if method == "ss-lc":
163 search = SurpriseSearchLC(archive, 40, **options)
164 else:
165 weight = .5 if method == "nss-lc" else None
166 search = NoveltySurpriseSearchLC(archive, 40, novelty_weight=weight,
167 novelty_threshold=.13, **options)
168 result = search.run(evaluate, budget)
169 evaluations, forecasts, failures = result.evaluations, result.forecasts, result.failed_evaluations
170 yield dict(task="maze", method=method, maze=maze, seed=seed, evaluations=evaluations,
171 forecasts=forecasts, failed_evaluations=failures, cells=len(archive),
172 qd_score=archive.qd_score(), best=archive.best.fitness.values[0])
173
174
175def main():
176 """Write one JSON object per method and seed."""
177 parser = argparse.ArgumentParser(description=__doc__)
178 parser.add_argument("study", choices=("aria", "ensemble", "surprise", "surprise-hybrids"))
179 parser.add_argument("--seeds", type=int, nargs="+", default=[0])
180 parser.add_argument("--budget", type=int)
181 parser.add_argument("--output", type=Path)
182 args = parser.parse_args()
183 trial, default = {"aria": (aria_trial, 648), "ensemble": (ensemble_trial, 300),
184 "surprise": (surprise_trial, 360), "surprise-hybrids": (surprise_hybrid_trials, 240)}[args.study]
185 if args.budget is not None and args.budget < 1:
186 parser.error("--budget must be positive.")
187 records = []
188 for seed in args.seeds:
189 for row in trial(seed, default if args.budget is None else args.budget):
190 line = json.dumps(row)
191 print(line)
192 records.append(line)
193 if args.output is not None:
194 args.output.parent.mkdir(parents=True, exist_ok=True)
195 args.output.write_text("\n".join(records) + "\n", encoding="utf-8")
196
197
198if __name__ == "__main__":
199 main()