Changing constraints, structured niches, fidelity, and replay ============================================================= The four workflows in this guide use the base QDpy installation. The example runs them on a six-job scheduling problem, a simulated fidelity ladder, and verified integer arithmetic. :doc:`new_qd_families_benchmarks` reports the comparisons and includes the per-seed data. .. code-block:: bash python -I examples/new_qd_families.py all --seeds 11 12 13 14 15 .. _changing-score-constraints: Changing score constraints -------------------------- Use :class:`qdpy.algorithms.VariableConstraintMAPElites` when the evaluator can measure quantities that users will later constrain. For example, a schedule evaluator can record completion times for two jobs, alongside tardiness-based fitness and a descriptor for the first scheduled job. The archive keeps one feasible elite per descriptor cell. A bounded history keeps other recent valid measurements, including candidates that missed an earlier deadline or lost to a better elite. .. code-block:: python from qdpy.algorithms import VariableConstraintMAPElites from qdpy.containers import Grid archive = Grid(shape=(6,), features_domain=((0., 1.),), fitness_domain=((0., 1.),), fitness_weights=(1.,)) # schedule(order) returns scalar quality, a descriptor tuple, and a # mapping with both scores. permutation(rng) and swap(parent, rng) # return immutable tuples of job IDs. search = VariableConstraintMAPElites( archive, score_names=("completion_0", "completion_4"), constraints={"completion_0": (None, 13)}, history_size=100, propose=permutation, mutate=swap, seed=11, ) search.run(schedule, budget=100) search.set_constraints({"completion_0": (None, 9), "completion_4": (None, 9)}) print(len(archive), search.nb_evaluations) search.run(schedule, budget=40) The bounds are inclusive. Omit a name to remove its constraint and use ``None`` for an open bound. A call to ``set_constraints()`` filters cached measurements and repopulates the same grid, with zero evaluator calls. ``history_size=0`` only reuses the current elites. Each cache entry assumes a stable measurement, so this workflow applies when the requirements change and the measured problem stays fixed. A quantity introduced outside the declared score schema requires a new measured run. This workflow uses the changing requirements studied in QDA-VC. `Shyne2026 `__ .. _magnitude-go-explore: Magnitude Go-Explore -------------------- Use a :class:`qdpy.algorithms.MagnitudeArchive` when descriptors are objects such as permutations and you can define a dissimilarity between them. The archive places a descriptor according to the ordered indices of its closest reference landmarks. Ties follow the landmark order. Use supplied landmarks or fit them from a reference panel with magnitude-increasing swaps. .. code-block:: python from qdpy.algorithms import MagnitudeArchive, MagnitudeGoExplore # The reference panel contains distinct or repeated permutations. # kendall(a, b) counts the job pairs that switch order. archive = MagnitudeArchive.from_reference( reference, kendall, count=6, rank=2, capacity=12, ) search = MagnitudeGoExplore( archive, propose=permutation, mutate=swap, seed=11, ) search.optimise(lambda order: (schedule(order)[0], order), budget=128) for cell, elite in archive.cells.items(): print(cell, elite.fitness, archive.weights[cell]) The archive keeps a pairwise distance matrix for the retained elites. The magnitude solve uses the kernel :math:`\exp(-tD)`, where the automatic scale gives a strictly diagonally dominant matrix with nonnegative weights. Use a symmetric finite dissimilarity that is positive between distinct descriptors and zero for identical ones. When the archive reaches its capacity, a new niche competes with the existing elites by magnitude weight, with fitness breaking ties. Memory grows quadratically with capacity and the dense solve grows cubically, so start with a modest archive. The bounded direct-evaluation variant uses the paper's landmark signatures and diversity weighting. Each visit makes one offspring through the supplied mutation. The original paper also models local fitness and ranks a pool of unevaluated offspring before making a visit. Run ``selection="uniform"`` to control for parent weighting with the same archive and mutation. `Huntsman2023 `__ .. _asynchronous-multifidelity-search: Asynchronous multifidelity search --------------------------------- :class:`qdpy.algorithms.AsyncQDHalving` allocates trials to a ladder of increasing fidelity costs. For a ladder of ``(1, 3, 9)`` and ``eta=3``, one complete allocation buys nine trials at cost 1, three at cost 3, and one at cost 9. Each group of three completed trials gives the next rung a promotion. The scheduler chooses among eligible niches by the number of promotions each has received at that rung. It then selects the best available candidate within that niche. Remaining resources can buy direct highest-fidelity trials. If too many lower-rung trials fail, the scheduler fills unserved slots with new proposals. By default about a quarter of promotion slots at each rung are held until all upstream results arrive, with at least one slot open for early results. This gives slower niches a chance to compete. Set ``late_fraction=0`` to release every promotion as soon as enough upstream trials finish. .. code-block:: python from concurrent.futures import ThreadPoolExecutor from qdpy.algorithms import AsyncQDHalving from qdpy.containers import Grid archive = Grid(shape=(8,), features_domain=((0., 1.),), fitness_domain=((0., 1.),), fitness_weights=(1.,)) search = AsyncQDHalving(archive, 2, (1, 3, 9), budget=216, seed=11) # evaluate(genome, fidelity) returns (scalar fitness, descriptor tuple). with ThreadPoolExecutor(max_workers=4) as pool: search.run(evaluate, executor=pool, max_pending=4) print(search.quotas, search.spent, archive.qd_score()) With an application scheduler, call ``ask()`` on the coordinator and send the ticket's genome and fidelity to a worker. Keep the original ticket on the coordinator and pass it to ``tell(request, result)`` when the worker returns. If ``ask()`` returns ``None`` and ``pending`` contains tickets, wait for a completion. A failed evaluation costs the priced fidelity and is reported as ``None``. The archive admits only full-fidelity measurements, using their actual measured descriptors. A low-fidelity descriptor controls promotion and can differ from that at full fidelity. Completion order can change eligible candidates, even at the same seed. Every call is priced from scratch. Incremental training checkpoints are the evaluator's responsibility. QDpy's scheduler uses one anytime ladder and follows asynchronous successive halving for dispatch and qdHB for the QD workflow. `Schmucker2021 `__ and `Schneider2022 `__ .. _verified-strategy-replay: Verified strategy replay ------------------------ :class:`qdpy.algorithms.EliteReplay` builds a fixed repertoire for an external trainer. Declare the target strategies for each problem. Pass a frozen model or a deterministic generator to ``propose``, and use an independent verifier to check correctness and label the achieved strategy. The shortest verified solution per problem and achieved cell wins. Choose the length function used by the trainer, such as the number of response tokens. .. code-block:: python import numpy as np from qdpy.algorithms import EliteReplay, EliteReplayDataset search = EliteReplay({"17+19": ("direct", "compensate", "split")}, seed=11) # propose(problem, target, parent, rng) returns solution text or None. # verify(problem, solution) returns its achieved strategy or None. dataset = search.run(propose, verify, budget=20) dataset.save("arithmetic-replay.jsonl") replay = EliteReplayDataset.load("arithmetic-replay.jsonl") rng = np.random.default_rng(11) batch = replay.sample(32, rng=rng) Each replay draw samples a problem uniformly among those with solutions, then a populated cell uniformly within that problem. The caller maps problem IDs to prompts and tokenizes the saved solution text. For the EliteReplay training recipe, average the negative log probability over response tokens per example, then average over the batch. Combine that loss with the trainer's GRPO loss using a replay coefficient. The implementation covers search, verification, and replay data. The external trainer owns model updates. The offline example compares targeted and independent proposals with a fixed arithmetic verifier. `Moussa2026 `__