QDpy
Loading...
Searching...
No Matches
few_shot_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run three seeded QD comparisons on small synthetic problems."""
6
7import argparse
8import json
9import random
10from statistics import median
11
12import numpy as np
13
14from qdpy.algorithms import DominatedNoveltySearch, FAERY, HillVallEA, QDEvo
15from qdpy.algorithms.modern import _cma_strategy
16from qdpy.containers import Grid
17from qdpy.containers.pareto import _hypervolume_2d
18
19
20def task_grid(task):
21 """Use style as the descriptor when looking for several designs near a target."""
22 return Grid(shape=(8,), features_domain=((0., 1.),), fitness_domain=((0., 1.),), fitness_weights=(1.,))
23
24
25def evaluate_design(task, genome):
26 """Score proximity in physical coordinates and report one independent style axis."""
27 x, y, style = genome
28 distance = (x - task[0])**2 + (y - task[1])**2
29 return 1. - .5 * distance, (style,), distance <= .095**2
30
31
32def mutate_design(genome, rng):
33 """Perturb a real genome within the design bounds."""
34 return tuple(map(float, np.clip(np.asarray(genome) + rng.normal(0., .115, size=3), 0., 1.)))
35
36
37def transfer_trial(seed, budget):
38 """Compare priors on held-out designs under a shared per-task search cap."""
39 rng = np.random.default_rng(seed)
40 train = ((.24, .30), (.28, .51), (.81, .35), (.74, .54), (.20, .44), (.78, .43))
41 held_out = ((.25, .33), (.30, .39), (.23, .48), (.77, .34), (.75, .37), (.79, .49),
42 (.26, .41), (.72, .47))
43 prior = tuple(tuple(map(float, row)) for row in rng.random((5, 3)))
44 training_budget = max(20, 3 * budget)
45 search = FAERY(task_grid, mutate_design, task_budget=training_budget, offspring=5, seed=seed)
46 learned = search.fit(prior, train, evaluate_design, generations=8)
47 # Spend the same source-task budget on completed searches and take the
48 # best representatives by style, never using a held-out measurement.
49 by_style, archive_calls = {}, 0
50 for _ in range(len(learned.history)):
51 for task in train:
52 run = search.adapt(prior, task, evaluate_design, seed=int(rng.integers(2**32)))
53 archive_calls += run.evaluations
54 for elite in run.archive:
55 cell = run.archive.index_grid(elite)
56 score = elite.fitness.values[0]
57 if cell not in by_style or score > by_style[cell][0]:
58 by_style[cell] = (score, tuple(elite))
59 source_elites = sorted(by_style.values(), key=lambda row: -row[0])
60 archived = tuple(dict.fromkeys([*(genome for _, genome in source_elites), *prior]))[:len(prior)]
61
62 held_seeds = rng.integers(2**32, size=len(held_out))
63 for label, start, source_calls in (("FAERY", learned.prior, learned.evaluations),
64 ("random prior", prior, 0),
65 ("source elites", archived, archive_calls)):
66 outcomes = [search.adapt(start, task, evaluate_design, budget, seed=int(rollout_seed))
67 for task, rollout_seed in zip(held_out, held_seeds)]
68 first = [result.first_success or budget + 1 for result in outcomes]
69 yield dict(method=label, seed=seed, source_evaluations=source_calls, per_task_budget=budget,
70 held_out_evaluations=sum(result.evaluations for result in outcomes),
71 tasks_solved=sum(result.first_success is not None for result in outcomes),
72 median_first_success=median(first),
73 mean_successful_designs=float(np.mean([len(result.successes) for result in outcomes])))
74
75
76PEAKS = np.asarray(((.18, .25), (.77, .27), (.53, .78)))
77
78
79def basin_cost(genome):
80 """Use a cost with three separated, equally good analytic minima."""
81 return float(np.min(np.sum((PEAKS - genome)**2, axis=1)))
82
83
84def basin_trial(seed, budget):
85 """Compare plateau-free basin discovery at a matched objective-call budget."""
86 search = HillVallEA(((0., 1.),)*2, maximise=False, initial_samples=32, local_generations=15,
87 fitness_tolerance=.002, seed=seed)
88 report = search.run(basin_cost, budget)
89
90 rng = np.random.default_rng(seed)
91 starts = []
92 for offset in range(0, budget, 90):
93 remaining = min(90, budget - offset)
94 start = _cma_strategy(rng.random(2), .15, 6, int(rng.integers(1, 2**32)), (0., 1.))
95 best = None
96 for offset_in_start in range(0, remaining, 6):
97 points = start.ask(number=min(6, remaining - offset_in_start))
98 costs = [basin_cost(point) for point in points]
99 winner = int(np.argmin(costs))
100 if best is None or costs[winner] < best[0]:
101 best = costs[winner], points[winner]
102 if len(points) == 6:
103 start.tell(points, costs)
104 starts.append(best[1])
105
106 np.random.seed(seed)
107 random.seed(seed)
108 dns = DominatedNoveltySearch(budget, 2, population_size=20, batch_size=8,
109 optimisation_task="minimisation", iso_sigma=.04)
110 dns.optimise(lambda genome: ((basin_cost(genome),), tuple(genome)))
111 controls = (
112 ("HillVallEA", [peak.genome for peak in report.peaks], report.evaluations,
113 report.probes, report.local_evaluations, report.best.fitness),
114 ("multistart CMA-ES", starts, budget, 0, budget, min(map(basin_cost, starts))),
115 ("decision-space DNS", list(dns.container), dns.nb_evaluations, 0, 0, dns.best().fitness.values[0]),
116 )
117 for label, designs, calls, probes, local, best_cost in controls:
118 distances = np.linalg.norm(PEAKS[None, :, :] - np.asarray(designs)[:, None, :], axis=2) if designs else None
119 covered = int(np.count_nonzero(np.min(distances, axis=0) <= .04)) if distances is not None else 0
120 yield dict(method=label, seed=seed, evaluations=calls, probes=probes,
121 local_evaluations=local, peaks_recovered=covered, best_cost=best_cost)
122
123
124def schedule(rule, case):
125 """Return a job order and the number of priority terms evaluated."""
126 adaptive, duration_weight, due_weight = rule
127 durations, due = case
128 duration = durations / durations.mean()
129 deadlines = due / due.mean()
130 terms = int(duration_weight > 0) + int(due_weight > 0)
131 if not adaptive:
132 return np.argsort(duration_weight * duration + due_weight * deadlines, kind="stable"), terms * len(durations)
133 pending, picks = list(range(len(durations))), []
134 time = 0
135 while pending:
136 slack = np.maximum(0., (due[pending] - durations[pending] - time) / due.mean())
137 priorities = duration_weight * duration[pending] + due_weight * slack
138 job = pending.pop(int(np.argmin(priorities)))
139 picks.append(job)
140 time += durations[job]
141 return np.asarray(picks), terms * len(durations) * (len(durations) + 1) // 2
142
143
144def schedule_metrics(rule, cases):
145 """Measure normalized weighted tardiness and normalized priority work."""
146 rows = []
147 for case in cases:
148 jobs, effort = schedule(rule, case)
149 durations, due = case
150 lateness = np.maximum(0., np.cumsum(durations[jobs]) - due[jobs])
151 cost = float(np.mean(lateness * np.where(durations[jobs] % 2, 1., .25)) / durations.sum())
152 rows.append((cost, effort / (len(jobs) * (len(jobs) + 1))))
153 return tuple(map(float, np.mean(rows, axis=0)))
154
155
156def schedule_proposal(parents, rng):
157 """Mutate one scheduling field, optionally blending two parents' rules."""
158 if not parents:
159 return (int(rng.integers(2)), int(rng.integers(1, 8)), int(rng.integers(8)))
160 rule = list(parents[0].heuristic)
161 if len(parents) == 2:
162 coordinate = int(rng.integers(3))
163 rule[coordinate] = parents[1].heuristic[coordinate]
164 coordinate = int(rng.integers(3))
165 if coordinate == 0:
166 rule[0] = 1 - rule[0]
167 else:
168 rule[coordinate] = int(np.clip(rule[coordinate] + rng.choice((-2, -1, 1, 2)), 0, 7))
169 return tuple(rule) if any(rule[1:]) else None
170
171
172def _cases(rng, n):
173 cases = []
174 for _ in range(n):
175 durations = rng.integers(1, 18, size=8)
176 cases.append((durations, rng.uniform(.05, .8, size=8) * durations.sum()))
177 return cases
178
179
180def semantic_trial(seed, budget):
181 """Compare clustered and global Pareto retention on held-out job schedules."""
182 rng = np.random.default_rng(seed)
183 train, embedding_panel, held_out = (_cases(rng, size) for size in (8, 6, 12))
184
185 def embed(rule):
186 ranks = [np.argsort(schedule(rule, case)[0]) - (len(case[0]) - 1) / 2. for case in embedding_panel]
187 return np.ravel(ranks)
188
189 for label, similarity in (("QDEvo", .85), ("global Pareto", -1.)):
190 search = QDEvo(propose=schedule_proposal, embed=embed, evaluate=lambda rule: schedule_metrics(rule, train),
191 fitness_weights=(-1., -1.), similarity=similarity, seed=seed)
192 stats = search.run(budget, initial=((0, 1, 0), (0, 0, 1), (1, 1, 1)))
193 held = [schedule_metrics(entry.heuristic, held_out) for cluster in search.clusters for entry in cluster]
194 rows = [(-cost, -effort) for cost, effort in held]
195 yield dict(method=label, seed=seed, evaluated_rules=stats.evaluations,
196 training_instance_calls=len(train) * stats.evaluations, niches=len(search.clusters),
197 embedding_instance_calls=len(embedding_panel) * stats.evaluations,
198 retained_rules=len(held), held_out_calls=len(held_out) * len(held),
199 held_out_hypervolume=float(_hypervolume_2d(rows, (-1., -1.05))),
200 best_held_out_cost=min(cost for cost, _ in held))
201
202
203if __name__ == "__main__":
204 trials = {"transfer": (transfer_trial, 20, 5), "basins": (basin_trial, 540, 16),
205 "semantic": (semantic_trial, 42, 3)}
206 parser = argparse.ArgumentParser(description=__doc__)
207 parser.add_argument("task", choices=trials)
208 parser.add_argument("--budget", type=int)
209 parser.add_argument("--seeds", type=int, nargs="+", default=[11, 22, 33])
210 args = parser.parse_args()
211 trial, default, minimum = trials[args.task]
212 budget = args.budget if args.budget is not None else default
213 if budget < minimum:
214 parser.error(f"This comparison needs a budget of at least {minimum}.")
215 for seed in args.seeds:
216 for row in trial(seed, budget):
217 print(json.dumps(row, sort_keys=True))