QDpy
Loading...
Searching...
No Matches
verified_symmetry_manifold.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Compare each method against a matched baseline on bounded seeded workloads."""
6
7import argparse
8import json
9import random
10from collections import deque
11from itertools import permutations, product
12from pathlib import Path
13from time import perf_counter
14
15import numpy as np
16
17from qdpy.algorithms import (
18 CounterexampleMAPElites,
19 DDEElites,
20 IsoLineMAPElites,
21 PolicyManifoldSearch,
22 ScenarioRiskMAPElites,
23 SymmetryAwareMAPElites,
24)
25from qdpy.containers import Grid
26
27
28_DURATIONS = (3, 3, 2, 4, 2, 2, 1, 3)
29_DEADLINES = (5, 5, 7, 9, 10, 11, 12, 13)
30_SCENARIOS = (None, *range(len(_DURATIONS)))
31_INITIAL_SCENARIOS = (None, 6, 7)
32_EDGES = tuple((i, j) for i in range(5) for j in range(i + 1, 5) if (i, j) != (0, 1))
33_EDGE_INDEX = {edge: i for i, edge in enumerate(_EDGES)}
34_LABELS = ((0, 1, *internal) for internal in permutations((2, 3, 4)))
35_RELABELS = tuple(tuple(_EDGE_INDEX[tuple(sorted((perm[i], perm[j])))] for i, j in _EDGES)
36 for perm in _LABELS)
37_CONTROL_STEPS = 24
38_CONTROL_DIMENSION = 16
39
40
41def _binary_proposal(size):
42 def propose(rng):
43 return tuple(map(int, rng.integers(2, size=size)))
44 return propose
45
46
47def _flip(parent, rng):
48 child = list(parent)
49 index = rng.integers(len(child))
50 child[index] = 1 - child[index]
51 return tuple(child)
52
53
54def _summary(archive):
55 return dict(cells=len(archive), qd_score=sum(elite.fitness.values[0] for elite in archive))
56
57
58def schedule_measure(genome):
59 """Measure nominal makespan and describe assignment balance and switches."""
60 loads = _completion_times(genome, None)
61 quality = 1. / max(loads)
62 switches = sum(first != second for first, second in zip(genome, genome[1:]))
63 return (quality,), (sum(genome), switches)
64
65
66def _completion_times(genome, delayed_job):
67 loads, completion = [0, 0], []
68 for job, (machine, duration) in enumerate(zip(genome, _DURATIONS, strict=True)):
69 loads[machine] += duration + 2 * (delayed_job == job)
70 completion.append(loads[machine])
71 return completion
72
73
74def schedule_check(genome, delayed_job):
75 """Check every deadline after delaying the selected job by two time units."""
76 return all(finish <= deadline for finish, deadline in zip(_completion_times(genome, delayed_job), _DEADLINES))
77
78
79def _schedule_grid():
80 return Grid(shape=(9, 8), features_domain=((0, 9), (0, 8)),
81 fitness_domain=((.001, 1.),), fitness_weights=(1.,))
82
83
84def _schedule_optima(archive):
85 best = {}
86 for genome in product((0, 1), repeat=len(_DURATIONS)):
87 if all(schedule_check(genome, case) for case in _SCENARIOS):
88 (fitness,), features = schedule_measure(genome)
89 cell = archive.index_grid(features)
90 best[cell] = max(fitness, best.get(cell, 0.))
91 return best
92
93
94def compare_scheduling(budget, seed):
95 """Compare verified coverage on fixed and counterexample-driven screening."""
96 initializer = _binary_proposal(len(_DURATIONS))
97 oracle = _schedule_optima(_schedule_grid())
98 check_limit = budget * len(_INITIAL_SCENARIOS)
99 matched_limit = check_limit
100 for method in ("counterexample", "fixed-panel", "fixed-panel-matched-checks"):
101 archive = _schedule_grid()
102 limit = matched_limit if method == "fixed-panel-matched-checks" else check_limit
103 if method == "counterexample":
104 search = CounterexampleMAPElites(
105 archive, _SCENARIOS, initial_scenarios=_INITIAL_SCENARIOS,
106 propose=initializer, mutate=_flip, measure=schedule_measure, verify=schedule_check, seed=seed,
107 )
108 stats = search.run(proposals=budget, checks=limit)
109 attempts, checks, learned = stats.proposals, stats.checks, stats.counterexamples
110 panel_size = len(_INITIAL_SCENARIOS)
111 matched_limit = ((checks + panel_size - 1) // panel_size) * panel_size
112 else:
113 # The worst score on this fixed panel must be positive for admission.
114 search = ScenarioRiskMAPElites(
115 archive, _INITIAL_SCENARIOS, initializer=initializer, mutate=_flip,
116 tail_fraction=1. / len(_INITIAL_SCENARIOS), objective="cvar", seed=seed,
117 )
118
119 def evaluate(genome, case):
120 (quality,), features = schedule_measure(genome)
121 return quality if schedule_check(genome, case) else 0., features
122
123 stats = search.run(evaluate, limit)
124 attempts, checks, learned = stats.candidates, stats.scenario_calls, 0
125 audited = {}
126 for elite in archive:
127 # Audit every scenario for every elite in both arms.
128 passed = [schedule_check(elite, case) for case in _SCENARIOS]
129 if all(passed):
130 audited[archive.index_grid(elite)] = elite.fitness.values[0]
131 assert all(cell in oracle and quality <= oracle[cell] for cell, quality in audited.items())
132 if method == "counterexample":
133 assert len(audited) == len(archive)
134 proposal_limit = budget if method == "counterexample" else limit // len(_INITIAL_SCENARIOS)
135 yield dict(task="scheduling", method=method, seed=seed, proposal_limit=proposal_limit, proposals=attempts,
136 check_limit=limit, checks=checks, audit_checks=len(_SCENARIOS) * len(archive),
137 counterexamples=learned, reachable_cells=len(oracle), archive_cells=len(archive),
138 verified_cells=len(audited), verified_qd_score=sum(audited.values()))
139
140
141def canonical_network(genome):
142 """Return the lexicographically first network under internal-node relabeling."""
143 return min(tuple(genome[index] for index in permutation) for permutation in _RELABELS)
144
145
146def network_measure(genome):
147 """Score terminal connectivity and the number of tolerated single-edge failures."""
148 present = tuple(edge for edge, enabled in zip(_EDGES, genome, strict=True) if enabled)
149 locations = [set() for _ in range(5)]
150 for i, j in present:
151 locations[i].add(j)
152 locations[j].add(i)
153
154 def distance():
155 queue, visited = deque([(0, 0)]), {0}
156 while queue:
157 vertex, depth = queue.popleft()
158 if vertex == 1:
159 return depth
160 for successor in locations[vertex] - visited:
161 visited.add(successor)
162 queue.append((successor, depth + 1))
163 return 0
164
165 hops = distance()
166 if not hops:
167 return (0.,), (len(present), 0)
168 resilient = 0
169 for first, second in present:
170 locations[first].remove(second)
171 locations[second].remove(first)
172 resilient += bool(distance())
173 locations[first].add(second)
174 locations[second].add(first)
175 return ((1. + resilient) / (len(_EDGES) + 1),), (len(present), hops)
176
177
178def _network_grid():
179 return Grid(shape=(len(_EDGES) + 1, 5), features_domain=((0, len(_EDGES) + 1), (0, 5)),
180 fitness_domain=((.001, 1.),), fitness_weights=(1.,))
181
182
183def _network_oracle(grid):
184 labelled, canonical = {}, {}
185 representatives = set()
186 for genome in product((0, 1), repeat=len(_EDGES)):
187 representative = canonical_network(genome)
188 representatives.add(representative)
189 original, reduced = network_measure(genome), network_measure(representative)
190 assert original == reduced
191 for measurement, report in ((original, labelled), (reduced, canonical)):
192 (fitness,), features = measurement
193 if fitness > 0.:
194 cell = grid.index_grid(features)
195 report[cell] = max(fitness, report.get(cell, 0.))
196 assert labelled == canonical
197 return canonical, len(representatives)
198
199
200def compare_networks(budget, seed):
201 """Compare label-sensitive and canonical caching on the same network problem."""
202 exact, representatives = _network_oracle(_network_grid())
203 for method, canonicalize in (("symmetry-aware", canonical_network), ("labelled", tuple)):
204 archive = _network_grid()
205 search = SymmetryAwareMAPElites(archive, canonicalize=canonicalize,
206 propose=_binary_proposal(len(_EDGES)), mutate=_flip, seed=seed)
207 stats = search.run(network_measure, proposals=budget)
208 assert all(archive.index_grid(elite) in exact for elite in archive)
209 yield dict(task="networks", method=method, seed=seed, proposals=stats.proposals,
210 evaluations=stats.evaluations, duplicates=stats.duplicates,
211 labelled_space=2 ** len(_EDGES), canonical_space=representatives,
212 reachable_cells=len(exact), **_summary(archive))
213
214
215def control_rollout(genome):
216 """Roll out a bounded continuous feedback controller over a fixed horizon."""
217 weights = np.asarray(genome, dtype=float).reshape(2, _CONTROL_DIMENSION // 2)
218 position, velocity = np.zeros(2), np.zeros(2)
219 actions = []
220 for step in range(_CONTROL_STEPS):
221 phase = 2 * np.pi * step / _CONTROL_STEPS
222 features = (1., *position, *velocity, np.sin(phase), np.cos(phase), np.sin(2 * phase))
223 action = np.tanh(weights @ features)
224 velocity = .92 * velocity + .05 * action
225 position += velocity
226 actions.append(action)
227 effort = np.mean(np.square(actions))
228 change = np.mean(np.square(np.diff(actions, axis=0)))
229 quality = float(np.exp(-effort - .45 * change))
230 return (quality,), tuple(np.tanh(position / 1.5))
231
232
234 def reinit(self):
235 super().reinit()
236 self.model_fit_seconds = 0.
237 fit = self._model.fit
238
239 def timed_fit(*args, **kwargs):
240 start = perf_counter()
241 result = fit(*args, **kwargs)
242 self.model_fit_seconds += perf_counter() - start
243 return result
244
245 self._model.fit = timed_fit
246
247
248def compare_control(budget, seed):
249 """Compare native policy-vector optimisation at equal candidate rollout counts."""
250 import torch
251
252 torch.set_num_threads(1)
253 for method in ("poms", "dde-elites", "iso-line"):
254 archive = Grid(shape=(10, 10), features_domain=((-1., 1.),) * 2,
255 fitness_domain=((0., 1.),), fitness_weights=(1.,))
256 options = dict(container=archive, budget=budget, dimension=_CONTROL_DIMENSION,
257 batch_size=16, ind_domain=(-1., 1.), optimisation_task="max")
258 model = dict(min_elites=4, fit_interval=2, fit_epochs=8, fit_batch_size=32,
259 hidden_size=24, latent_size=4, seed=seed)
260 random.seed(seed)
261 np.random.seed(seed)
262 if method == "poms":
263 search = PolicyManifoldSearch(sigma=.05, **model, **options)
264 elif method == "dde-elites":
265 search = _TimedDDE(iso_sigma=.10, **model, **options)
266 else:
267 search = IsoLineMAPElites(iso_sigma=.10, **options)
268 start = perf_counter()
269 search.optimise(control_rollout, batch_mode=True)
270 yield dict(task="control", method=method, seed=seed, rollouts=search.nb_evaluations,
271 environment_steps=_CONTROL_STEPS * search.nb_evaluations,
272 model_fits=getattr(search, "model_fits", 0),
273 model_fit_seconds=getattr(search, "model_fit_seconds", 0.),
274 variation=getattr(search, "operator_counts", {}),
275 seconds=perf_counter() - start, **_summary(archive))
276
277
278def main():
279 """Run both base benchmarks by default, or include the optional control task."""
280 parser = argparse.ArgumentParser(description=__doc__)
281 parser.add_argument("--task", choices=("base", "scheduling", "networks", "control", "all"), default="base")
282 parser.add_argument("--seeds", type=int, default=3)
283 parser.add_argument("--budget", type=int, default=160)
284 parser.add_argument("--output", type=Path)
285 args = parser.parse_args()
286 if args.seeds < 1 or args.budget < 1:
287 parser.error("seeds and budget must be positive")
288 tasks = {"scheduling": compare_scheduling, "networks": compare_networks, "control": compare_control}
289 chosen = ("scheduling", "networks") if args.task == "base" else tuple(tasks) if args.task == "all" else (args.task,)
290 rows = [row for task in chosen for seed in range(args.seeds) for row in tasks[task](args.budget, seed)]
291 contents = "".join(json.dumps(row, sort_keys=True, allow_nan=False) + "\n" for row in rows)
292 if args.output is None:
293 print(contents, end="")
294 else:
295 args.output.write_text(contents, encoding="utf-8")
296
297
298if __name__ == "__main__":
299 main()
Use a sliding-window UCB1 bandit over learned and conventional mutations.
Definition dde.py:96
Fill a one-elite grid using Iso+LineDD variation.
Definition modern.py:56
Mutate well-reconstructed policies in a learned latent space.