QDpy
Loading...
Searching...
No Matches
relevance_search.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run small paired CPU comparisons. Each JSON row contains one method and seed."""
6
7import argparse
8from dataclasses import asdict
9import json
10
11import numpy as np
12from scipy.spatial.distance import cdist, pdist
13from scipy.special import expit
14from threadpoolctl import threadpool_limits
15
16from qdpy.algorithms import (CycleQD, HebbianEvaluator, hebbian_map_elites, m2n2,
17 portfolio_map_elites, ruda_search)
18from qdpy.containers import Grid
19
20
21def relevance_trials(seed):
22 """Build equal-size motion repertoires and test them on new waypoints."""
23 rng = np.random.default_rng(177)
24 training = rng.uniform((.61, .63), (.87, .87), (18, 2))
25 audit = rng.uniform((.61, .63), (.87, .87), (48, 2))
26
27 def evaluate(genome):
28 x, y = genome
29 quality = 1. - .12 * ((x - .5)**2 + (y - .5)**2)
30 observations = (x, y, .22 * np.sin(6 * x), .15 * np.cos(7 * y))
31 return quality, observations
32
33 def solve(archive, rng):
34 endpoints = [row.observation[:2] for row in archive]
35 goals = training[rng.choice(len(training), size=6, replace=False)]
36 return tuple(cdist(goals, endpoints).argmin(axis=1))
37
38 for method, guided in (("RUDA", True), ("AURORA-style", False)):
39 outcome = ruda_search(evaluate, solve, dimension=2, budget=240, capacity=24, fit_period=24,
40 task_period=24, novelty_threshold=.08, distance_floor=.025,
41 training_capacity=160, initial_samples=40, guidance=guided, seed=seed)
42 endpoints = [entry.observation[:2] for entry in outcome.archive]
43 gap = cdist(audit, endpoints).min(axis=1)
44 yield dict(method=method, seed=seed, evaluations=outcome.evaluations, tasks=outcome.solver_calls,
45 members=len(endpoints), encoder_fits=outcome.encoder_fits,
46 waypoint_success=float(np.mean(gap <= .055)), mean_distance=float(gap.mean()),
47 audit_goals=len(audit))
48
49
50def fusion_trials(seed):
51 """Measure complementary aligned classifiers on a held-out input panel."""
52 rng = np.random.default_rng(617)
53 train = rng.uniform(-1., 1., (4, 24, 2))
54 audit = rng.uniform(-1., 1., (4, 80, 2))
55 experts = []
56 for group in range(4):
57 values = np.full((4, 2), (.1, .85))
58 values[group] = (2.4, -.25)
59 values[(group + 1) % 4] = (1.55, .25)
60 experts.append((values, np.zeros(4)))
61
62 def measure(model, inputs):
63 weights, bias = model
64 expected = np.where(inputs[:, :, 0] > .16 * inputs[:, :, 1], 1., -1.)
65 logits = np.einsum("gni,gi->gn", inputs, weights) + bias[:, None]
66 return expit(3 * expected * logits)
67
68 def evaluate(model):
69 return measure(model, train).ravel()
70
71 options = (("M2N2", "continuous", True), ("mean-sampling", "mean", False))
72 for label, competition, attraction in options:
73 outcome = m2n2(experts, evaluate, budget=72, population_size=10,
74 competition=competition, attraction=attraction, seed=seed)
75 score = measure(outcome.best.checkpoint, audit)
76 yield dict(method=label, seed=seed, evaluated=outcome.evaluations, audit_accuracy=float(np.mean(score > .5)),
77 audit_score=float(score.mean()), worst_group=float(score.mean(axis=1).min()))
78
79 cycle = CycleQD((np.zeros((4, 2)), np.zeros(4)), experts, ((0., 1.),) * 4,
80 bins=6, seed=seed)
81 best = None
82 quality = -np.inf
83
84 def task_evaluate(model):
85 nonlocal best, quality
86 scores = measure(model, train).mean(axis=1)
87 if scores.mean() > quality:
88 quality, best = scores.mean(), model
89 return scores
90
91 stats = cycle.run(task_evaluate, 72)
92 score = measure(best, audit)
93 yield dict(method="CycleQD", seed=seed, evaluated=stats.evaluations, audit_accuracy=float(np.mean(score > .5)),
94 audit_score=float(score.mean()), worst_group=float(score.mean(axis=1).min()))
95
96
97def planning_trials(seed):
98 """Illuminate resource-allocation strategies using identical scenario panels."""
99 horizon = 6
100 scenarios = tuple((0, 0, 0, mode) for mode in (0, 1, 2))
101
102 def simulate(state, action):
103 turn, materials, products, terrain = state
104 reward = .05
105 if action == "gather":
106 materials += 1 if terrain == 2 else 2
107 reward = .20
108 elif action == "craft" and materials >= 2:
109 materials -= 2
110 products += 1
111 reward = .98 if terrain == 0 else .74
112 elif action == "survey":
113 reward = .54 if terrain == 2 else .39
114 return (turn + 1, materials, products, terrain), reward, turn + 1 == horizon
115
116 def gathering(state):
117 _, materials, _, _ = state
118 return (("gather", 1. if materials < 2 else .45), ("rest", .25))
119
120 def crafting(state):
121 _, materials, _, _ = state
122 return (("craft", 1. if materials >= 2 else .1), ("gather", .48))
123
124 def surveying(state):
125 return (("survey", .95), ("rest", .40))
126
127 def summarize(plans):
128 quality = np.mean([row.return_ / horizon for row in plans])
129 fractions = tuple(np.mean([row.actions.count(action) / horizon for row in plans])
130 for action in ("gather", "survey"))
131 return (quality,), fractions
132
133 for label, fraction in (("progressive", .25), ("all-open", 1.)):
134 archive = Grid(shape=(7, 7), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),))
135 result = portfolio_map_elites(archive, scenarios, scripts=(gathering, crafting, surveying),
136 simulate=simulate, summarize=summarize, seed=seed, horizon=horizon,
137 budget=64, plan_budget=19, planner_options=dict(initial_fraction=fraction,
138 unprune_at=3))
139 yield dict(method=label, seed=seed, evaluations=result.evaluations, plans=result.plans,
140 simulator_calls=result.simulator_calls, filled=archive.filled_bins,
141 qd_score=archive.qd_score(), best=archive.best.fitness.values[0])
142
143
144def hebbian_trials(seed):
145 """Evolve local update rules and audit the same genome with plasticity frozen."""
146 def episode(policy, reset, switch, plastic):
147 controller = policy.start(seed=reset, plastic=plastic)
148 actions, returns = [], []
149 feedback = 0.
150 for tick in range(16):
151 gain = 1. if tick < switch else -1.
152 target = -.6 if tick < switch else .65
153 action = controller.act((1., feedback))[0]
154 feedback = (target - gain * action) / 2.
155 actions.append(float(action))
156 returns.append(1. - abs(feedback))
157 return np.asarray(actions), np.asarray(returns)
158
159 def evaluate(policy):
160 rows = [episode(policy, reset, 7, True) for reset in (3, 7)]
161 quality = np.mean([returns.mean() for _, returns in rows])
162 descriptor = np.mean([(actions[:7].mean(), actions[7:].mean()) for actions, _ in rows], axis=0)
163 return (quality,), descriptor
164
165 grid = Grid(shape=(7, 7), features_domain=((-1., 1.),) * 2, fitness_domain=((0., 1.),))
166 evaluator = HebbianEvaluator((2, 3, 1), evaluate, learning_scale=.35)
167 search = hebbian_map_elites(grid, evaluator, budget=132, batch_size=6, seed=seed)
168 policy = evaluator.policy(grid.best)
169 for label, plastic in (("plastic", True), ("frozen", False)):
170 rows = [episode(policy, reset, switch, plastic)
171 for reset in range(101, 107) for switch in (5, 9)]
172 switches = np.tile([5, 9], 6)
173 yield dict(method=label, seed=seed, evaluations=search.evaluations, filled=grid.filled_bins,
174 held_out_episodes=len(rows), quality=float(np.mean([row[1].mean() for row in rows])),
175 post_shift=float(np.mean([row[1][switch:].mean() for row, switch in zip(rows, switches)])))
176
177
178def skill_trials(seed):
179 """Train the same four discrete skills in one or two SAC species."""
180 import gymnasium as gym
181 import torch
182
183 from qdpy.rl import PolicyConfig, SACConfig, SSD, SSDConfig
184
185 torch.set_num_threads(1)
186
187 class Drift(gym.Env):
188 observation_space = gym.spaces.Box(-1., 1., (2,), dtype=np.float32)
189 action_space = gym.spaces.Box(-1., 1., (2,), dtype=np.float32)
190
191 def reset(self, *, seed=None, options=None):
192 super().reset(seed=seed)
193 self.state = self.np_random.uniform(-.08, .08, 2).astype(np.float32)
194 self.t = 0
195 return self.state.copy(), {}
196
197 def step(self, action):
198 self.state = np.clip(self.state + .23 * action, -1., 1.)
199 self.t += 1
200 return self.state.copy(), float(1. - self.state[0] ** 2), self.t == 6, False, {}
201
202 goals = np.asarray(((.7, 0.), (-.7, 0.), (0., .7), (0., -.7)))
203 grid = Grid(shape=(8, 8), features_domain=((-1., 1.),) * 2, fitness_domain=((0., 6.),))
204 for species in (1, 2):
205 policy = PolicyConfig((12,))
206 sac = SACConfig(batch_size=16, critic_hidden_sizes=(16,), learning_starts=18,
207 initial_temperature=.1, actor_learning_rate=.001)
208 config = SSDConfig(species=species, skills=4 // species, representation_layers=(12,),
209 embedding_size=6, representation_batch=12, update_period=4, contrastive_weight=2.)
210 search = SSD(Drift, config=config, sac=sac, policy=policy, max_episode_steps=6, seed=seed)
211 stats = search.train(480)
212 audit = search.evaluate(episodes=5, descriptor=lambda episode: episode.observations[-1], seed=821)
213 endpoints = [row.descriptor for result in audit for row in result.skills]
214 yield dict(method=f"{species}-species", seed=seed, env_steps=stats.env_steps,
215 audit_steps=sum(row.env_steps for row in audit), filled=len({grid.index_grid(row) for row in endpoints}),
216 mean_separation=float(pdist(endpoints).mean()), goal_gap=float(cdist(goals, endpoints).min(axis=1).mean()),
217 **asdict(stats))
218
219
220def main():
221 """Run one comparison on a reproducible list of seeds."""
222 choices = dict(relevance=relevance_trials, fusion=fusion_trials, planning=planning_trials,
223 hebbian=hebbian_trials, skills=skill_trials)
224 parser = argparse.ArgumentParser(description=__doc__)
225 parser.add_argument("task", choices=tuple(choices))
226 parser.add_argument("--seeds", type=int, nargs="+", default=(11, 22, 33, 44, 55))
227 args = parser.parse_args()
228 with threadpool_limits(limits=1):
229 for seed in args.seeds:
230 for row in choices[args.task](seed):
231 print(json.dumps(row, sort_keys=True), flush=True)
232
233
234if __name__ == "__main__":
235 main()