QDpy
Loading...
Searching...
No Matches
structured_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run four seeded benchmarks using the base installation."""
6
7import argparse
8import itertools
9import json
10import random
11
12import numpy as np
13from scipy.optimize import Bounds, LinearConstraint
14
15from qdpy.algorithms import (CartesianGraphSpace, CuriosityMutPolyBounded, DecisionTreePolicy,
16 GraphMAPElites, MILPArchiveSearch, MatchResult, RandomSearchMutPolyBounded,
17 QDSelfPlay, YouthMAPElites, game_search)
18from qdpy.containers import Grid
19from qdpy.phenotype import Features, Fitness, Individual
20from qdpy.tools import mut_polynomial_bounded
21
22
23def assignment_trial(seed, budget):
24 """Match all niche optima against exhaustive enumeration of six two-machine assignments."""
25 rng = np.random.default_rng(seed)
26 cost = rng.integers(1, 20, size=12)
27 loads = np.asarray([1, 1, 2, 2, 3, 4])
28 descriptor = np.zeros((2, 12), dtype=int)
29 descriptor[0, ::2], descriptor[1, ::2] = 1, loads
30 rows = np.vstack((np.kron(np.eye(6), np.ones((1, 2))), descriptor[1]))
31 constraints = LinearConstraint(rows, [1] * 6 + [4], [1] * 6 + [10])
32 grid = Grid(shape=(7, 14), features_domain=((0, 6), (0, 13)), fitness_domain=((0, 120),),
33 fitness_weights=(-1.,))
34
35 def measure(first_machine):
36 bits = np.column_stack((first_machine, 1 - np.asarray(first_machine))).ravel()
37 features = tuple(descriptor @ bits)
38 if 4 <= features[1] <= 10:
39 return grid.index_grid(features), int(cost @ bits)
40 return None, None
41
42 oracle = {}
43 for assignment in itertools.product((0, 1), repeat=6):
44 cell, fitness = measure(assignment)
45 if cell is not None:
46 oracle[cell] = min(fitness, oracle.get(cell, np.inf))
47
48 search = MILPArchiveSearch(grid, cost, Bounds(0, 1), descriptor, constraints=constraints)
49 results = search.run()
50 solved = {row.cell: row.fitness for row in results if row.status == "optimal"}
51 assert solved == oracle and all(row.status != "unresolved" for row in results)
52 yield dict(method="MILP", seed=seed, cells=len(solved), solver_calls=sum(row.solver_status is not None for row in results),
53 infeasible_cells=len(results) - len(solved), exhaustive_assignments=2**6,
54 best_cost=min(solved.values()), mean_cell_gap=0.)
55
56 # Preserve assignment equalities by flipping one job's machine.
57 elites = {}
58 for _ in range(budget):
59 if elites and rng.random() < .9:
60 parent = tuple(elites.values())[rng.integers(len(elites))][1]
61 assignment = list(parent)
62 assignment[rng.integers(6)] ^= 1
63 else:
64 assignment = rng.integers(2, size=6).tolist()
65 cell, fitness = measure(assignment)
66 if cell is not None and (cell not in elites or fitness < elites[cell][0]):
67 elites[cell] = fitness, tuple(assignment)
68 yield dict(method="assignment MAP-Elites", seed=seed, cells=len(elites), candidate_calls=budget,
69 best_cost=min((value for value, _ in elites.values()), default=None),
70 mean_cell_gap=float(np.mean([value - oracle[cell] for cell, (value, _) in elites.items()]))
71 if elites else None)
72
73
74STEPS = ((1, 0), (-1, 0), (0, 1), (0, -1))
75START, GOAL = (1, 3), (5, 3)
76
77
78def _advance(position, action):
79 if action is None:
80 return position
81 dx, dy = STEPS[action]
82 x, y = position[0] + dx, position[1] + dy
83 if 0 <= x < 7 and 0 <= y < 7 and (x != 3 or y in (0, 6)):
84 return x, y
85 return position
86
87
88def navigate(choose, *, mask_direction=False, horizon=22):
89 """Reach a goal across a wall with two possible detours using a reactive policy."""
90 position = START
91 for step in range(horizon):
92 x, y = position
93 observation = (x / 3. - 1., y / 3. - 1.,
94 0. if mask_direction else (GOAL[0] - x) / 6., (GOAL[1] - y) / 6.,
95 *[float(_advance(position, action) == position) for action in range(4)])
96 position = _advance(position, choose(observation))
97 if position == GOAL:
98 return 1. + (horizon - step) / (horizon + 1), position
99 return 1. / (1 + sum(abs(a - b) for a, b in zip(position, GOAL))), position
100
101
102def _graph_action(graph, observation):
103 dx, dy = graph.act(observation)
104 if dx == dy == 0.:
105 return None
106 if abs(dx) > abs(dy):
107 return 0 if dx > 0. else 1
108 return 2 if dy > 0. else 3
109
110
111def _tree_policy(genome):
112 thresholds = (-.5, 0., .5)
113 first, left, right = (tuple(genome[i:i + 2]) for i in (0, 2, 4))
114 leaves = genome[6:]
115 return DecisionTreePolicy(
116 (first[0], thresholds[first[1]], (left[0], thresholds[left[1]], *leaves[:2]),
117 (right[0], thresholds[right[1]], *leaves[2:])), (8,), 4,
118 )
119
120
121def graph_trial(seed, budget):
122 """Compare structural and endpoint archives with fitness-only CGP and shallow decision trees."""
123 space = CartesianGraphSpace(8, 2, 12, operation_rate=.09, connection_rate=.12)
124 for mode in ("graph fitness only", "graph behavior", "graph joint", "decision trees"):
125 if mode == "graph fitness only":
126 shape, domains = (1,), ((0., 1.),)
127 else:
128 shape, domains = (7, 7), ((0., 6.),) * 2
129 if mode == "graph joint":
130 shape, domains = (*shape, 4, 4), (*domains, (0., 1.), (0., 1.))
131 archive = Grid(shape=shape, features_domain=domains, fitness_domain=((0., 2.),), fitness_weights=(1.,))
132 endpoints = set()
133
134 def decode(genome):
135 if mode == "decision trees":
136 return _tree_policy(genome).act, ()
137 graph = space.decode(genome)
138 return lambda observation: _graph_action(graph, observation), graph.structure_descriptors
139
140 def evaluate(genome):
141 policy, structure = decode(genome)
142 score, endpoint = navigate(policy)
143 endpoints.add(endpoint)
144 if mode == "graph fitness only":
145 descriptor = (0.,)
146 elif mode == "graph joint":
147 descriptor = (*endpoint, *structure)
148 else:
149 descriptor = endpoint
150 return (score,), descriptor
151
152 if mode == "decision trees":
153 rng = np.random.default_rng(seed)
154 limits = np.array([8, 3] * 3 + [4] * 4)
155 for _ in range(budget):
156 if archive:
157 candidate = list(archive[rng.integers(len(archive))])
158 gene = rng.integers(len(limits))
159 flip = rng.integers(limits[gene] - 1)
160 candidate[gene] = int(flip + (flip >= candidate[gene]))
161 else:
162 candidate = list(map(int, rng.integers(limits)))
163 fitness, descriptor = evaluate(candidate)
164 archive.add(Individual(candidate, fitness=Fitness(fitness, weights=(1.,)), features=Features(descriptor)))
165 else:
166 GraphMAPElites(archive, budget, space, seed=seed, batch_size=1).optimise(evaluate)
167
168 audited = [navigate(decode(item)[0], mask_direction=True)[0] for item in archive]
169 structures = {decode(item)[1] for item in archive}
170 yield dict(method=mode, seed=seed, evaluations=budget, explored_endpoints=len(endpoints),
171 cells=archive.filled_bins, distinct_graph_structures=len(structures) if mode != "decision trees" else None,
172 best_fitness=archive.best.fitness.values[0], held_out_evaluations=len(audited),
173 best_masked_fitness=max(audited))
174
175
176def cyclic_action(strategy):
177 """Decode the cycle action from a bounded scalar strategy."""
178 return min(2, int(3 * strategy[0]))
179
180
181def cyclic_match(red, blue):
182 """Score rock-paper-scissors with a small penalty away from each action center."""
183 red_action, blue_action = cyclic_action(red), cyclic_action(blue)
184 red_penalty = abs(red[0] - (red_action + .5) / 3.)
185 blue_penalty = abs(blue[0] - (blue_action + .5) / 3.)
186 reward = (0., 1., -1.)[(red_action - blue_action) % 3] + .2 * (blue_penalty - red_penalty)
187 return reward, -reward
188
189
190def propose_cyclic(context, rng):
191 """Perturb an archived strategy, with larger moves after a loss."""
192 size = .19 if context.payoffs[context.role] < 0. else .12
193 value = context.parents[context.role][0]
194 return (float(np.clip(value + rng.normal(0., size), 0., 1.)),)
195
196
197def self_play_trial(seed, budget):
198 """Compare grid-free competition and GAME using the same maximum match budget."""
199 search = QDSelfPlay(((.17,), (.17,)), play=cyclic_match, propose=propose_cyclic,
200 embed=lambda role, policy: policy, novelty_radius=.16, opponents=3, seed=seed)
201 stats = search.run(budget)
202
203 def play(red, blue):
204 return MatchResult(cyclic_match(red, blue), (red, blue))
205
206 result = game_search(play, dimensions=(1, 1), rounds=8, matches_per_round=budget // 8,
207 task_count=3, cells_per_task=5, seed=seed, match_budget=budget)
208 game = []
209 for side in ("red", "blue"):
210 latest = next((row.representatives for row in reversed(result.rounds) if row.side == side), ())
211 game.append(tuple(item.genome for item in latest))
212 panel = tuple(((action + .5) / 3.,) for action in range(3))
213 for label, archives, calls in (("QD Self-Play", search.archives, stats.matches),
214 ("GAME", tuple(game), result.total_attempts)):
215 coverage = [len({cyclic_action(policy) for policy in archive}) for archive in archives]
216 values = []
217 for side, archive in enumerate(archives):
218 for opponent in panel:
219 payoffs = [(cyclic_match(policy, opponent) if side == 0 else cyclic_match(opponent, policy))[side]
220 for policy in archive]
221 if payoffs:
222 values.append(max(payoffs))
223 yield dict(method=label, seed=seed, matches=calls, role_action_coverage=coverage,
224 mean_best_panel_payoff=float(np.mean(values)) if values else None,
225 audit_matches=sum(map(len, archives)) * len(panel))
226
227
228def youth_trial(seed, budget):
229 """Compare recent, uniform, and curiosity parent selection under the same maze and mutation."""
230 length = 16
231
232 def evaluate(genome):
233 actions = iter(min(3, int(value * 4)) for value in genome)
234 quality, endpoint = navigate(lambda observation: next(actions), horizon=length)
235 return (quality,), endpoint
236
237 def mutate(parent, rng):
238 return mut_polynomial_bounded(list(parent), eta=5., low=0., up=1., mut_pb=2 / length)
239
240 for kind in ("youth", "uniform", "curiosity"):
241 archive = Grid(shape=(7, 7), features_domain=((0, 6),) * 2,
242 fitness_domain=((0., 2.),), fitness_weights=(1.,))
243 start = [float(value) for value in np.random.default_rng(seed).random(length)]
244 fitness, endpoint = evaluate(start)
245 archive.add(Individual(start, fitness=Fitness(fitness, weights=(1.,)), features=Features(endpoint)))
246 random.seed(seed)
247 if kind == "youth":
248 search = YouthMAPElites(archive, budget, length, parent_window=4, mutate=mutate, seed=seed, batch_size=1)
249 else:
250 settings = dict(init_pb=0., eta=5., mut_pb=2 / length, optimisation_task="maximisation", batch_size=1)
251 search = (RandomSearchMutPolyBounded(archive, budget, length, sel_pb=1., **settings)
252 if kind == "uniform" else CuriosityMutPolyBounded(archive, budget, length, **settings))
253 search.optimise(evaluate)
254 yield dict(method=kind, seed=seed, evaluations=search.nb_evaluations + 1, cells=archive.filled_bins,
255 best_fitness=archive.best.fitness.values[0], reached_goal=bool(archive.solutions[GOAL]))
256
257
258if __name__ == "__main__":
259 trials = {"assignment": (assignment_trial, 64), "graphs": (graph_trial, 768),
260 "self-play": (self_play_trial, 144), "youth": (youth_trial, 256)}
261 parser = argparse.ArgumentParser(description=__doc__)
262 parser.add_argument("task", choices=trials)
263 parser.add_argument("--budget", type=int)
264 parser.add_argument("--seeds", type=int, nargs="+", default=[11, 22, 33])
265 args = parser.parse_args()
266 trial, default_budget = trials[args.task]
267 budget = default_budget if args.budget is None else args.budget
268 if budget < (16 if args.task == "self-play" else 1):
269 parser.error("Use a positive budget, or at least 16 matches for self-play.")
270 for seed in args.seeds:
271 for row in trial(seed, budget):
272 print(json.dumps(row, sort_keys=True))