Model merging, subset selection, and planning ============================================= CycleQD builds a repertoire from pretrained specialists. Boolean conjunctions let several subset-selection problems share objective evaluations. divTuRBO1 searches for a small, separated set of costly designs. QD-guided subgoal MCTS discovers action sequences inside a simulator during planning. All four methods use the base install. .. _cycle-qd: CycleQD for specialist checkpoints ---------------------------------- Give CycleQD a base model and compatible experts. Their tensors must refer to the same parameters in the same order. Each archive optimizes one task and uses the other task scores as descriptors. The active archive sets the parents for a new candidate. The measured score vector updates all archives. .. code-block:: python import numpy as np from qdpy.algorithms import CycleQD base = (np.zeros((2, 2)),) expert_a = (np.diag([.8, .15]),) expert_b = (np.diag([.15, .8]),) def evaluate(checkpoint): a, b = checkpoint[0].diagonal() return 1. / (1. + (a - 1.)**2), 1. / (1. + (b - 1.)**2) search = CycleQD(base, [expert_a, expert_b], ((0., 1.),) * 2, bins=8, seed=11) stats = search.run(evaluate, 40) checkpoint = search.checkpoint(search.archives[0].best) aggregate = search.aggregate() print(stats.breeding_by_task, evaluate(checkpoint), evaluate(aggregate)) Every evaluation includes a score for every task. The expert evaluations count toward the budget. The search prefers parents with high rescaled scores across tasks. Crossover combines the aligned task deltas relative to the base model. Mutation rescales the singular components of matrix deltas and passes through rank-one and scalar deltas. For tensors with more than two axes, the first axis becomes the row axis and the trailing axes form columns. Use ``checkpoint(elite)`` to retrieve independent arrays. Use ``aggregate()`` to form the paper's weighted merge of the highest scoring specialist from each archive. Evaluate that aggregate on its own because its weights are a new candidate. The examples also select an existing elite using its weakest development score and audit that elite on held-out inputs. Each archive has one axis per inactive task, so use fewer bins as task count grows. See §3 of `Kuroki et al., Agent Skill Acquisition for Large Language Models via CycleQD `_. .. _boolean-conjunction-map-elites: Boolean-conjunction MAP-Elites ------------------------------ A conjunction names the items a subset must include and the items it must exclude. The archive for each rule keeps the highest-scoring measured subset at each exact cardinality. Callers can add an empty conjunction to track the unrestricted problem alongside the rules. Overlapping rules may share one measurement. .. code-block:: python from qdpy.algorithms import BooleanConjunction, ConjunctionMAPElites coverage_sets = ({0, 1, 2}, {1, 3}, {3, 4}, {0, 4, 5}) rules = { "unrestricted": BooleanConjunction(), "use zero": BooleanConjunction(required={0}), "zero without two": BooleanConjunction(required={0}, excluded={2}), } def coverage(subset): return len(set().union(*(coverage_sets[i] for i in subset))) search = ConjunctionMAPElites(4, rules, max_items=2, seed=11) stats = search.run(coverage, 50) for name, archive in search.archives.items(): print(name, archive.best.fitness.values[0]) print(stats.evaluations, stats.archive_updates) The evaluator receives a sorted tuple of selected indices. Over-limit or unmatched subsets consume proposal slots. The default mutation flips each bit with probability equal to the inverse item count. Set ``crossover_probability`` to add uniform crossover before mutation. Check ``stats.evaluations`` for the number of objective calls. Rule cells can be absent because they are infeasible at that cardinality or because the search has yet to find a matching subset. QDpy uses separate cardinality grids and routes each valid measurement to all matching grids. See `Schmidbauer et al., Guiding Quality Diversity on Monotone Submodular Functions `_. .. _divturbo1: Separated designs with divTuRBO1 -------------------------------- Use divTuRBO1 when the evaluator returns a scalar and the portfolio has a minimum pairwise distance in decision coordinates. Each slot gets its own local Gaussian process. Candidate generation happens in an adaptive trust region, and the best measured designs are selected subject to the shared distance threshold. .. code-block:: python from qdpy.algorithms import DivTuRBO1 def loss(genome): x, y = genome return min((x - .2)**2 + (y - .2)**2, .05 + (x - .8)**2 + (y - .8)**2) search = DivTuRBO1(((0., 1.),) * 2, population_size=2, distance=.5, phases=2, initial_samples=3, seed=11) result = search.optimise(loss, 50) print(result.solutions, result.minimum_distance, result.violating_pairs) The default schedule runs each slot to completion in order. With ``phases`` greater than one, each slot shares a candidate at the end of its block and receives the current representatives of the other slots. The local GP uses normalized coordinates and a fixed Matérn kernel. Each step draws a correlated Thompson sample over a perturbed candidate pool. Region expansion, contraction, and restart depend on measured feedback. Euclidean separation uses the original coordinate units. Scale dimensions before search if they have incomparable units. The procedure can fall back to the farthest measured point when its observations contain no feasible point. Use ``minimum_distance`` and ``violating_pairs`` to check the delivered portfolio. Both the initial data and every restart count against the same evaluation cap. See `Perera et al., Trust Region-Based Bayesian Optimisation to Discover Diverse Solutions `_. .. _qd-subgoal-mcts: Online subgoals for Monte Carlo tree search ------------------------------------------- Supply a deterministic simulator, a callback yielding available actions for a state, and a numeric descriptor of the state. Use immutable snapshots so stored transitions can be reused. The low-level tree samples short paths using discounted descriptor distance from its local root. After enough probes it keeps endpoints that offer task reward and local novelty. Those paths become macro-actions in the higher-level tree, which uses task returns. .. code-block:: python from qdpy.algorithms import qd_subgoal_mcts def simulate(state, action): successor = state + action done = successor >= 5 return successor, (1. if successor == 5 else -.01), done result = qd_subgoal_mcts( 0, actions=lambda state: (1, 2), simulate=simulate, describe=lambda state: (state,), budget=50, horizon=6, macro_steps=2, probes=3, subgoals=2, seed=11, ) print(result.plan.actions, result.plan.return_, result.simulator_calls) ``budget`` counts actual simulator transitions across both levels and continuation rollouts. The planner can spend fewer calls when its search tree is exhausted. The result contains the best complete observed path by discounted return, or a measured prefix if the budget was too short to complete one. Check ``plan.terminated`` and ``plan.final_state`` before interpreting the outcome. ``primitive_mcts`` uses the same simulator interface, discount, and horizon for a primitive-action comparison. See `Jeurissen et al., Automatic Goal Discovery in Subgoal Monte Carlo Tree Search `_. The :doc:`cyclic_subset_planning_benchmarks` page includes controls, metrics, and reproduction commands.