5"""Seeded CPU controls for archive repair, ensemble selection, and exploration."""
8from copy
import deepcopy
10from pathlib
import Path
12from time
import perf_counter
16from qdpy.algorithms import ARIA, NoveltySurpriseSearchLC, QDOES, SurpriseSearchLC, reevaluate_archive
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),)
29def _grid(shape, domain, best=2.):
30 return Grid(shape=shape, features_domain=domain, fitness_domain=((0., best),), fitness_weights=(1.,))
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)))
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()
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
53 rng = np.random.default_rng(seed)
54 archive = deepcopy(source)
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)
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)]
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
83 return sample(120), sample(512), config
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)
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)
108 if (x != 2
or y == gaps[0])
and (x != 4
or y == gaps[1]):
110 return (1. - np.linalg.norm(position - 6) / np.sqrt(72.),), tuple(position / 6.)
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
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)
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)
146 for method
in (
"nslc",
"ss-lc",
"nss-lc",
"ns-ss-lc"):
147 archive = _grid((7, 7), ((0., 1.),) * 2, 1.)
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
161 options = dict(population_size=24, clusters=8, seed=seed)
162 if method ==
"ss-lc":
163 search = SurpriseSearchLC(archive, 40, **options)
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])
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.")
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)
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")
198if __name__ ==
"__main__":