QDpy
Loading...
Searching...
No Matches
cyclic_subset_planning.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run four reproducible CPU comparisons on small optimization problems."""
6
7import argparse
8from itertools import combinations
9import json
10from math import dist
11
12import numpy as np
13
14from qdpy.algorithms import (BooleanConjunction, ConjunctionMAPElites, CycleQD, DivTuRBO1,
15 primitive_mcts, qd_subgoal_mcts)
16
17
18def cycle_trial(seed, budget):
19 """Fit three linear specialists and audit the merged weights on fresh inputs."""
20 rng = np.random.default_rng([408, seed])
21 target = rng.normal(0., .65, size=(5, 3))
22 experts = []
23 for task in range(3):
24 training = rng.normal(size=(12, len(target)))
25 weights = np.zeros_like(target)
26 labels = training @ target[:, task] + rng.normal(0., .12, len(training))
27 weights[:, task] = np.linalg.solve(training.T @ training + .1 * np.eye(len(target)),
28 training.T @ labels)
29 experts.append((weights,))
30 base = (np.zeros_like(target),)
31 development = rng.normal(size=(32, len(target)))
32 audit = rng.normal(size=(256, len(target)))
33
34 def performance(checkpoint, panel):
35 errors = panel @ (checkpoint[0] - target)
36 return 1. / (1. + np.mean(errors**2, axis=0))
37
38 for method, order in (("CycleQD", None), ("Fixed task role", (0,))):
39 search = CycleQD(base, experts, ((0., 1.),) * 3, bins=8, task_order=order,
40 merge_std=.35, svd_max=2., seed=seed)
41 stats = search.run(lambda checkpoint: performance(checkpoint, development), budget)
42 elites = {elite[0]: elite for archive in search.archives for elite in archive}
43 balanced = max(elites.values(), key=lambda elite: min(elite.scores["cycle_scores"]))
44 held_out = performance(search.checkpoint(balanced), audit)
45 aggregate = performance(search.aggregate(), audit)
46 yield dict(task="cycle", method=method, seed=seed, evaluations=stats.evaluations,
47 task_evaluations=3 * stats.evaluations, audit_models=2,
48 filled_cells=[len(archive) for archive in search.archives],
49 best_balanced_audit=held_out.min(), aggregate_audit=aggregate.min())
50 average = performance((np.mean([expert[0] for expert in experts], axis=0),), audit)
51 yield dict(task="cycle", method="Weight averaging", seed=seed, evaluations=0, task_evaluations=0,
52 audit_models=1, best_balanced_audit=average.min(), aggregate_audit=average.min())
53
54
55def subset_trial(seed, budget):
56 """Use exhaustive coverage optima as reference for overlapping inclusion rules."""
57 rng = np.random.default_rng([112, seed])
58 dimension, cap = 14, 4
59 sets = [frozenset(rng.choice(26, 5, replace=False)) for _ in range(dimension)]
60 rules = {"unrestricted": BooleanConjunction(),
61 "first": BooleanConjunction({0}, {1}),
62 "second": BooleanConjunction({2}, {3}),
63 "paired": BooleanConjunction({0, 2}, {1, 3})}
64
65 def coverage(subset):
66 return len(frozenset().union(*(sets[i] for i in subset)))
67
68 reference = {}
69 for size in range(cap + 1):
70 for subset in combinations(range(dimension), size):
71 for name, rule in rules.items():
72 if rule.matches(subset):
73 key = name, size
74 reference[key] = max(reference.get(key, 0), coverage(subset))
75
76 for method, shared in (("Shared rules", True), ("Separate rules", False)):
77 groups = (rules,) if shared else tuple({name: rule} for name, rule in rules.items())
78 size, extra = divmod(budget, len(groups))
79 archives, evaluations = {}, 0
80 for i, group in enumerate(groups):
81 limit = size + (i < extra)
82 search = ConjunctionMAPElites(dimension, group, max_items=cap, crossover_probability=.3,
83 seed=np.random.SeedSequence([seed, i]))
84 stats = search.run(coverage, limit, proposal_limit=60 * limit)
85 archives.update(search.archives)
86 evaluations += stats.evaluations
87 found = {(name, elite.features.values[0]): int(elite.fitness.values[0])
88 for name, archive in archives.items() for elite in archive}
89 yield dict(task="subset", method=method, seed=seed, evaluations=evaluations, covered=len(found),
90 possible=len(reference),
91 exact_matches=sum(found.get(key) == value for key, value in reference.items()),
92 fitness_fraction=float(np.mean([found.get(key, 0) / max(value, 1)
93 for key, value in reference.items() if value > 0])))
94
95
96def trust_trial(seed, budget):
97 """Search three peaks with a common minimum portfolio separation."""
98 centers = np.array([[.12, .2, .48, .50, .55, .34],
99 [.44, .9, .45, .5, .5, .42],
100 [.92, .26, .56, .49, .5, .55]])
101 separation = .55
102
103 def quality(point):
104 penalty = ((centers - point)**2).sum(axis=1)
105 return float(np.max(np.array([1., .98, .96]) - penalty))
106
107 for method, phases in (("Sequential divTuRBO1", 1), ("Interleaved divTuRBO1", 3)):
108 search = DivTuRBO1(((0., 1.),) * 6, population_size=3, distance=separation, phases=phases,
109 fitness_weight=1., initial_samples=4, candidate_pool=36, seed=seed)
110 result = search.optimise(quality, budget)
111 yield dict(task="trust", method=method, seed=seed, evaluations=result.evaluations,
112 mean_fitness=float(np.mean([point.fitness for point in result.solutions])),
113 minimum_distance=result.minimum_distance, violations=result.violating_pairs,
114 restarts=sum(result.restarts_by_slot))
115 rng = np.random.default_rng(seed)
116 candidates = sorted(((quality(point), tuple(point)) for point in rng.random((budget, 6))), reverse=True)
117 representatives = []
118 for score, point in candidates:
119 if all(dist(point, elite) >= separation for _, elite in representatives):
120 representatives.append((score, point))
121 if len(representatives) == 3:
122 break
123 distances = [dist(a, b) for i, (_, a) in enumerate(representatives) for _, b in representatives[:i]]
124 yield dict(task="trust", method="Separated random search", seed=seed, evaluations=budget,
125 mean_fitness=float(np.mean([score for score, _ in representatives])),
126 minimum_distance=min(distances, default=None), violations=0, restarts=0,
127 portfolio_size=len(representatives))
128
129
130def maze_trial(seed, budget):
131 """Plan through a gate with a toll or a second route with lower cost."""
132 start, goal = (0, 3), (8, 3)
133 offsets = ((1, 0), (0, 1), (0, -1), (-1, 0))
134
135 def legal(state):
136 for dx, dy in offsets:
137 x, y = state[0] + dx, state[1] + dy
138 if 0 <= x <= 8 and 0 <= y <= 6 and (x != 4 or y in (1, 5)):
139 yield dx, dy
140
141 def simulate(state, action):
142 x, y = state[0] + action[0], state[1] + action[1]
143 reached = (x, y) == goal
144 reward = -.01 - .12 * (x == 4 and y == 1) + 1. * reached
145 return (x, y), reward, reached
146
147 for planner, method in ((qd_subgoal_mcts, "QD subgoals"), (primitive_mcts, "Primitive MCTS")):
148 settings = (dict(describe=lambda state: state, macro_steps=4, probes=6, subgoals=3)
149 if planner is qd_subgoal_mcts else {})
150 result = planner(start, actions=legal, simulate=simulate, budget=budget, horizon=18,
151 seed=seed, **settings)
152 state, gate = start, None
153 for action in result.plan.actions:
154 state = (state[0] + action[0], state[1] + action[1])
155 if state[0] == 4 and gate is None:
156 gate = state[1]
157 yield dict(task="maze", method=method, seed=seed, budget=budget, simulator_calls=result.simulator_calls,
158 discovery_calls=result.low_level_calls, goal=result.plan.terminated,
159 planned_steps=len(result.plan.actions), reward=result.plan.return_, first_gate=gate,
160 published_subgoals=result.published_subgoals)
161
162
163def main():
164 """Run one of the comparisons and print JSON records for each seed."""
165 trials = {"cycle": (cycle_trial, 72, 5), "subset": (subset_trial, 180, 4),
166 "trust": (trust_trial, 96, 9), "maze": (maze_trial, 800, 1)}
167 parser = argparse.ArgumentParser(description=__doc__)
168 parser.add_argument("task", choices=trials)
169 parser.add_argument("--budget", type=int)
170 parser.add_argument("--seeds", type=int, nargs="+", default=[11, 23, 47])
171 args = parser.parse_args()
172 trial, default, minimum = trials[args.task]
173 budget = default if args.budget is None else args.budget
174 if budget < minimum:
175 parser.error(f"--budget must be at least {minimum} for this task.")
176 for seed in args.seeds:
177 for row in trial(seed, budget):
178 print(json.dumps(row))
179
180
181if __name__ == "__main__":
182 main()