Pareto fronts, noisy elites, and policy gradients ================================================= These methods solve four different search problems. Bayesian Pareto illumination guides expensive evaluations towards per-cell trade-offs. AS-Delta keeps a preferred stack of noisy solutions per cell. CPDEA finds different decision vectors that reach similar objective values. CMA-MEGA (TD3, ES) searches over continuous-control policies with episode-level descriptors. .. _bayesian-pareto-illumination: Bayesian Pareto illumination ---------------------------- Return two objective values and one or two descriptor coordinates per evaluation. Create a crowding :class:`~qdpy.containers.ParetoGrid` with the objective directions you need. Supply the hypervolume reference in raw objective units. It must be weakly dominated by the worst corner of the declared fitness domain, so it can also serve as a reporting reference for every occupied cell. .. code-block:: python from qdpy.algorithms import BayesianParetoIllumination from qdpy.containers import ParetoGrid archive = ParetoGrid(shape=(6,), max_items_per_bin=5, fitness_domain=((0., 1.), (0., 1.)), fitness_weights=(1., -1.), truncation="crowding", features_domain=((0., 1.),)) def evaluate(genome): x, y = genome return (x, x**2), (.7*y + .3*x,) search = BayesianParetoIllumination(archive, budget=24, dimension=2, ind_domain=(0., 1.), reference=(0., 1.), initial_samples=8, candidate_pool=32, restarts=2, seed=7) search.optimise(evaluate) print(archive.qd_hypervolume(search.reference)) The acquisition is a sum over cells. In each cell, multiply the probability of falling in that cell by the expected improvement over its current Pareto hypervolume. With two independent Gaussian objective posteriors, QDpy integrates the improvement exactly over vertical strips. Independent Gaussian descriptor posteriors give rectangular cell probabilities. Predictions guide proposals and measured candidates populate the archive. Finite values outside the declared domain can train the model. The budget counts attempted true evaluations, and ``n_observations`` counts complete finite measurements. For a remote evaluator, send one proposal via ``ask_batch()`` and return one measured result with ``tell_batch()``. This is a QDpy extension of the cell-probability acquisition in `BOP-Elites by Kent et al. `_. The `EHVI paper by Daulton et al. `_ describes the improvement criterion and its batch generalization. QDpy uses a single candidate at a time and fits fixed kernels at each modelled proposal. A small pool and a few restarts are useful when testing the evaluator. Larger archives and training sets raise the cost of a proposal. .. _as-delta: AS-Delta for uncertain evaluations ---------------------------------- AS-Delta estimates performance and reproducibility from repeated observations. With ``seeded=True``, the evaluator receives an independent seed per attempt. The default reproducibility score is the negative mean of the population standard deviations of the descriptor coordinates. Higher scores indicate more consistent behavior. .. code-block:: python import numpy as np from qdpy.algorithms import ASDelta from qdpy.containers import Grid archive = Grid(shape=(5,), max_items_per_bin=2, fitness_weights=(1.,), fitness_domain=((0., 1.),), features_domain=((0., 1.),)) def evaluate(genome, seed): quality, location = genome rng = np.random.default_rng(seed) measured = np.clip(location + rng.normal(0., .02 + .12*quality), 0., 1.) return (quality,), (measured,) search = ASDelta(archive, budget=240, dimension=2, delta_f=.08, delta_r=.025, sampling_size=24, estimator=("mean", "median"), seed=7) search.optimise(evaluate, seeded=True) elites = [search.front(cell)[0] for cell in archive.solutions if search.front(cell)] print(len(elites), search.incumbent_evaluations, search.nb_evaluations) The two delta values are in raw fitness and reproducibility units. Orient the objective with the grid's fitness weight. A candidate wins if its fitness gain meets ``delta_f``, if it weakly improves both scores, or if its fitness loss is within ``delta_f`` and its reproducibility gain reaches ``delta_r``. Exact ties keep the incumbent. A displaced solution is compared with the deeper entries in the same cell. Use ``search.front(cell)`` for that preference order. The grid's ``quality_array`` reports its usual best raw fitness. A generation refreshes each incumbent before selecting parents. A changed descriptor estimate can move a solution to a new cell. Failed refreshes keep the previous estimate, and new solutions need every initial repeat. Track failures and unused final rollout capacity through the search counters. Size ``sampling_size`` to fit the grid's full depth plus one group of ``initial_samples`` rollouts. Reserve separate seeds for a held-out audit. Use a custom reproducibility reducer if the descriptor coordinates have different units or standard deviation does not capture the consistency you need. See Eq. 5 and §IV-C of `Flageat et al., Exploring the Performance-Reproducibility Trade-off in Quality-Diversity `_. .. _cpdea: CPDEA for alternate realizations of a Pareto front -------------------------------------------------- Supply bounded real decisions and the raw objective vector. CPDEA uses decision-space distance directly. It reduces the effective distance between pairs when nearby dominators indicate that either solution has poor local convergence. The breeding population uses this adjusted density. The returned archive stores nondominated designs with a separate nearest-neighbor density criterion in decision and objective space. .. code-block:: python from qdpy.algorithms import CPDEA def evaluate(genome): x, branch = genome error = min(abs(branch - .2), 4. * abs(branch - .8)) return x + error, 1. - x + error search = CPDEA(((0., 1.), (0., 1.)), (-1., -1.), population_size=16, neighbors=3, seed=7) result = search.optimise(evaluate, budget=160) print(result.evaluations, [point.genome for point in result.archive]) Use compatible units across decision coordinates because Euclidean distances and the convergence bandwidth depend on their scale. The objectives also use Euclidean distances when thinning an overfull archive. CPDEA uses one callback per offspring. The first half of the budget uses population tournaments and the second half also samples sparse archive members and their decision-space neighbors. Candidate scores should be deterministic. See `Liu et al., Handling Imbalance Between Convergence and Diversity in the Decision Space `_. .. _cma-mega-td3-es: CMA-MEGA (TD3, ES) for continuous policies ------------------------------------------ Install the RL and CMA extras with ``pip install "qdpy[rl,cma]"`` or ``uv pip install "qdpy[rl,cma]"``. The trainer takes a factory for a single Gymnasium environment with finite Box actions and fixed Box observations. Return an archive descriptor from a completed episode. The example below uses Pendulum's mean speed. Its objective is undiscounted episode return and its TD3 critic learns from the step rewards. .. code-block:: python import gymnasium as gym from qdpy.containers import Grid from qdpy.rl import CMAMEGATD3ES, ContinuousPolicy, PolicyConfig, TD3Config archive = Grid(shape=(8,), fitness_weights=(1.,), features_domain=((0., 8.),), fitness_domain=((-2048., 0.),)) def descriptor(episode): return (abs(episode.observations[1:, 2]).mean(),) search = CMAMEGATD3ES(lambda: gym.make("Pendulum-v1"), archive, descriptor=descriptor, policy=PolicyConfig((8,)), td3=TD3Config(learning_starts=32, batch_size=16, critic_hidden_sizes=(16,)), batch_size=4, es_samples=4, critic_steps=3, gradient_batch_size=16, max_episode_steps=32, seed=7) stats = search.train(640) print(stats.env_steps, stats.training_steps, stats.evaluation_steps, stats.reward_gradients) search.best_policy().save("pendulum-actor.npz") inference_actor = ContinuousPolicy.load("pendulum-actor.npz") The centre and CMA branches are evaluated in the live archive, along with a greedy TD3 policy. Normalized descriptor gradients come from ranked outcomes of mirrored perturbations. These probes train the replay critic and count as ``training_steps``. The centre, CMA branches, and greedy policy count as ``evaluation_steps``. A reward gradient requires a trained critic. The first generations can branch using descriptors alone while replay accumulates. A cut episode contributes its available transitions to replay. Its proposal is retried with a fresh episode group on the next ``train()`` call. The gradient and greedy-actor schedule follows Algorithm 1 of `Tjanaka et al., Approximating Gradients for Differentiable Quality Diversity in Reinforcement Learning `_. See :doc:`tutorial_descriptor_cma` for the black-box version and :doc:`tutorial_advanced_policy_qd` for PPO-based estimates. The :doc:`pareto_gradients_benchmarks` page includes commands, held-out metrics, and raw records for all four methods.