QDpy
Loading...
Searching...
No Matches
learned_exploration.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Print seeded JSON records for the dynamic mutation and learned-exploration tutorial."""
6
7import argparse
8from itertools import combinations
9import json
10from math import pi
11
12import numpy as np
13from scipy.spatial.distance import jensenshannon
14
15from qdpy.algorithms import BRNS, SERENE, STAX, TAXONS, DynamicMutationMAPElites
16from qdpy.benchmarks import ackley, rastrigin
17from qdpy.containers import Grid
18
19
20def _grid(shape):
21 return Grid(shape=shape, fitness_domain=((0., 1.),), features_domain=((0., 1.),) * len(shape),
22 fitness_weights=(1.,))
23
24
25def _mutation_landscape(name):
26 functions = {
27 "rastrigin": lambda z: rastrigin(8. * z)[0],
28 "ackley": lambda z: ackley(8. * z)[0],
29 "rosenbrock": lambda z: np.sum(100. * (z[1:] - z[:-1] ** 2) ** 2 + (1. - z[:-1]) ** 2),
30 }
31
32 def evaluate(point):
33 loss = functions[name](np.asarray(point) - .5)
34 return (1. / (1. + max(0., loss)),), tuple(point[:2])
35
36 return evaluate
37
38
39def _mutation_trial(name, mode, sigma, seed, budget):
40 archive = _grid((10, 10))
41 search = DynamicMutationMAPElites(archive, budget, 7, mode=mode, sigma_start=sigma,
42 sigma_stop=.02, seed=seed, optimisation_task="maximisation")
43 search.optimise(_mutation_landscape(name))
44 return dict(seed=seed, case="mutation", landscape=name, method=mode, sigma=sigma,
45 evaluations=search.nb_evaluations, cells=archive.filled_bins,
46 qd_score=float(archive.qd_score()), best=float(archive.best.fitness.values[0]))
47
48
49
50def mutation(seeds, budget):
51 """Compare coverage, time, and inheritance schedules against a tuned fixed strength."""
52 for name in ("rastrigin", "ackley", "rosenbrock"):
53 fixed = max((.06, .12, .24, .48), key=lambda sigma: np.mean(
54 [_mutation_trial(name, "fixed", sigma, seed, budget)["qd_score"] for seed in (173, 231, 317)]))
55 for seed in seeds:
56 yield _mutation_trial(name, "fixed", fixed, seed, budget)
57 for mode in ("coverage", "anneal", "self_adaptive"):
58 yield _mutation_trial(name, mode, .24, seed, budget)
59
60
61def _sparse_task(genome, seed):
62 """Map four real parameters to a path, with reward only inside three small disks."""
63 x, y, phase, swing = genome
64 t = np.linspace(0., 1., 8)
65 angle = 2 * pi * phase
66 dx = swing * .18 * np.sin(2 * pi * t) * np.cos(angle)
67 dy = swing * .18 * np.sin(2 * pi * t) * np.sin(angle)
68 end = np.clip([x, y], 0., 1.)
69 path = t[:, None] * end + np.column_stack((dx, dy))
70 centers = np.array([[.2, .78], [.74, .22], [.81, .83]])
71 distance = np.linalg.norm(end - centers, axis=1).min()
72 reward = max(0., 1. - distance / .095)
73 # A fixed nonlinear observation map with one seeded nuisance channel.
74 observation = np.stack((np.sin(2 * pi * path[:, 0]), np.cos(2 * pi * path[:, 0]),
75 np.sin(2 * pi * path[:, 1]), np.cos(2 * pi * path[:, 1]),
76 np.sin(pi * (path[:, 0] + path[:, 1])), np.cos(pi * (2. * path[:, 0] - path[:, 1])),
77 np.random.default_rng(seed).uniform(-.15, .15, len(t))), axis=1)
78 return reward, end, observation
79
80
81def _learned_trial(name, seed, budget):
82 audit, successful = _grid((12, 12)), _grid((12, 12))
83 from qdpy.phenotype import Features, Fitness, Individual
84
85 def observe(genome, rollout_seed):
86 reward, end, observation = _sparse_task(genome, rollout_seed)
87 record = Individual(genome, fitness=Fitness((reward,), weights=(1.,)), features=Features(tuple(end)))
88 audit.add(record)
89 if reward > 0.:
90 successful.add(record)
91 return (reward, end) if name == "serene" else (reward, observation)
92
93 settings = dict(population_size=16, seed=seed)
94 if name == "serene":
95 search = SERENE(_grid((12, 12)), 4, chunk_size=16, **settings)
96 else:
97 cls = {"taxons": TAXONS, "stax": STAX, "brns": BRNS}[name]
98 settings.update(offspring=16, batch_size=32, epochs=2)
99 if name == "stax":
100 settings.update(emitter_budget=16, bootstrap_calls=4)
101 search = cls(4, **settings)
102 stats = search.run(observe, budget)
103 return dict(seed=seed, case="learned", method=name, evaluations=stats.evaluations,
104 cells=audit.filled_bins, rewarding_cells=successful.filled_bins,
105 rewarding_qd=float(successful.qd_score()), best=float(audit.best.fitness.values[0]),
106 emitter_evaluations=stats.bootstrap_evaluations + stats.emitter_evaluations,
107 model_updates=getattr(stats, "model_updates", 0))
108
109
110
111def learned(seeds, budget):
112 """Audit outcome coverage in a geometry external to the learned searches."""
113 for seed in seeds:
114 for method in ("taxons", "stax", "brns", "serene"):
115 yield _learned_trial(method, seed, budget)
116
117
118def _fork_environment():
119 import gymnasium as gym
120
121 class Fork(gym.Env):
122 observation_space = gym.spaces.Box(0., 1., (3,), dtype=np.float32)
123 action_space = gym.spaces.Discrete(2)
124 observations = np.eye(3, dtype=np.float32)
125
126 def reset(self, *, seed=None, options=None):
127 super().reset(seed=seed)
128 self.state = 0
129 return self.observations[0], {}
130
131 def step(self, action):
132 if self.state == 0:
133 self.state = int(action) + 1
134 return self.observations[self.state], 0., False, False, {}
135 reward = 1. if action == self.state - 1 else .45
136 return self.observations[self.state], reward, True, False, {}
137
138 return Fork
139
140
141def _exact_fork(actor, gamma):
142 import torch
143
144 states = actor._tensor(np.eye(3, dtype=np.float32))
145 with torch.no_grad():
146 start, left, right = actor._network(states).softmax(dim=-1).cpu().numpy()
147 visits = np.concatenate(((1. - gamma) * start, (1. - gamma) * gamma * start[0] * left,
148 (1. - gamma) * gamma * start[1] * right, [gamma ** 2]))
149 value = start[0] * (.45 + .55 * left[0]) + start[1] * (.45 + .55 * right[1])
150 return visits, float(value), int(start.argmax())
151
152
153def _exact_js(rows, pairs):
154 return float(np.mean([jensenshannon(rows[i][0], rows[j][0]) ** 2 for i, j in pairs]))
155
156
157
158def dice(seeds, budget):
159 """Measure exact discounted visitation and expected return from every exported actor."""
160 from qdpy.rl import PolicyConfig, QDDualDICEConfig, QDDualDICEJS
161
162 env = _fork_environment()
163 for seed in seeds:
164 for repulsion in (0., 1.):
165 config = QDDualDICEConfig(gamma=.7, temperature=.15, diversity_weight=repulsion,
166 episodes_per_update=6, dice_steps=8, dice_hidden_sizes=(12,),
167 actor_learning_rate=.035, dice_learning_rate=.014)
168 trainer = QDDualDICEJS(env, population_size=3, policy=PolicyConfig(()), config=config,
169 max_episode_steps=2, seed=seed)
170 panel_cost = 3 * config.episodes_per_update * 2
171 before_last = max(0, budget // panel_cost - 1) * panel_cost
172 if before_last:
173 trainer.train(before_last)
174 previous = [_exact_fork(actor, config.gamma) for actor in trainer.policies()]
175 stats = trainer.train(budget - before_last)
176 rows = [_exact_fork(actor, config.gamma) for actor in trainer.policies()]
177 pairs = tuple(combinations(range(len(rows)), 2))
178 estimated = trainer.last_divergences
179 yield dict(seed=seed, case="dice", method="dualdice-js" if repulsion else "reward-kernel-control",
180 env_steps=stats.env_steps, actor_steps=stats.actor_steps,
181 estimator_steps=stats.estimator_steps, branches=len({row[2] for row in rows}),
182 exact_js=_exact_js(rows, pairs), exact_js_before_update=_exact_js(previous, pairs),
183 return_mean=float(np.mean([row[1] for row in rows])),
184 estimated_js=None if estimated is None else float(np.mean([estimated[i][j] for i, j in pairs])))
185
186
187def main():
188 parser = argparse.ArgumentParser(description=__doc__)
189 parser.add_argument("case", choices=("mutation", "learned", "dice"))
190 parser.add_argument("--seeds", type=int, nargs="+", default=[11, 22, 33, 44, 55])
191 parser.add_argument("--budget", type=int)
192 args = parser.parse_args()
193 function, default_budget = {"mutation": (mutation, 600), "learned": (learned, 480),
194 "dice": (dice, 1440)}[args.case]
195 budget = default_budget if args.budget is None else args.budget
196 if budget < 1:
197 parser.error("budget must be positive")
198 for row in function(args.seeds, budget):
199 print(json.dumps(row, sort_keys=True), flush=True)
200
201
202if __name__ == "__main__":
203 main()