QDpy
Loading...
Searching...
No Matches
sequence_distribution_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run deterministic CPU pilots for structured sequences, noisy outcomes, and continuing control."""
6
7import argparse
8import json
9from itertools import product
10from pathlib import Path
11
12import numpy as np
13
14from qdpy.algorithms import (
15 DistributionMAPElites,
16 EmpiricalDistribution,
17 GramElites,
18 MedoidArchive,
19 MedoidMAPElites,
20 NGramSequenceSpace,
21 QDAlgorithm,
22 wasserstein_descriptor_distance,
23)
24from qdpy.containers import Grid
25from qdpy.phenotype import Features, Fitness, Individual
26
27
28_TILE_STEPS = {"a": 0, "b": 1, "c": 2, "k": 1, "d": 1}
29_CORPUS = ("ababkbbcdbab", "bababccbkddb", "abbabkbcbbda", "bccbkdbababa",
30 "abbdbbabkcbb", "bbkbcbbdbcba", "babcbabkabdb", "babccbbkadba")
31_LEVEL_LENGTH = 20
32_ROLLOUTS = 24
33_AUDIT = 96
34_CENTERS = (-1., 0., 1.)
35_WIDTHS = (.05, .45, .95)
36_HORIZON = 4
37
38
39def play_level(level):
40 """Check climb height and access to locked doors, then score tile variety."""
41 keys, previous, doors = 0, 0, 0
42 for tile in level:
43 elevation = _TILE_STEPS[tile]
44 if abs(elevation - previous) > 1 or (tile == "d" and keys == 0):
45 return None
46 if tile == "k":
47 keys += 1
48 if tile == "d":
49 keys -= 1
50 doors += 1
51 previous = elevation
52 quality = len(set(zip(level, level[1:]))) / (len(level) - 1)
53 return quality, (min(3, doors), min(4, level.count("c")))
54
55
57 def __init__(self, archive, space, budget, seed, *, sampling):
58 self.space, self.sampling = space, sampling
59 self.rng = np.random.default_rng(seed)
60 super().__init__(archive, budget, dimension=space.length, batch_size=1,
61 optimisation_task="maximisation")
62
63 def _internal_ask(self, individual):
64 if self.sampling or not self.container or self.nb_suggestions < 8:
65 individual[:] = self.space.sample(self.rng)
66 else:
67 first, second = self.rng.integers(len(self.container), size=2)
68 cut = self.rng.integers(1, self.space.length)
69 individual[:] = self.container[first][:cut] + self.container[second][cut:]
70 if self.rng.random() < .2:
71 individual[self.rng.integers(self.space.length)] = tuple(_TILE_STEPS)[self.rng.integers(len(_TILE_STEPS))]
72 return individual
73
74
75def compare_levels(budget, seed):
76 """Compare valid levels and niche quality at equal proposal cost."""
77 space = NGramSequenceSpace(_CORPUS, n=3, length=_LEVEL_LENGTH)
78 for method in ("gram-elites", "standard-map-elites", "ngram-sampling"):
79 grid = Grid(shape=(4, 5), features_domain=((0, 4), (0, 5)), fitness_domain=((0., 1.),))
80 if method == "gram-elites":
81 search = GramElites(grid, budget, space, mutation_probability=.2, seed=seed)
82 else:
83 search = _TileBaseline(grid, space, budget, seed, sampling=method == "ngram-sampling")
84 supported, playable = 0, 0
85 for _ in range(budget):
86 individual = search.ask()
87 supported += space.supports(individual)
88 result = play_level(individual)
89 playable += result is not None
90 quality, descriptors = result or (0., (0, 0))
91 search.tell(individual, (quality,), descriptors, tell_container=result is not None)
92 yield dict(task="levels", method=method, seed=seed, proposals=search.nb_evaluations,
93 supported=supported, playable=playable, cells=len(grid),
94 qd_score=sum(elite.fitness.values[0] for elite in grid))
95
96
97def _propose(rng):
98 return (int(rng.integers(3)), int(rng.integers(3)), int(rng.integers(9)))
99
100
101def _mutate(genome, rng):
102 child = list(genome)
103 index = rng.integers(len(child))
104 child[index] = (child[index] + int(rng.choice([-1, 1]))) % (3, 3, 9)[index]
105 return tuple(child)
106
107
108def stochastic_outcome(genome, seed):
109 """Generate an outcome whose expectation and spread vary independently."""
110 mean, spread, quality = genome
111 rng = np.random.default_rng(seed)
112 outcome = _CENTERS[mean] + _WIDTHS[spread] * rng.choice((-1., 1.)) + rng.normal(0., .025)
113 return quality / 8., float(outcome)
114
115
116def _distribution_grid():
117 anchors = tuple(EmpiricalDistribution((mean - spread, mean + spread))
118 for mean, spread in product(_CENTERS, _WIDTHS))
119 return MedoidArchive(anchors, wasserstein_descriptor_distance)
120
121
122def compare_outcomes(budget, seed):
123 """Reassign both methods to the same distribution niches on held-out seeds."""
124 distribution = _distribution_grid()
125 search = DistributionMAPElites(distribution, propose=_propose, mutate=_mutate,
126 rollouts=_ROLLOUTS, seed=seed)
127 search.optimise(stochastic_outcome, budget=budget)
128 audit = search.audit(stochastic_outcome, rollouts=_AUDIT)
129 yield dict(task="outcomes", method="distribution", seed=seed, proposals=search.nb_evaluations,
130 rollouts=search.nb_rollouts, audit_rollouts=search.nb_audit_rollouts,
131 search_cells=len(distribution), stable=sum(row.stable for row in audit),
132 **_audit_summary((row.audit_niche, row.fitness) for row in audit))
133
134 # Both methods have nine slots, identical variation, and the same seed stream.
135 mean_grid = MedoidArchive(np.linspace(-1., 1., 9), lambda a, b: abs(a - b))
136 variation, training, holdout = np.random.SeedSequence(seed).spawn(3)
137 rng = np.random.default_rng(training)
138 called = 0
139
140 def evaluate(genome):
141 nonlocal called
142 results = [stochastic_outcome(genome, rng.bit_generator.random_raw()) for _ in range(_ROLLOUTS)]
143 called += len(results)
144 return tuple(np.mean(results, axis=0))
145
146 baseline = MedoidMAPElites(mean_grid, propose=_propose, mutate=_mutate, seed=variation)
147 baseline.optimise(evaluate, budget=budget)
148 audit_panel = holdout.generate_state(_AUDIT, dtype=np.uint64)
149 rows, stable = [], 0
150 for cell, elite in mean_grid.cells.items():
151 scores, outcomes = zip(*(stochastic_outcome(elite.genome, int(s)) for s in audit_panel))
152 stable += mean_grid.index(float(np.mean(outcomes))) == cell
153 index = distribution.index(EmpiricalDistribution(outcomes))
154 rows.append((index, float(np.mean(scores))))
155 yield dict(task="outcomes", method="mean", seed=seed, proposals=baseline.nb_evaluations,
156 rollouts=called, audit_rollouts=len(rows) * _AUDIT,
157 search_cells=len(mean_grid), stable=stable, **_audit_summary(rows))
158
159
160def _audit_summary(rows):
161 best = {}
162 for niche, score in rows:
163 best[niche] = max(score, best.get(niche, -np.inf))
164 return dict(audit_cells=len(best), audit_qd_score=sum(best.values()))
165
166
167def safety_margin(observation):
168 """Return positive margin inside the circular navigation region."""
169 return .77 - float(np.linalg.norm(observation))
170
171
172def fallback_action(observation):
173 """Steer toward the center of the training region."""
174 return np.clip(-3. * observation, -1., 1.).astype(np.float32)
175
176
177def navigation_reward(observation, action, successor):
178 """Reward progress while charging for control effort."""
179 return .5 + float(np.linalg.norm(successor - observation)) - .12 * float(action @ action)
180
181
182def displacement(episode):
183 """Describe a skill by the measured displacement of its complete trajectory."""
184 return episode.observations[-1] - episode.observations[0]
185
186
187def _nav_grid():
188 return Grid(shape=(7, 7), features_domain=((-1., 1.),) * 2, fitness_domain=((0., 4.),))
189
190
191def _navigation_factory(trace):
192 import gymnasium as gym
193
194 class Navigation(gym.Env):
195 def __init__(self):
196 self.observation_space = gym.spaces.Box(-1.5, 1.5, (2,), dtype=np.float32)
197 self.action_space = gym.spaces.Box(-1., 1., (2,), dtype=np.float32)
198
199 def reset(self, *, seed=None, options=None):
200 super().reset(seed=seed)
201 trace["resets"] += 1
202 self.state = self.np_random.uniform(-.035, .035, 2).astype(np.float32)
203 return self.state.copy(), {}
204
205 def step(self, action):
206 assert self.action_space.contains(action)
207 x, y = self.state
208 drift = np.array((.055 + .06 * y, -.035 - .04 * x), dtype=np.float32)
209 successor = np.clip(self.state + .16 * action + drift, -1.5, 1.5)
210 reward = navigation_reward(self.state, action, successor)
211 trace["steps"] += 1
212 trace["unsafe_steps"] += safety_margin(successor) < 0.
213 self.state = successor
214 return successor.copy(), reward, False, False, {}
215
216 return Navigation
217
218
219def _fixed_navigation(factory, archive, budget, seed):
220 """Select from nine hand-written actions with nominal safety and novelty scores."""
221 library = [np.asarray(move, dtype=np.float32) for move in product((-.8, 0., .8), repeat=2)]
222 env = factory()
223 recovery = 0
224 try:
225 observation, _ = env.reset(seed=seed)
226 for _ in range(budget // _HORIZON):
227 start = observation.copy()
228 priority = []
229 for action in library:
230 path = [start + .16 * i * action for i in range(1, _HORIZON + 1)]
231 margin = min(map(safety_margin, path))
232 if margin >= .10:
233 features = tuple(path[-1] - start)
234 priority.append((not archive.solutions[archive.index_grid(features)], margin, action))
235 candidate = (max(priority, key=lambda row: row[:2])[-1]
236 if priority and safety_margin(start) >= 0. else None)
237 score = 0.
238 valid = candidate is not None
239 for _ in range(_HORIZON):
240 if valid:
241 action = candidate
242 else:
243 action = fallback_action(observation)
244 recovery += 1
245 observation, reward, *_ = env.step(action)
246 valid &= safety_margin(observation) >= 0.
247 score += reward
248 if valid:
249 elite = Individual(candidate, fitness=Fitness((score,), weights=(1.,)),
250 features=Features(observation - start))
251 archive.add(elite)
252 finally:
253 env.close()
254 return recovery
255
256
257def compare_navigation(budget, seed):
258 """Measure real and model steps, cumulative archive score, and safety outcomes."""
259 import torch
260
261 from qdpy.rl import DynamicsAwareQD, PolicyConfig, ResetFreeQD
262
263 if budget <= 32 or budget % _HORIZON:
264 raise ValueError("Navigation uses more than 32 steps and a multiple of four.")
265 torch.set_num_threads(1)
266 for method in ("reset-free", "fixed-repertoire", "episodic-da-qd"):
267 trace = dict(resets=0, steps=0, unsafe_steps=0)
268 factory, archive = _navigation_factory(trace), _nav_grid()
269 kwargs = dict(descriptor=displacement, model_reward=navigation_reward, initial_policies=4,
270 policy=PolicyConfig(()), model_policy=PolicyConfig((16,)), min_model_steps=32,
271 model_updates=6, model_learning_rate=.01, ensemble_size=2, model_batch_size=24,
272 imagined_candidates=16, iso_sigma=.30, seed=seed)
273 model_steps, recovery_steps = 0, 0
274 if method == "reset-free":
275 rng = np.random.default_rng(seed)
276
277 def warmup(observation):
278 if safety_margin(observation) < .31:
279 return fallback_action(observation)
280 return rng.uniform(-1., 1., 2).astype(np.float32)
281
282 with ResetFreeQD(factory, archive, safety_margin=safety_margin, fallback_action=fallback_action,
283 safety_buffer=.10, warmup_action=warmup, skill_steps=_HORIZON, **kwargs) as search:
284 stats = search.train(budget)
285 model_steps, recovery_steps = stats.imagined_steps, stats.recovery_steps
286 elif method == "fixed-repertoire":
287 recovery_steps = _fixed_navigation(factory, archive, budget, seed)
288 else:
289 search = DynamicsAwareQD(factory, archive, max_episode_steps=_HORIZON, max_transfers=1, **kwargs)
290 stats = search.train(budget)
291 model_steps = stats.imagined_steps
292 yield dict(task="navigation", method=method, seed=seed, step_budget=budget, **trace,
293 external_resets=trace["resets"] - 1, model_steps=model_steps, recovery_steps=recovery_steps,
294 cells=len(archive), qd_score=sum(elite.fitness.values[0] for elite in archive))
295
296
297def main():
298 """Run base pilots by default, or select the optional RL pilot."""
299 parser = argparse.ArgumentParser(description=__doc__)
300 parser.add_argument("--task", choices=("base", "levels", "outcomes", "navigation", "all"), default="base")
301 parser.add_argument("--seeds", type=int, default=3)
302 parser.add_argument("--budget", type=int, default=160)
303 parser.add_argument("--output", type=Path)
304 args = parser.parse_args()
305 if args.seeds < 1 or args.budget < 1:
306 parser.error("seeds and budget must be positive")
307 tasks = {"levels": compare_levels, "outcomes": compare_outcomes, "navigation": compare_navigation}
308 chosen = ("levels", "outcomes") if args.task == "base" else tuple(tasks) if args.task == "all" else (args.task,)
309 rows = [row for task in chosen for seed in range(args.seeds) for row in tasks[task](args.budget, seed)]
310 contents = "".join(json.dumps(row, sort_keys=True, allow_nan=False) + "\n" for row in rows)
311 if args.output is None:
312 print(contents, end="")
313 else:
314 args.output.write_text(contents, encoding="utf-8")
315
316
317if __name__ == "__main__":
318 main()
Measure stochastic outcomes repeatedly and illuminate fixed distributional niches.
Represent an empirical probability measure with equal mass per observation.
Illuminate supported token sequences in a native Grid or CVTGrid.
Learn allowed token transitions and keep variation within their support.
Assign descriptors to the nearest fixed medoid and keep the best candidate there.
Draw parents from occupied medoid niches and mutate with caller-defined operators.
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405