# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Benchmark counterexample-guided QD, symmetry reduction, and Policy Manifold Search. """Compare each method against a matched baseline on bounded seeded workloads.""" import argparse import json import random from collections import deque from itertools import permutations, product from pathlib import Path from time import perf_counter import numpy as np from qdpy.algorithms import ( CounterexampleMAPElites, DDEElites, IsoLineMAPElites, PolicyManifoldSearch, ScenarioRiskMAPElites, SymmetryAwareMAPElites, ) from qdpy.containers import Grid _DURATIONS = (3, 3, 2, 4, 2, 2, 1, 3) _DEADLINES = (5, 5, 7, 9, 10, 11, 12, 13) _SCENARIOS = (None, *range(len(_DURATIONS))) _INITIAL_SCENARIOS = (None, 6, 7) _EDGES = tuple((i, j) for i in range(5) for j in range(i + 1, 5) if (i, j) != (0, 1)) _EDGE_INDEX = {edge: i for i, edge in enumerate(_EDGES)} _LABELS = ((0, 1, *internal) for internal in permutations((2, 3, 4))) _RELABELS = tuple(tuple(_EDGE_INDEX[tuple(sorted((perm[i], perm[j])))] for i, j in _EDGES) for perm in _LABELS) _CONTROL_STEPS = 24 _CONTROL_DIMENSION = 16 def _binary_proposal(size): def propose(rng): return tuple(map(int, rng.integers(2, size=size))) return propose def _flip(parent, rng): child = list(parent) index = rng.integers(len(child)) child[index] = 1 - child[index] return tuple(child) def _summary(archive): return dict(cells=len(archive), qd_score=sum(elite.fitness.values[0] for elite in archive)) def schedule_measure(genome): """Measure nominal makespan and describe assignment balance and switches.""" loads = _completion_times(genome, None) quality = 1. / max(loads) switches = sum(first != second for first, second in zip(genome, genome[1:])) return (quality,), (sum(genome), switches) def _completion_times(genome, delayed_job): loads, completion = [0, 0], [] for job, (machine, duration) in enumerate(zip(genome, _DURATIONS, strict=True)): loads[machine] += duration + 2 * (delayed_job == job) completion.append(loads[machine]) return completion def schedule_check(genome, delayed_job): """Check every deadline after delaying the selected job by two time units.""" return all(finish <= deadline for finish, deadline in zip(_completion_times(genome, delayed_job), _DEADLINES)) def _schedule_grid(): return Grid(shape=(9, 8), features_domain=((0, 9), (0, 8)), fitness_domain=((.001, 1.),), fitness_weights=(1.,)) def _schedule_optima(archive): best = {} for genome in product((0, 1), repeat=len(_DURATIONS)): if all(schedule_check(genome, case) for case in _SCENARIOS): (fitness,), features = schedule_measure(genome) cell = archive.index_grid(features) best[cell] = max(fitness, best.get(cell, 0.)) return best def compare_scheduling(budget, seed): """Compare verified coverage on fixed and counterexample-driven screening.""" initializer = _binary_proposal(len(_DURATIONS)) oracle = _schedule_optima(_schedule_grid()) check_limit = budget * len(_INITIAL_SCENARIOS) matched_limit = check_limit for method in ("counterexample", "fixed-panel", "fixed-panel-matched-checks"): archive = _schedule_grid() limit = matched_limit if method == "fixed-panel-matched-checks" else check_limit if method == "counterexample": search = CounterexampleMAPElites( archive, _SCENARIOS, initial_scenarios=_INITIAL_SCENARIOS, propose=initializer, mutate=_flip, measure=schedule_measure, verify=schedule_check, seed=seed, ) stats = search.run(proposals=budget, checks=limit) attempts, checks, learned = stats.proposals, stats.checks, stats.counterexamples panel_size = len(_INITIAL_SCENARIOS) matched_limit = ((checks + panel_size - 1) // panel_size) * panel_size else: # The worst score on this fixed panel must be positive for admission. search = ScenarioRiskMAPElites( archive, _INITIAL_SCENARIOS, initializer=initializer, mutate=_flip, tail_fraction=1. / len(_INITIAL_SCENARIOS), objective="cvar", seed=seed, ) def evaluate(genome, case): (quality,), features = schedule_measure(genome) return quality if schedule_check(genome, case) else 0., features stats = search.run(evaluate, limit) attempts, checks, learned = stats.candidates, stats.scenario_calls, 0 audited = {} for elite in archive: # Audit every scenario for every elite in both arms. passed = [schedule_check(elite, case) for case in _SCENARIOS] if all(passed): audited[archive.index_grid(elite)] = elite.fitness.values[0] assert all(cell in oracle and quality <= oracle[cell] for cell, quality in audited.items()) if method == "counterexample": assert len(audited) == len(archive) proposal_limit = budget if method == "counterexample" else limit // len(_INITIAL_SCENARIOS) yield dict(task="scheduling", method=method, seed=seed, proposal_limit=proposal_limit, proposals=attempts, check_limit=limit, checks=checks, audit_checks=len(_SCENARIOS) * len(archive), counterexamples=learned, reachable_cells=len(oracle), archive_cells=len(archive), verified_cells=len(audited), verified_qd_score=sum(audited.values())) def canonical_network(genome): """Return the lexicographically first network under internal-node relabeling.""" return min(tuple(genome[index] for index in permutation) for permutation in _RELABELS) def network_measure(genome): """Score terminal connectivity and the number of tolerated single-edge failures.""" present = tuple(edge for edge, enabled in zip(_EDGES, genome, strict=True) if enabled) locations = [set() for _ in range(5)] for i, j in present: locations[i].add(j) locations[j].add(i) def distance(): queue, visited = deque([(0, 0)]), {0} while queue: vertex, depth = queue.popleft() if vertex == 1: return depth for successor in locations[vertex] - visited: visited.add(successor) queue.append((successor, depth + 1)) return 0 hops = distance() if not hops: return (0.,), (len(present), 0) resilient = 0 for first, second in present: locations[first].remove(second) locations[second].remove(first) resilient += bool(distance()) locations[first].add(second) locations[second].add(first) return ((1. + resilient) / (len(_EDGES) + 1),), (len(present), hops) def _network_grid(): return Grid(shape=(len(_EDGES) + 1, 5), features_domain=((0, len(_EDGES) + 1), (0, 5)), fitness_domain=((.001, 1.),), fitness_weights=(1.,)) def _network_oracle(grid): labelled, canonical = {}, {} representatives = set() for genome in product((0, 1), repeat=len(_EDGES)): representative = canonical_network(genome) representatives.add(representative) original, reduced = network_measure(genome), network_measure(representative) assert original == reduced for measurement, report in ((original, labelled), (reduced, canonical)): (fitness,), features = measurement if fitness > 0.: cell = grid.index_grid(features) report[cell] = max(fitness, report.get(cell, 0.)) assert labelled == canonical return canonical, len(representatives) def compare_networks(budget, seed): """Compare label-sensitive and canonical caching on the same network problem.""" exact, representatives = _network_oracle(_network_grid()) for method, canonicalize in (("symmetry-aware", canonical_network), ("labelled", tuple)): archive = _network_grid() search = SymmetryAwareMAPElites(archive, canonicalize=canonicalize, propose=_binary_proposal(len(_EDGES)), mutate=_flip, seed=seed) stats = search.run(network_measure, proposals=budget) assert all(archive.index_grid(elite) in exact for elite in archive) yield dict(task="networks", method=method, seed=seed, proposals=stats.proposals, evaluations=stats.evaluations, duplicates=stats.duplicates, labelled_space=2 ** len(_EDGES), canonical_space=representatives, reachable_cells=len(exact), **_summary(archive)) def control_rollout(genome): """Roll out a bounded continuous feedback controller over a fixed horizon.""" weights = np.asarray(genome, dtype=float).reshape(2, _CONTROL_DIMENSION // 2) position, velocity = np.zeros(2), np.zeros(2) actions = [] for step in range(_CONTROL_STEPS): phase = 2 * np.pi * step / _CONTROL_STEPS features = (1., *position, *velocity, np.sin(phase), np.cos(phase), np.sin(2 * phase)) action = np.tanh(weights @ features) velocity = .92 * velocity + .05 * action position += velocity actions.append(action) effort = np.mean(np.square(actions)) change = np.mean(np.square(np.diff(actions, axis=0))) quality = float(np.exp(-effort - .45 * change)) return (quality,), tuple(np.tanh(position / 1.5)) class _TimedDDE(DDEElites): def reinit(self): super().reinit() self.model_fit_seconds = 0. fit = self._model.fit def timed_fit(*args, **kwargs): start = perf_counter() result = fit(*args, **kwargs) self.model_fit_seconds += perf_counter() - start return result self._model.fit = timed_fit def compare_control(budget, seed): """Compare native policy-vector optimisation at equal candidate rollout counts.""" import torch torch.set_num_threads(1) for method in ("poms", "dde-elites", "iso-line"): archive = Grid(shape=(10, 10), features_domain=((-1., 1.),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,)) options = dict(container=archive, budget=budget, dimension=_CONTROL_DIMENSION, batch_size=16, ind_domain=(-1., 1.), optimisation_task="max") model = dict(min_elites=4, fit_interval=2, fit_epochs=8, fit_batch_size=32, hidden_size=24, latent_size=4, seed=seed) random.seed(seed) np.random.seed(seed) if method == "poms": search = PolicyManifoldSearch(sigma=.05, **model, **options) elif method == "dde-elites": search = _TimedDDE(iso_sigma=.10, **model, **options) else: search = IsoLineMAPElites(iso_sigma=.10, **options) start = perf_counter() search.optimise(control_rollout, batch_mode=True) yield dict(task="control", method=method, seed=seed, rollouts=search.nb_evaluations, environment_steps=_CONTROL_STEPS * search.nb_evaluations, model_fits=getattr(search, "model_fits", 0), model_fit_seconds=getattr(search, "model_fit_seconds", 0.), variation=getattr(search, "operator_counts", {}), seconds=perf_counter() - start, **_summary(archive)) def main(): """Run both base benchmarks by default, or include the optional control task.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--task", choices=("base", "scheduling", "networks", "control", "all"), default="base") parser.add_argument("--seeds", type=int, default=3) parser.add_argument("--budget", type=int, default=160) parser.add_argument("--output", type=Path) args = parser.parse_args() if args.seeds < 1 or args.budget < 1: parser.error("seeds and budget must be positive") tasks = {"scheduling": compare_scheduling, "networks": compare_networks, "control": compare_control} chosen = ("scheduling", "networks") if args.task == "base" else tuple(tasks) if args.task == "all" else (args.task,) rows = [row for task in chosen for seed in range(args.seeds) for row in tasks[task](args.budget, seed)] contents = "".join(json.dumps(row, sort_keys=True, allow_nan=False) + "\n" for row in rows) if args.output is None: print(contents, end="") else: args.output.write_text(contents, encoding="utf-8") if __name__ == "__main__": main()