QDpy
Loading...
Searching...
No Matches
selection_and_skills.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run seeded pilots for NSS-ME, DSAGE, HTE, DOMiNO, and QDAIF."""
6
7import argparse
8from collections import deque
9from dataclasses import asdict
10import json
11from time import perf_counter
12
13import numpy as np
14
15from qdpy.algorithms import (DSAGE, DSAGEMeasurement, DSAGESurrogate, HierarchicalRepertoire,
16 HierarchicalTrialAndError, IsoLineMAPElites, MonteCarloElites,
17 NSSMAPElites, QDAIF, RTESkill, ResetFreeTrialAndError, SAIL)
18from qdpy.containers import Grid
19from qdpy.simple import run
20
21
22def _grid(shape=(8, 8)):
23 return Grid(shape=shape, features_domain=((0., 1.),) * len(shape), fitness_domain=((0., 1.),))
24
25
26def _summary(archive):
27 return dict(cells=len(archive), qd_score=sum(ind.fitness.values[0] for ind in archive),
28 best=archive.best.fitness.values[0] if len(archive) else None)
29
30
31
32def run_nss(method, seed, budget=360):
33 """Use fixed two-dimensional descriptors on a four-coordinate objective."""
34 archive = _grid()
35 settings = dict(dimension=4, budget=budget, batch_size=12, optimisation_task="max")
36 if method == "nss":
37 search = NSSMAPElites(archive, sigma=.12, seed=seed, **settings)
38 elif method == "monte-carlo":
39 search = MonteCarloElites(archive, sigma=.12, seed=seed, **settings)
40 else:
41 search = IsoLineMAPElites(archive, iso_sigma=.12, line_sigma=0, **settings)
42
43 def evaluate(genome):
44 x = np.asarray(genome)
45 peak = np.exp(-3 * np.square(x - [.22, .77, .55, .42]).sum())
46 ripple = .68 + .32 * np.cos(3 * np.pi * (x[0] - x[1])) ** 2
47 return (float(peak * ripple),), tuple(x[:2])
48
49 started = perf_counter()
50 run(search, evaluate, seed=seed)
51 return dict(suite="nss", method=method, seed=seed, evaluations=search.nb_evaluations,
52 seconds=perf_counter() - started, **_summary(archive))
53
54
55def maze(genome):
56 """Score a 5-by-5 layout using route-length and wall-count descriptors."""
57 walls = np.asarray(genome).reshape(5, 5) > .55
58 walls[0, 0] = walls[4, 4] = False
59 distance = {(0, 0): 0}
60 frontier = deque([(0, 0)])
61 while frontier:
62 i, j = frontier.popleft()
63 for neighbor in ((i-1, j), (i+1, j), (i, j-1), (i, j+1)):
64 a, b = neighbor
65 if 0 <= a < 5 and 0 <= b < 5 and not walls[a, b] and neighbor not in distance:
66 distance[neighbor] = distance[i, j] + 1
67 frontier.append(neighbor)
68 visited = np.zeros((5, 5))
69 for coordinate in distance:
70 visited[coordinate] = 1.
71 quality = 1. if (4, 4) in distance else .4 * visited.mean()
72 return DSAGEMeasurement(quality, (float(walls.mean()), distance.get((4, 4), 25) / 25), visited)
73
74
75
76def run_dsage(method, seed, budget=112):
77 """Record true simulator calls, surrogate predictions where exposed, and elapsed time."""
78 archive = _grid()
79 started = perf_counter()
80 if method.startswith("dsage"):
81 surrogate = DSAGESurrogate(width=32, epochs=30, seed=seed)
82 use_auxiliary = method == "dsage"
83
84 def evaluate(genome):
85 result = maze(genome)
86 return result if use_auxiliary else DSAGEMeasurement(result.fitness, result.features)
87
88 def layout(genome):
89 encoded = np.asarray(genome).reshape(5, 5) > .55
90 encoded[0, 0] = encoded[4, 4] = False
91 return encoded
92
93 search = DSAGE(archive, 25, initial_samples=min(20, budget), surrogate_evaluations=96,
94 prediction_batch_size=12, simulation_batch_size=7, encoder=layout,
95 surrogate=surrogate, seed=seed)
96 costs = asdict(search.run(evaluate, budget=budget))
97 else:
98 base = IsoLineMAPElites(archive, budget, 25, batch_size=7, iso_sigma=.1, optimisation_task="max")
99 if method == "sail":
100 acquisition = IsoLineMAPElites(_grid(), 96, 25, batch_size=12,
101 iso_sigma=.1, optimisation_task="max")
102 search = SAIL(illumination_algo=base, acquisition_algo=acquisition, ucb_stddev=.05)
103 else:
104 search = base
105
106 def evaluate(genome):
107 result = maze(genome)
108 return (result.fitness,), result.features
109
110 run(search, evaluate, seed=seed)
111 costs = dict(evaluations=search.nb_evaluations)
112 if method == "sail":
113 costs["surrogate_evaluations"] = acquisition.nb_evaluations
114 return dict(suite="dsage", method=method, seed=seed, seconds=perf_counter() - started,
115 **costs, **_summary(archive))
116
117
118
119def run_hte(method, seed, budget=160):
120 """Plan in an additive 2D task with one degraded actuator family."""
121 moves = ((1., 0.), (-1., 0.), (0., 1.), (0., -1.))
122 hierarchy = HierarchicalRepertoire([RTESkill((*move, family), move)
123 for family in (0., 1.) for move in moves])
124
125 def measure(primitives):
126 treatment = sum(key.genome[-1] for key in primitives) / len(primitives)
127 return 1. - .2 * treatment, tuple(np.sum([key.displacement for key in primitives], axis=0)), (treatment,)
128
129 layer = hierarchy.add_layer(measure, shape=(5, 5, 3), features_domain=((-2.5, 2.5),) * 2 + ((0., 1.),),
130 sequence_length=2, budget=budget, seed=seed)
131 steps = 0
132
133 def execute(state, primitive):
134 nonlocal steps
135 steps += 1
136 x, y, family = primitive
137 return tuple(np.asarray(state) + np.array([x, y]) * (1. if family else .25))
138
139 initial, goal = (0., 0.), (5., 1.)
140 settings = dict(horizon=3, simulations=42, goal_tolerance=.6, seed=seed)
141 started = perf_counter()
142 if method == "hte":
143 planner = HierarchicalTrialAndError(hierarchy, **settings)
144 path = planner.run(initial, goal, execute, max_trials=12)
145 else:
146 groups = {}
147 for index, row in enumerate(layer):
148 best = groups.get(row.primary_cell, index)
149 groups[row.primary_cell] = index if row.fitness > layer[best].fitness else best
150 flat = [RTESkill((index,), layer[index].displacement) for index in groups.values()]
151 planner = ResetFreeTrialAndError(flat, **settings)
152
153 def execute_macro(state, genome):
154 for primitive in layer[int(genome[0])].primitive_indices:
155 state = execute(state, hierarchy.primitives[primitive].genome)
156 return state
157
158 path = planner.run(initial, goal, execute_macro, max_trials=12)
159 return dict(suite="hte", method=method, seed=seed, layer_evaluations=hierarchy.evaluations,
160 compositions=len(layer), primary_cells=len({cell.primary_cell for cell in layer}),
161 macro_trials=len(path.skills), primitive_steps=steps, goal_reached=path.goal_reached,
162 distance=float(np.linalg.norm(np.subtract(path.states[-1], goal))),
163 planning_rollouts=planner.stats.planning_rollouts, seconds=perf_counter() - started)
164
165
166
167def run_domino(method, seed, budget=3840):
168 """Train three skills on a contextual bandit with two high-return choices."""
169 import gymnasium as gym
170 from gymnasium import spaces
171 from qdpy.rl import DOMiNO, PPOConfig, PolicyConfig
172
173 class Routes(gym.Env):
174 observation_space = spaces.Box(-1., 1., (1,), dtype=np.float32)
175 action_space = spaces.Discrete(3)
176
177 def reset(self, *, seed=None, options=None):
178 super().reset(seed=seed)
179 self.context = self.np_random.uniform(-1., 1.)
180 return np.array([self.context], dtype=np.float32), {}
181
182 def step(self, action):
183 reward = (.95 + .03 * self.context, .89 - .03 * self.context, .18)[action]
184 return np.array([self.context], dtype=np.float32), reward, True, False, {}
185
186 def occupancy(state, action, info):
187 return np.eye(3)[action]
188
189 search = DOMiNO(Routes, feature=occupancy, feature_dimension=3, num_skills=3,
190 reward_floor=.78, dual_rate=.7, mean_decay=.65,
191 diversity_weight=2. if method == "domino" else 0.,
192 max_episode_steps=1, policy=PolicyConfig(hidden_sizes=(16,)),
193 config=PPOConfig(rollout_steps=40, epochs=2, batch_size=20, learning_rate=.01),
194 seed=seed)
195 started = perf_counter()
196 stats = search.train(budget)
197 audit = search.evaluate(episodes_per_skill=24, seed=405)
198 distances = np.asarray(audit.distances)
199 return dict(suite="domino", method=method, seed=seed, training_steps=stats.training_steps,
200 optimizer_steps=stats.optimizer_steps, audit_steps=audit.steps, floor=audit.reward_floor,
201 satisfaction=audit.satisfaction, reward_rates=[row.reward_rate for row in audit.skills],
202 occupancy=[row.occupancy for row in audit.skills],
203 mean_distance=float(distances[np.triu_indices(3, 1)].mean()), seconds=perf_counter() - started)
204
205
206WORDS = (("amber", "quiet", "green", "distant", "small", "warm", "bright", "slow"),
207 ("rivers", "mountains", "willows", "clouds", "coves", "waves", "stones", "fields"),
208 ("bend", "rise", "sleep", "gather", "fall", "turn", "wait", "shine"),
209 ("at dawn", "at noon", "at dusk", "at night"))
210
211
212def _text_score(text):
213 words = text.split(" | ")
214 indices = [group.index(word) for group, word in zip(WORDS, words)]
215 a, n, v, time = indices
216 features = ((n // 2) / 3, time / 3)
217 score = .3 + .26 * (a % 4 == n % 4) + .24 * (v % 4 == n % 4) + .2 * ((a + v) % 4 == time)
218 return score, features
219
220
221
222def run_qdaif(method, seed, budget=60):
223 """Simulate text generation with a deterministic recorded lookup rubric."""
224 from itertools import product
225
226 scores = {" | ".join(words): _text_score(" | ".join(words)) for words in product(*WORDS)}
227 archive = _grid((4, 4))
228 search = QDAIF(archive, parent_count=int(method == "qdaif"), seed=seed)
229
230 def propose(parents, rng):
231 if parents:
232 words = parents[0].split(" | ")
233 locus = int(rng.integers(len(words)))
234 words[locus] = rng.choice(WORDS[locus])
235 else:
236 words = [rng.choice(group) for group in WORDS]
237 return " | ".join(words)
238
239 started = perf_counter()
240 stats = search.run(propose, scores.__getitem__, initial=("amber | rivers | bend | at dawn",),
241 proposal_budget=budget * 4, judgment_budget=budget)
242 return dict(suite="qdaif", method=method, seed=seed, **asdict(stats),
243 seconds=perf_counter() - started, **_summary(archive))
244
245
246def main():
247 parser = argparse.ArgumentParser(description=__doc__)
248 parser.add_argument("suite", choices=("nss", "dsage", "hte", "domino", "qdaif", "core", "all"))
249 parser.add_argument("--seeds", type=int, nargs="+", default=(11, 22, 33))
250 parser.add_argument("--quick", action="store_true")
251 args = parser.parse_args()
252 workloads = {
253 "nss": (run_nss, ("nss", "uniform", "monte-carlo"), 96, 360),
254 "dsage": (run_dsage, ("dsage", "dsage-direct", "sail", "map-elites"), 32, 112),
255 "hte": (run_hte, ("hte", "flat"), 80, 160),
256 "domino": (run_domino, ("domino", "reward-only"), 360, 3840),
257 "qdaif": (run_qdaif, ("qdaif", "independent"), 18, 60),
258 }
259 for suite, (runner, methods, quick, full) in workloads.items():
260 if args.suite in (suite, "all") or (args.suite == "core" and suite in ("nss", "hte", "qdaif")):
261 for seed in args.seeds:
262 for method in methods:
263 print(json.dumps(runner(method, seed, quick if args.quick else full),
264 sort_keys=True, allow_nan=False), flush=True)
265
266
267if __name__ == "__main__":
268 main()