5"""Compare guided search methods on small, reproducible tasks."""
8from dataclasses
import asdict
10from pathlib
import Path
14from qdpy.algorithms import (OperatorMOME, PriorGuidedOfflineMAPElites, fit_tabular_successor_features,
15 tabular_optimal_policy, tabular_sfols)
21def symbolic_trials(seed, budget):
22 rng = np.random.default_rng(seed)
23 training = rng.uniform(-1., 1., (48, 2))
24 test = rng.uniform(-1.3, 1.3, (96, 2))
26 "sin-product":
lambda x: np.sin(2 * x[:, 0]) * x[:, 1] + x[:, 1]**2,
27 "polynomial":
lambda x: (x[:, 0] + x[:, 1]) * (x[:, 0] - x[:, 1]) + .4 * x[:, 1],
29 for task, target
in targets.items():
30 for variation
in (
"subtree",
"template-linkage",
"learned-linkage"):
31 result =
symbolic_regression(training, target(training), variation=variation, budget=12 * budget,
32 max_fit_evaluations=budget, fit_evaluations=24,
33 max_depth=3, max_nodes=11, operators=(
"add",
"sub",
"mul",
"sin",
"square"),
35 yield dict(task=task, method=variation, seed=seed, training_rmse=result.best.training_rmse,
36 archive_cells=len(result.archive), nodes=result.best.expression.node_count,
37 heldout_rmse=result.best.rmse(test, target(test)), **asdict(result.stats))
41 rng = np.random.default_rng(seed)
42 groups = ([0], [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12])
43 coordinates = rng.uniform(.1, 1., (13, 3, 2))
44 transitions = np.zeros((13, 3, 13))
45 for current, following
in zip(groups, groups[1:]):
47 transitions[state, np.arange(3), rng.permutation(following)] = 1.
49 return transitions, coordinates, start
53def policy_trials(seed, budget):
54 transitions, rewards, start = _navigation(seed)
56 result = tabular_sfols(transitions, rewards, start, gamma=gamma, max_policy_solves=budget)
57 alternatives = [tabular_optimal_policy(transitions, rewards, (w, 1. - w), gamma=gamma)
58 for w
in np.linspace(0., 1., result.policy_solves)]
59 fixed = fit_tabular_successor_features(transitions, rewards, alternatives, gamma=gamma)
60 panel = [(w, 1. - w)
for w
in (np.arange(40) + .5) / 40]
62 def performance(policy, weight):
63 repertoire = fit_tabular_successor_features(transitions, rewards, [policy], gamma=gamma)
64 return float(repertoire.action_values(weight)[0, 0, policy[0]])
66 exact = [performance(tabular_optimal_policy(transitions, rewards, weight, gamma=gamma), weight)
68 for method, repertoire, count
in ((
"sfols", result.repertoire, len(result.policies)),
69 (
"uniform-weights", fixed, len(set(alternatives)))):
70 returns = [performance(repertoire.action_table(weight), weight)
for weight
in panel]
71 regrets = np.maximum(0., np.subtract(exact, returns))
72 yield dict(task=
"reward-transfer", method=method, seed=seed, policies=count,
73 policy_solves=result.policy_solves, audit_weights=len(panel), mean_return=float(np.mean(returns)),
74 mean_regret=float(regrets.mean()), worst_regret=float(regrets.max()),
75 bound_solves=result.bound_solves
if method ==
"sfols" else 0,
76 upper_gap=result.upper_gap
if method ==
"sfols" else None)
80def offline_trials(seed, budget):
81 rng = np.random.default_rng(seed)
84 return ((point[2] == point[4]) + (point[3] == point[5])) / 2.
86 def measure(point, reset_seed):
87 a, b, c, d, e, f = point
88 compatibility = prior(point)
89 quality = .38 + .4 * compatibility + .14 * (e == (a + b) % 3) + .05 * (c == (b + 1) % 3)
90 return (quality,), (a, b)
94 prefix = rng.choice(3, 2, p=[.70, .23, .07])
95 point = tuple(map(int, (*prefix, *rng.integers(3, size=4))))
96 log[point] = measure(point, seed)
97 training, goals = zip(*log.values())
98 fitness = np.asarray(training)[:, 0]
100 for method, weight, penalty
in ((
"pome", 1., 0.), (
"fixed-penalty", 0., 1.), (
"prior-free", 0., 0.)):
101 archive = Grid(shape=(3, 3), features_domain=((-0.5, 2.5),) * 2,
102 fitness_domain=((0., 1.),), fitness_weights=(1.,))
103 search = PriorGuidedOfflineMAPElites(archive, tuple(log), fitness, goals, nvec=(3,) * 6,
104 prior=prior, prior_weight=weight, uncertainty_penalty=penalty,
106 result = search.run(budget)
107 audit = search.verify(result, measure, 9, seed=1000 + seed)
108 yield dict(task=
"offline-configurations", method=method, seed=seed, training_rows=len(log),
109 predictions=result.predictions, prior_queries=result.prior_queries,
110 predicted_cells=len(result.archive), matched_cells=audit.cell_matches,
111 audit_evaluations=audit.evaluations, verified_cells=len(audit.archive),
112 verified_qd_score=audit.archive.qd_score(),
113 mean_verified_quality=float(np.mean([p.fitness.values[0]
for p
in audit.archive])))
117def scheduling_trials(seed, budget):
120 from qdpy.rl import DMOME, DMOMEConfig
122 torch.set_num_threads(1)
123 rng = np.random.default_rng(seed)
125 durations = rng.integers(1, 8, size=jobs)
126 due = rng.permutation(np.arange(3, 4 * jobs, 4))
127 weights = rng.integers(1, 4, size=jobs)
128 family = rng.permutation(np.arange(jobs) % 3)
130 def measure(order, reset_seed):
131 assert len(order) == jobs
and len(set(order)) == jobs
132 clock = tardiness = setup_cost = switches = 0
135 changed = family[job] != family[previous]
136 setup = int(changed) * (1 + (job + 2 * previous) % 4)
139 clock += durations[job] + setup
140 tardiness += max(0, clock - due[job]) * weights[job]
142 return (tardiness, setup_cost), (family[order[0]], switches)
144 def swap(parent, donor, rng):
145 vector = list(parent)
146 index = int(rng.integers(jobs - 1))
147 vector[index:index + 2] = reversed(vector[index:index + 2])
150 def reverse(parent, donor, rng):
151 start, end = sorted(rng.choice(jobs, 2, replace=
False))
152 return (*parent[:start], *reversed(parent[start:end + 1]), *parent[end + 1:])
154 def splice(parent, donor, rng):
155 prefix = parent[:int(rng.integers(1, jobs))]
156 return (*prefix, *(job
for job
in donor
if job
not in prefix))
158 def repair(parent, donor, rng):
159 start = int(rng.integers(jobs - 2))
160 middle = sorted(parent[start:start + 3], key=
lambda job: due[job])
161 return (*parent[:start], *middle, *parent[start + 3:])
163 for method
in (
"uniform",
"bandit",
"dqn"):
164 archive = ParetoGrid(shape=(3, jobs), max_items_per_bin=3, truncation=
"hypervolume",
165 features_domain=((-0.5, 2.5), (-0.5, jobs - .5)),
166 fitness_domain=((0., 1800.), (0., 28.)), fitness_weights=(-1., -1.))
167 options = dict(initializer=
lambda rng: rng.permutation(jobs),
168 operators=dict(swap=swap, reverse=reverse, splice=splice, repair=repair),
169 initial_samples=20, seed=seed)
171 search = DMOME(archive, config=DMOMEConfig(hidden_sizes=(16, 16), batch_size=16, target_period=16),
174 search = OperatorMOME(archive, controller=method, **options)
175 stats = search.run(measure, budget)
176 rough_worst = (1800., 28.)
177 yield dict(task=
"scheduling", method=method, seed=seed, archive_cells=archive.filled_bins,
178 archive_members=len(archive), qd_hypervolume=archive.qd_hypervolume(rough_worst) / np.prod(rough_worst),
184 parser = argparse.ArgumentParser(description=__doc__)
185 parser.add_argument(
"task", nargs=
"?", choices=(
"symbolic",
"policy",
"offline",
"scheduling"))
186 parser.add_argument(
"--budget", type=int)
187 parser.add_argument(
"--seeds", nargs=
"+", type=int, default=[11, 23, 47])
188 parser.add_argument(
"--output", type=Path)
189 args = parser.parse_args()
190 if args.budget
is not None and args.budget < 2:
191 parser.error(
"--budget must be at least two.")
192 tasks = dict(symbolic=(symbolic_trials, 720), policy=(policy_trials, 5),
193 offline=(offline_trials, 360), scheduling=(scheduling_trials, 512))
195 for task
in (args.task,)
if args.task
else (
"symbolic",
"policy",
"offline"):
196 trial, default = tasks[task]
197 for seed
in args.seeds:
198 for result
in trial(seed, args.budget
or default):
199 line = json.dumps(result, allow_nan=
False, sort_keys=
True)
202 if args.output
is not None:
203 args.output.parent.mkdir(parents=
True, exist_ok=
True)
204 args.output.write_text(
"\n".join(records) +
"\n", encoding=
"utf-8")
207if __name__ ==
"__main__":