QDpy
Loading...
Searching...
No Matches
serene_trees_dvd.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# SPDX-License-Identifier: LGPL-3.0-or-later
3
5
6"""Run one or all of the sparse-reward, tree-policy, and population comparisons."""
7
8import argparse
9import json
10from pathlib import Path
11
12import numpy as np
13
14from qdpy.algorithms import DvDES, SERENE, TraceElites, behavior_logdet
15from qdpy.containers import Grid, TraceArchive
16
17
18def _navigation(genome):
19 route, endpoint = np.asarray(genome).reshape(2, 2)
20 gates = np.array([[.23, .28], [.73, .71]])
21 goals = np.array([[.14, .82], [.86, .18]])
22 route_error, goal_error = np.linalg.norm(route - gates, axis=1), np.linalg.norm(endpoint - goals, axis=1)
23 quality = np.where((route_error < .23) & (goal_error < .16), 1. - route_error - 2 * goal_error, 0.)
24 return float(quality.max()), tuple(map(float, endpoint))
25
26
27def _sparse(seed, budget):
28 settings = dict(shape=(16, 16), features_domain=((0., 1.), (0., 1.)), fitness_domain=((0., 1.),),
29 fitness_weights=(1.,))
30 for method in ("serene", "endpoint-map-elites"):
31 first, calls = None, 0
32
33 def evaluate(genome, _seed=None):
34 nonlocal first, calls
35 calls += 1
36 reward, endpoint = _navigation(genome)
37 if reward > 0 and first is None:
38 first = calls
39 return reward, endpoint
40
41 if method == "serene":
42 archive = Grid(**settings)
43 search = SERENE(archive, 4, exploration_sigma=.18, emitter_sigma=.04, seed=seed)
44 stats = search.run(evaluate, budget)
45 rows = [(ind.fitness.values[0], ind.features.values) for ind in archive]
46 phases = dict(exploration=stats.exploration_evaluations, bootstrap=stats.bootstrap_evaluations,
47 emitter=stats.emitter_evaluations, novelty_records=len(search.novelty_archive))
48 assert stats.evaluations == calls and stats.first_reward_evaluation == first
49 else:
50 archive = TraceArchive(Grid(**settings))
51 search = TraceElites(archive, 4, iso_sigma=.18, line_sigma=0., initial_samples=24, seed=seed)
52
53 def single_point(genome):
54 reward, endpoint = evaluate(genome)
55 return reward, [endpoint]
56
57 search.run(single_point, budget)
58 rows = [(elite.fitness, elite.trace[0]) for elite in archive]
59 phases = {}
60 assert calls == budget
61 regions = [max((value for value, endpoint in rows if (endpoint[0] < .5) == left), default=0.)
62 for left in (True, False)]
63 yield dict(task="sparse", method=method, seed=seed, evaluations=calls, first_reward=first,
64 rewarding_cells=sum(value > 0 for value, _ in rows), rewarding_regions=sum(x > 0 for x in regions),
65 best_reward=max(regions), region_rewards=regions, **phases)
66
67
68def _balance_factory():
69 import gymnasium as gym
70
71 class LineBalance(gym.Env):
72 """Keep a particle near the origin with two available impulses."""
73
74 observation_space = gym.spaces.Box(-np.inf, np.inf, (2,), dtype=np.float32)
75 action_space = gym.spaces.Discrete(2)
76
77 def reset(self, *, seed=None, options=None):
78 super().reset(seed=seed)
79 self.x, self.v = self.np_random.uniform([-.8, -.18], [.8, .18])
80 return np.array([self.x, self.v], dtype=np.float32), {}
81
82 def step(self, action):
83 self.v = .62 * self.v + .12 * (2 * action - 1)
84 self.x += self.v
85 return np.array([self.x, self.v], dtype=np.float32), max(0., 1. - abs(self.x)), False, False, {}
86
87 return LineBalance()
88
89
90def _trees(seed, budget, policy_dir):
91 from qdpy.rl import DecisionTreeMAPElites, DecisionTreePolicy
92
93 for selection in ("archive", "quality"):
94 method = "tree-map-elites" if selection == "archive" else "reward-only-trees"
95 search = DecisionTreeMAPElites([(-1., 1.), (-.35, .35)], max_depth=4, entropy_bins=8,
96 train_episodes=8, evaluation_episodes=4, max_episode_steps=16,
97 selection=selection, seed=seed)
98 stats = search.run(_balance_factory, budget)
99 policy = search.best_policy
100 if policy_dir:
101 policy_dir.mkdir(parents=True, exist_ok=True)
102 path = policy_dir / f"{method}-{seed}.json"
103 policy.save(path)
104 policy = DecisionTreePolicy.load(path)
105 audit = search.evaluate(_balance_factory, policy, episodes=24, seed=seed + 10_000)
106 best = search.archive.best.fitness.values[0]
107 yield dict(task="trees", method=method, seed=seed, training_steps=stats.training_steps,
108 evaluation_steps=stats.evaluation_steps, evaluated_policies=stats.evaluated_policies,
109 audit_steps=audit.steps, occupied_cells=len(search.archive), best_return=best,
110 qd_score=float(np.nansum(search.archive.quality_array)), best_depth=policy.depth,
111 audit_return=audit.mean_return, audit_entropy=audit.action_entropy)
112
113
114_MODES = np.array([[-.6, -.6], [-.6, .6], [.6, -.6], [.6, .6]])
115_PROBES = np.array([-.75, 0., .75])
116
117
118def _control(genome, rng):
119 point = np.asarray(genome).reshape(2, 2)
120 context = rng.uniform(-.85, .85)
121 action = np.tanh(point[0] + context * point[1])
122 reward = np.exp(-np.min(np.sum((action - _MODES)**2, axis=1)) / .24)
123 return float(reward)
124
125
126def _population(seed, budget):
127 initial = np.random.default_rng(seed).normal(.15, .12, size=(4, 4))
128
129 def evaluate(genome, rollout_seed):
130 point = np.asarray(genome).reshape(2, 2)
131 actions = np.tanh(point[0] + _PROBES[:, None] * point[1]).ravel()
132 return _control(genome, np.random.default_rng(rollout_seed)), actions
133
134 for method, weight in (("dvd-es", None), ("dvd-es-fixed", .5), ("independent-es", 0.)):
135 search = DvDES(initial, pairs=4, sigma=.14, learning_rate=.07, diversity_weight=weight,
136 bandwidth=.7, ind_domain=(-2., 2.), seed=seed)
137 stats = search.run(evaluate, budget)
138 diagnostics = []
139 for member in search.population:
140 outcomes = [_control(member.genome, np.random.default_rng([seed, 20_000, i])) for i in range(64)]
141 mean_action = np.mean(np.asarray(member.embedding).reshape(-1, 2), axis=0)
142 distances = np.linalg.norm(_MODES - mean_action, axis=1)
143 diagnostics.append((float(np.mean(outcomes)), int(np.argmin(distances)), float(distances.min())))
144 quality = [row[0] for row in diagnostics]
145 yield dict(task="dvd", method=method, seed=seed, evaluations=stats.evaluations, rounds=stats.updates,
146 mixed_rounds=stats.mixed_updates, audit_evaluations=64 * len(quality),
147 audit_mean=float(np.mean(quality)), audit_best=max(quality),
148 strong_modes=len({mode for reward, mode, distance in diagnostics if reward >= .7 and distance < .35}),
149 logdet=behavior_logdet([member.embedding for member in search.population], bandwidth=.7))
150
151
152
153def main():
154 """Use a headless synthetic workload and optionally persist results and trees."""
155 parser = argparse.ArgumentParser(description=__doc__)
156 parser.add_argument("task", choices=("sparse", "trees", "dvd", "all"))
157 parser.add_argument("--budget", type=int, help="Evaluator calls for sparse and dvd, or environment steps for trees.")
158 parser.add_argument("--seeds", nargs="+", type=int, default=[7, 13, 23])
159 parser.add_argument("--output", type=Path)
160 parser.add_argument("--policy-dir", type=Path)
161 args = parser.parse_args()
162 if args.budget is not None and (args.task == "all" or args.budget < {"sparse": 1, "trees": 192, "dvd": 4}[args.task]):
163 parser.error("For a custom budget select a single task and allow at least 1, 192, or 4 calls respectively.")
164 tasks = {"sparse": (_sparse, 768, ()), "trees": (_trees, 12_288, (args.policy_dir,)), "dvd": (_population, 1_156, ())}
165 selected = tasks if args.task == "all" else (args.task,)
166 lines = []
167 for task in selected:
168 run, default, options = tasks[task]
169 for seed in args.seeds:
170 for row in run(seed, args.budget or default, *options):
171 line = json.dumps(row, sort_keys=True, allow_nan=False)
172 lines.append(line)
173 print(line)
174 if args.output:
175 args.output.parent.mkdir(parents=True, exist_ok=True)
176 args.output.write_text("\n".join(lines) + "\n", encoding="utf-8")
177
178
179if __name__ == "__main__":
180 main()