Source code for qdpy.algorithms.faery

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Learn mutation priors for few-shot quality-diversity optimization.
# @see https://doi.org/10.1109/LRA.2022.3148438

"""Learn which initial genomes yield many successful descendants at low depth."""

from dataclasses import dataclass
from math import isfinite

import numpy as np

from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from .constrained import _validate_grid
from .evolvability_es import _pareto_utilities
from .modern import _positive_int

__all__ = ["FAERY", "FAERYSuccess", "FAERYTaskResult", "FAERYGeneration", "FAERYResult"]


## @brief A successful evaluated genome and its lineage in an adaptation run.
[docs] @dataclass(frozen=True) class FAERYSuccess: """Record a successful genome, its prior index, and its mutation depth.""" genome: tuple root: int depth: int
## @brief The result of adapting one prior population to one task.
[docs] @dataclass(frozen=True) class FAERYTaskResult: """Store a native archive, distinct successes, and measured evaluation costs. first_success is the one-based evaluation number, or None if no evaluated genome satisfied the task's success predicate. """ archive: Grid successes: tuple[FAERYSuccess, ...] evaluations: int first_success: int | None
## @brief Lineage credit used in one outer FAERY selection.
[docs] @dataclass(frozen=True) class FAERYGeneration: """Report counts and mean depths in candidate order, with selected indices. Candidates with zero successes have a mean_depths entry of None. """ candidates: tuple success_counts: tuple[int, ...] mean_depths: tuple[float | None, ...] selected: tuple[int, ...] evaluations: int
## @brief A learned prior and its training history.
[docs] @dataclass(frozen=True) class FAERYResult: """Hold selected genomes and total training evaluations across generations.""" prior: tuple history: tuple[FAERYGeneration, ...] evaluations: int
def _prior_population(prior): genomes = tuple(tuple(genome) for genome in prior) if not genomes or any(not genome for genome in genomes) or len(set(genomes)) != len(genomes): raise ValueError("Provide distinct, nonempty, immutable prior genomes.") return genomes ## @brief Fit an initialization prior using successful descendants and mutation depth.
[docs] class FAERY: """Meta-evolve a prior using mutation-only MAP-Elites as the inner search. During training, the current prior and its mutated candidates are measured together on each task. A successful genome credits its original root, including a successful root at depth zero. Track successes by genome within each task, using their first successful evaluations. Pareto selection favors more successes and lower mean mutation depth. :param grid_factory: Callable taking a task and returning a fresh, empty best-only Grid or CVTGrid. :param mutate: Callable taking (genome_tuple, rng) and returning a new immutable genome. :param task_budget: Maximum evaluator calls for one inner task, including initial genomes. :param offspring: Number of outer mutation proposals per generation. :param tasks_per_generation: Number of tasks sampled without replacement. Defaults to all tasks. :param success_limit: Optional stop after this many distinct successes. All initial genomes are measured. :param seed: Seed for outer sampling, mutation, and tie-breaking. """ def __init__(self, grid_factory, mutate, *, task_budget, offspring=4, tasks_per_generation=None, success_limit=None, seed=0): if not callable(grid_factory) or not callable(mutate): raise TypeError("Provide a grid factory and a mutation callback.") self._grid_factory, self._mutate = grid_factory, mutate self.task_budget = _positive_int(task_budget, "task_budget") self.offspring = _positive_int(offspring, "offspring") self.tasks_per_generation = (None if tasks_per_generation is None else _positive_int(tasks_per_generation, "tasks_per_generation")) self.success_limit = None if success_limit is None else _positive_int(success_limit, "success_limit") self.seed = seed ## @brief Evaluate one prior on a task without modifying it.
[docs] def adapt(self, prior, task, evaluate, budget=None, *, seed=0): """Run mutation-only MAP-Elites under a separate evaluation budget. evaluate(task, genome) returns (scalar fitness, descriptors, success). The success flag is independent of archive admission. """ prior = _prior_population(prior) budget = self.task_budget if budget is None else _positive_int(budget, "budget") if budget < len(prior) or not callable(evaluate): raise ValueError("Provide an evaluator and a budget that covers all prior genomes.") archive = self._grid_factory(task) _validate_grid(archive) weights = tuple(archive.fitness_weights or ()) if (archive.parents or len(weights) != 1 or not isfinite(weights[0]) or weights[0] == 0 or archive.fitness_score_names or archive.features_score_names): raise ValueError("Use a parentless archive with a finite signed scalar fitness weight and native scores.") rng = np.random.default_rng(seed) successes = {} first_success = None for attempt in range(budget): if attempt < len(prior): root, depth, genome = attempt, 0, prior[attempt] else: if self.success_limit is not None and len(successes) >= self.success_limit: break if archive: parent = archive[rng.integers(len(archive))] root, depth = parent.scores["faery_root"], parent.scores["faery_depth"] + 1 else: root = int(rng.integers(len(prior))) parent, depth = prior[root], 1 genome = tuple(self._mutate(tuple(parent), rng)) if not genome: raise ValueError("Mutation must return a nonempty genome.") hash(genome) quality, features, solved = evaluate(task, genome) quality, features = float(quality), tuple(map(float, features)) if (not isfinite(quality) or len(features) != len(archive.features_domain) or not all(map(isfinite, features)) or not isinstance(solved, (bool, np.bool_))): raise ValueError("Return finite fitness and descriptors, and a boolean success flag.") if solved: if first_success is None: first_success = attempt + 1 successes.setdefault(genome, FAERYSuccess(genome, root, depth)) if (archive.in_bounds((quality,), archive.fitness_domain) and archive.in_bounds(features, archive.features_domain)): cell = archive.index_grid(features) if archive.free or archive.solutions[cell]: individual = Individual(list(genome), fitness=Fitness((quality,), weights=weights), features=Features(features)) individual.scores["faery_root"] = root individual.scores["faery_depth"] = depth archive.add(individual) else: return FAERYTaskResult(archive, tuple(successes.values()), budget, first_success) return FAERYTaskResult(archive, tuple(successes.values()), attempt, first_success)
## @brief Learn a fixed-size population from training tasks.
[docs] def fit(self, initial, tasks, evaluate, *, generations): """Reassess the combined parent and offspring candidates on shared task panels.""" prior = _prior_population(initial) tasks = tuple(tasks) generations = _positive_int(generations, "generations") sample_size = len(tasks) if self.tasks_per_generation is None else self.tasks_per_generation if not 0 < sample_size <= len(tasks) or not callable(evaluate): raise ValueError("Provide enough training tasks and an evaluator.") if len(prior) + self.offspring > self.task_budget: raise ValueError("task_budget must cover the prior and all outer offspring.") size = len(prior) rng = np.random.default_rng(self.seed) history = [] for _ in range(generations): pool = dict.fromkeys(prior) for _ in range(self.offspring): child = tuple(self._mutate(prior[rng.integers(size)], rng)) if not child: raise ValueError("Mutation must return a nonempty genome.") pool.setdefault(child) genomes = tuple(pool) count = [0] * len(genomes) depth_sum = [0] * len(genomes) calls = 0 for task_index in rng.choice(len(tasks), size=sample_size, replace=False): result = self.adapt(genomes, tasks[task_index], evaluate, seed=int(rng.integers(2**32))) calls += result.evaluations for success in result.successes: count[success.root] += 1 depth_sum[success.root] += success.depth depths = tuple(total / number if number else None for total, number in zip(depth_sum, count)) speed = np.asarray([-depth if depth is not None else -self.task_budget for depth in depths]) utility = _pareto_utilities(np.asarray(count), speed) selected = tuple(map(int, np.lexsort((rng.random(len(genomes)), -utility))[:size])) prior = tuple(genomes[i] for i in selected) history.append(FAERYGeneration(genomes, tuple(count), depths, selected, calls)) return FAERYResult(prior, tuple(history), sum(row.evaluations for row in history))