QDpy
Loading...
Searching...
No Matches
hierarchical_generative_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Run four small matched-budget comparisons and emit per-seed JSONL."""
6
7import argparse
8import json
9import random
10from itertools import combinations, pairwise, product
11from pathlib import Path
12
13import numpy as np
14from scipy.special import expit
15
16from qdpy.algorithms import (
17 MOME,
18 ConstructiveDAG,
19 CounterfactualMOME,
20 HierarchicalArchive,
21 HierarchicalMAPElites,
22 PreferenceGFlowNet,
23 SoftPromptMAPElites,
24)
25from qdpy.containers import CVTGrid, Grid, ParetoGrid
26from qdpy.phenotype import Features, Fitness, Individual
27
28JOBS = ((2, 5), (3, 9), (5, 8), (4, 14), (6, 13), (3, 17), (7, 18))
29SITES = ((0, 0), (1, 0), (0, 3), (3, 1), (3, 3), (2, 3), (2, 0), (1, 2))
30REFERENCES = ((0, 1, 2, 7), (1, 4, 5, 6))
31AUDIT_PATROLS = ((0, 2, 4, 5), (2, 3, 5, 7))
32UNIT = ((0., 1.),)
33
34
35def grid(shape):
36 """Make a best-only unit grid with a maximizing quality objective."""
37 return Grid(shape=shape, features_domain=UNIT * len(shape), fitness_domain=UNIT, fitness_weights=(1.,))
38
39
40def start_schedule(rng):
41 """Draw a job order and a crew assignment for each job."""
42 return (tuple(map(int, rng.permutation(len(JOBS)))),
43 tuple(map(int, rng.integers(2, size=len(JOBS)))))
44
45
46def mutate_schedule(genome, rng):
47 """Swap two priorities or move one job to the other crew."""
48 order, crews = genome
49 if rng.random() < .5:
50 first, second = rng.choice(len(JOBS), size=2, replace=False)
51 change = list(order)
52 change[first], change[second] = change[second], change[first]
53 return tuple(change), crews
54 slot = int(rng.integers(len(JOBS)))
55 return order, crews[:slot] + (1 - crews[slot],) + crews[slot + 1:]
56
57
58def measure_schedule(genome):
59 """Measure tardiness, overtime, and two staffing proportions."""
60 order, crews = genome
61 loads = [0, 0]
62 tardiness = 0
63 for job in order:
64 duration, deadline = JOBS[job]
65 crew = crews[job]
66 loads[crew] += duration
67 tardiness += max(loads[crew] - deadline, 0)
68 overtime = max(0, max(loads) - 16) / 14.
69 return 1. / (1. + tardiness / 12.), (overtime,), (sum(crews[:3]) / 3., sum(crews[3:]) / 4.)
70
71
72def hierarchy_trial(seed, budget):
73 """Compare hierarchy and flat CVT with the same 18-cell Cartesian geometry."""
74 nested = HierarchicalArchive(grid((3,)), lambda cell: grid((2, 3)))
75 algorithm = HierarchicalMAPElites(nested, propose=start_schedule, mutate=mutate_schedule, seed=seed)
76 algorithm.run(measure_schedule, budget=budget)
77
78 thirds = (1 / 6, .5, 5 / 6)
79 sites = tuple(product(thirds, (.25, .75), thirds))
80 flat = CVTGrid(shape=len(sites), centroids=sites, features_domain=UNIT * 3,
81 fitness_domain=UNIT, fitness_weights=(1.,))
82 rng = np.random.default_rng(seed)
83 for _ in range(budget):
84 if len(flat) and rng.random() >= .1:
85 genome = mutate_schedule(flat[int(rng.integers(len(flat)))][0], rng)
86 else:
87 genome = start_schedule(rng)
88 score, coarse, fine = measure_schedule(genome)
89 flat.add(Individual((genome,), fitness=Fitness((score,), weights=(1.,)),
90 features=Features(coarse + fine)))
91
92 rows = []
93 for name, archive in (("hierarchical", nested), ("flat-cvt", flat)):
94 per_range = [0, 0, 0]
95 qualities = [0., 0., 0.]
96 for elite in archive:
97 coarse = nested.coarse_descriptor(elite) if name == "hierarchical" else elite.features.values[:1]
98 cell, = nested.index(coarse)
99 per_range[cell] += 1
100 qualities[cell] += elite.fitness.values[0]
101 rows.append({"task": "hierarchy", "method": name, "seed": seed, "evaluations": budget,
102 "alternatives": per_range, "quality_by_range": qualities,
103 "quality_sum": sum(qualities)})
104 return rows
105
106
107def observation_trace(genome):
108 """Visit the four highest-priority sites and measure value and travel cost."""
109 visited = tuple(map(int, np.argsort(-np.asarray(genome), kind="stable")[:4]))
110 travel = sum(abs(SITES[a][0] - SITES[b][0]) + abs(SITES[a][1] - SITES[b][1])
111 for a, b in pairwise(visited))
112 observed_value = sum(.2 + .25 * (i % 3) for i in visited) / 4.
113 return (observed_value, 1. / (1. + travel / 7.)), (visited, travel)
114
115
116def aggregate_route(trace):
117 """Describe the fraction of odd site IDs and the traveled distance."""
118 visited, travel = trace
119 return sum(i % 2 for i in visited) / len(visited), travel / 18.
120
121
122def overlap(trace, patrol):
123 """Measure overlap between the learner's visited sites and a virtual patrol."""
124 visited, _ = trace
125 return (len(set(visited).intersection(patrol)) / len(visited),)
126
127
128def counterfactual_trial(seed, budget):
129 """Evaluate the two MOME variants on a shared held-out patrol panel."""
130 rows = []
131 for guided in (False, True):
132 np.random.seed(seed)
133 random.seed(seed)
134 archive = ParetoGrid(shape=(4, 4), max_items_per_bin=3, features_domain=UNIT * 2,
135 fitness_domain=UNIT * 2, fitness_weights=(1., 1.))
136 options = {"budget": budget, "dimension": len(SITES), "batch_size": 8, "iso_sigma": .12}
137 if guided:
138 search = CounterfactualMOME(archive, **options)
139 search.run(observation_trace, references=REFERENCES, describe=overlap)
140 else:
141 search = MOME(archive, **options)
142
143 def evaluate(genome):
144 values, trace = observation_trace(genome)
145 return values, aggregate_route(trace)
146
147 search.optimise(evaluate)
148 audit = grid((4, 4))
149 occupied = set()
150 for elite in archive:
151 _, trace = observation_trace(elite)
152 descriptors = tuple(overlap(trace, patrol)[0] for patrol in AUDIT_PATROLS)
153 occupied.add(audit.index_grid(descriptors))
154 rows.append({"task": "counterfactual", "method": "c-mome" if guided else "mome", "seed": seed,
155 "evaluations": search.nb_evaluations, "audits": len(archive),
156 "heldout_cells": len(occupied), "hypervolume": archive.global_hypervolume((0., 0.))})
157 return rows
158
159
160def subset_graph():
161 """Construct three-item sets so that each leaf has six construction paths."""
162 nodes = [items for size in range(4) for items in combinations(range(5), size)]
163 return ConstructiveDAG((), {items: tuple(tuple(sorted((*items, i)))
164 for i in range(5) if len(items) < 3 and i not in items)
165 for items in nodes})
166
167
168def subset_values(items):
169 """Favor two different item motifs on a fixed constructive search task."""
170 return 1. + 2 * len(set(items).intersection((0, 1, 2))), 1. + 2 * len(set(items).intersection((0, 3, 4)))
171
172
173def subset_assessment(items):
174 """Audit shared coverage and scalar quality on a subset."""
175 value = sum(subset_values(items)) / 12.
176 return value, (sum(i in (1, 2) for i in items) / 2., float(0 in items))
177
178
179def gflownet_trial(seed, budget):
180 """Validate terminal probabilities and compare archive proposals at equal evaluation counts."""
181 graph = subset_graph()
182 flow = PreferenceGFlowNet(graph, subset_values, objectives=2, reward_power=3., seed=seed)
183 weights = ((1., 0.), (.75, .25), (.5, .5), (.25, .75), (0., 1.))
184 training = flow.fit(weights, updates=350, batch_size=40)
185 flow_archive = grid((3, 2))
186 flow.illuminate(flow_archive, subset_assessment, weights, budget=budget)
187 rng = np.random.default_rng(seed)
188 uniform = grid((3, 2))
189 for i in rng.integers(len(graph.terminals), size=budget):
190 subset = graph.terminals[i]
191 value, descriptors = subset_assessment(subset)
192 uniform.add(Individual((subset,), fitness=Fitness((value,), weights=(1.,)),
193 features=Features(descriptors)))
194 errors, uniform_errors = [], []
195 for preference in ((1., 0.), (.63, .37), (0., 1.)):
196 desired = flow.target_distribution(preference)
197 measured = flow.distribution(preference)
198 errors.append(sum(abs(measured[key] - value) for key, value in desired.items()) / 2)
199 uniform_errors.append(sum(abs(1. / len(desired) - value) for value in desired.values()) / 2)
200 rows = []
201 for method, archive, distances in (("gflownet", flow_archive, errors), ("uniform", uniform, uniform_errors)):
202 rows.append({"task": "gflownet", "method": method, "seed": seed, "evaluations": budget,
203 "reward_calls": training.reward_calls if method == "gflownet" else 0,
204 "audit_reward_calls": flow.stats.reward_calls - training.reward_calls if method == "gflownet" else 0,
205 "training_trajectories": training.trajectories if method == "gflownet" else 0,
206 "mean_tv": float(np.mean(distances)), "cells": len(archive), "qd": archive.qd_score()})
207 return rows
208
209
210def decode_fixture(embedding, seed):
211 """Produce a controlled text output from a frozen two-coordinate stochastic decoder."""
212 noise = np.random.default_rng(seed).normal(scale=.18, size=2)
213 travel, stops = expit(embedding[0] + noise)
214 return f"travel {travel:.8f} stops {stops:.8f}"
215
216
217def assess_text(text):
218 """Read behavioral measurements and score a synthetic text output."""
219 _, x, _, y = text.split()
220 first, second = float(x), float(y)
221 quality = 1. - .5 * abs(first - .65) - .5 * abs(second - .3)
222 return quality, (first, second)
223
224
225def prompt_trial(seed, budget):
226 """Compare prompt variants while counting every decode and finite-difference probe."""
227 rows = []
228 for mode in ("targeted", "gaussian", "fixed"):
229 archive = grid((5, 5))
230 search = SoftPromptMAPElites(archive, [[0., 0.]], sigma=.45, probe_step=.35,
231 probe_directions=2, seed=seed)
232 search.run(decode_fixture, assess_text, budget=budget, mode=mode)
233 rows.append({"task": "soft-prompt", "method": mode, "seed": seed,
234 "generations": search.stats.generations, "probes": search.stats.probes,
235 "cells": len(archive), "qd": archive.qd_score()})
236 return rows
237
238
239def main():
240 """Run the base comparisons and optionally the PyTorch sampler."""
241 tasks = {"hierarchy": (hierarchy_trial, 180), "counterfactual": (counterfactual_trial, 192),
242 "gflownet": (gflownet_trial, 30), "soft-prompt": (prompt_trial, 120)}
243 parser = argparse.ArgumentParser(description=__doc__)
244 parser.add_argument("task", choices=(*tasks, "all"))
245 parser.add_argument("--include-torch", action="store_true", help="Include GFlowNet when running all.")
246 parser.add_argument("--budget", type=int, help="Override each workload's candidate budget.")
247 parser.add_argument("--seeds", type=int, nargs="+", default=[11, 12, 13, 14, 15])
248 parser.add_argument("--output", type=Path, help="Write per-seed JSONL to this path.")
249 args = parser.parse_args()
250 if args.budget is not None and args.budget < 1:
251 parser.error("budget must be positive.")
252 selected = tuple(tasks) if args.task == "all" else (args.task,)
253 if args.task == "all" and not args.include_torch:
254 selected = tuple(name for name in selected if name != "gflownet")
255 if "gflownet" in selected:
256 import torch
257
258 torch.set_num_threads(1)
259 rows = [row for name in selected for seed in args.seeds
260 for row in tasks[name][0](seed, args.budget or tasks[name][1])]
261 report = "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows)
262 if args.output is None:
263 print(report, end="")
264 else:
265 args.output.write_text(report, encoding="utf-8")
266
267
268if __name__ == "__main__":
269 main()