# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare shared model merging, subset search, trust regions, and subgoal search. """Run four reproducible CPU comparisons on small optimization problems.""" import argparse from itertools import combinations import json from math import dist import numpy as np from qdpy.algorithms import (BooleanConjunction, ConjunctionMAPElites, CycleQD, DivTuRBO1, primitive_mcts, qd_subgoal_mcts) def cycle_trial(seed, budget): """Fit three linear specialists and audit the merged weights on fresh inputs.""" rng = np.random.default_rng([408, seed]) target = rng.normal(0., .65, size=(5, 3)) experts = [] for task in range(3): training = rng.normal(size=(12, len(target))) weights = np.zeros_like(target) labels = training @ target[:, task] + rng.normal(0., .12, len(training)) weights[:, task] = np.linalg.solve(training.T @ training + .1 * np.eye(len(target)), training.T @ labels) experts.append((weights,)) base = (np.zeros_like(target),) development = rng.normal(size=(32, len(target))) audit = rng.normal(size=(256, len(target))) def performance(checkpoint, panel): errors = panel @ (checkpoint[0] - target) return 1. / (1. + np.mean(errors**2, axis=0)) for method, order in (("CycleQD", None), ("Fixed task role", (0,))): search = CycleQD(base, experts, ((0., 1.),) * 3, bins=8, task_order=order, merge_std=.35, svd_max=2., seed=seed) stats = search.run(lambda checkpoint: performance(checkpoint, development), budget) elites = {elite[0]: elite for archive in search.archives for elite in archive} balanced = max(elites.values(), key=lambda elite: min(elite.scores["cycle_scores"])) held_out = performance(search.checkpoint(balanced), audit) aggregate = performance(search.aggregate(), audit) yield dict(task="cycle", method=method, seed=seed, evaluations=stats.evaluations, task_evaluations=3 * stats.evaluations, audit_models=2, filled_cells=[len(archive) for archive in search.archives], best_balanced_audit=held_out.min(), aggregate_audit=aggregate.min()) average = performance((np.mean([expert[0] for expert in experts], axis=0),), audit) yield dict(task="cycle", method="Weight averaging", seed=seed, evaluations=0, task_evaluations=0, audit_models=1, best_balanced_audit=average.min(), aggregate_audit=average.min()) def subset_trial(seed, budget): """Use exhaustive coverage optima as reference for overlapping inclusion rules.""" rng = np.random.default_rng([112, seed]) dimension, cap = 14, 4 sets = [frozenset(rng.choice(26, 5, replace=False)) for _ in range(dimension)] rules = {"unrestricted": BooleanConjunction(), "first": BooleanConjunction({0}, {1}), "second": BooleanConjunction({2}, {3}), "paired": BooleanConjunction({0, 2}, {1, 3})} def coverage(subset): return len(frozenset().union(*(sets[i] for i in subset))) reference = {} for size in range(cap + 1): for subset in combinations(range(dimension), size): for name, rule in rules.items(): if rule.matches(subset): key = name, size reference[key] = max(reference.get(key, 0), coverage(subset)) for method, shared in (("Shared rules", True), ("Separate rules", False)): groups = (rules,) if shared else tuple({name: rule} for name, rule in rules.items()) size, extra = divmod(budget, len(groups)) archives, evaluations = {}, 0 for i, group in enumerate(groups): limit = size + (i < extra) search = ConjunctionMAPElites(dimension, group, max_items=cap, crossover_probability=.3, seed=np.random.SeedSequence([seed, i])) stats = search.run(coverage, limit, proposal_limit=60 * limit) archives.update(search.archives) evaluations += stats.evaluations found = {(name, elite.features.values[0]): int(elite.fitness.values[0]) for name, archive in archives.items() for elite in archive} yield dict(task="subset", method=method, seed=seed, evaluations=evaluations, covered=len(found), possible=len(reference), exact_matches=sum(found.get(key) == value for key, value in reference.items()), fitness_fraction=float(np.mean([found.get(key, 0) / max(value, 1) for key, value in reference.items() if value > 0]))) def trust_trial(seed, budget): """Search three peaks with a common minimum portfolio separation.""" centers = np.array([[.12, .2, .48, .50, .55, .34], [.44, .9, .45, .5, .5, .42], [.92, .26, .56, .49, .5, .55]]) separation = .55 def quality(point): penalty = ((centers - point)**2).sum(axis=1) return float(np.max(np.array([1., .98, .96]) - penalty)) for method, phases in (("Sequential divTuRBO1", 1), ("Interleaved divTuRBO1", 3)): search = DivTuRBO1(((0., 1.),) * 6, population_size=3, distance=separation, phases=phases, fitness_weight=1., initial_samples=4, candidate_pool=36, seed=seed) result = search.optimise(quality, budget) yield dict(task="trust", method=method, seed=seed, evaluations=result.evaluations, mean_fitness=float(np.mean([point.fitness for point in result.solutions])), minimum_distance=result.minimum_distance, violations=result.violating_pairs, restarts=sum(result.restarts_by_slot)) rng = np.random.default_rng(seed) candidates = sorted(((quality(point), tuple(point)) for point in rng.random((budget, 6))), reverse=True) representatives = [] for score, point in candidates: if all(dist(point, elite) >= separation for _, elite in representatives): representatives.append((score, point)) if len(representatives) == 3: break distances = [dist(a, b) for i, (_, a) in enumerate(representatives) for _, b in representatives[:i]] yield dict(task="trust", method="Separated random search", seed=seed, evaluations=budget, mean_fitness=float(np.mean([score for score, _ in representatives])), minimum_distance=min(distances, default=None), violations=0, restarts=0, portfolio_size=len(representatives)) def maze_trial(seed, budget): """Plan through a gate with a toll or a second route with lower cost.""" start, goal = (0, 3), (8, 3) offsets = ((1, 0), (0, 1), (0, -1), (-1, 0)) def legal(state): for dx, dy in offsets: x, y = state[0] + dx, state[1] + dy if 0 <= x <= 8 and 0 <= y <= 6 and (x != 4 or y in (1, 5)): yield dx, dy def simulate(state, action): x, y = state[0] + action[0], state[1] + action[1] reached = (x, y) == goal reward = -.01 - .12 * (x == 4 and y == 1) + 1. * reached return (x, y), reward, reached for planner, method in ((qd_subgoal_mcts, "QD subgoals"), (primitive_mcts, "Primitive MCTS")): settings = (dict(describe=lambda state: state, macro_steps=4, probes=6, subgoals=3) if planner is qd_subgoal_mcts else {}) result = planner(start, actions=legal, simulate=simulate, budget=budget, horizon=18, seed=seed, **settings) state, gate = start, None for action in result.plan.actions: state = (state[0] + action[0], state[1] + action[1]) if state[0] == 4 and gate is None: gate = state[1] yield dict(task="maze", method=method, seed=seed, budget=budget, simulator_calls=result.simulator_calls, discovery_calls=result.low_level_calls, goal=result.plan.terminated, planned_steps=len(result.plan.actions), reward=result.plan.return_, first_gate=gate, published_subgoals=result.published_subgoals) def main(): """Run one of the comparisons and print JSON records for each seed.""" trials = {"cycle": (cycle_trial, 72, 5), "subset": (subset_trial, 180, 4), "trust": (trust_trial, 96, 9), "maze": (maze_trial, 800, 1)} parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("task", choices=trials) parser.add_argument("--budget", type=int) parser.add_argument("--seeds", type=int, nargs="+", default=[11, 23, 47]) args = parser.parse_args() trial, default, minimum = trials[args.task] budget = default if args.budget is None else args.budget if budget < minimum: parser.error(f"--budget must be at least {minimum} for this task.") for seed in args.seeds: for row in trial(seed, budget): print(json.dumps(row)) if __name__ == "__main__": main()