Offline search, learned niches, and cooperating policy parts

Choose Offline MAP-Elites when you have measurements but cannot collect more during search. Use cardinality-indexed MAP-Elites when you need subsets of several sizes, VQ-Elites when you can record behavior without defining descriptors, and CCQD when you can train continuous policies and want to reuse decision heads across representations.

Offline and cardinality search run with the base installation. Install qdpy[rl] for both policy and learned-niche examples. VQ-Elites itself needs only PyTorch in addition to the base dependencies. Settings and measured comparisons

Offline MAP-Elites

See Gradient-Augmented MAP-Elites for local gradient refinement on the same frozen model, or DynAMO for offline design batches for sampling a design batch without descriptor bins.

Prepare aligned arrays with one decision vector, measured scalar fitness, and measured descriptor per row. The constructor fits a Gaussian process with a fixed Matérn kernel. Search uses that single model to predict both fitness and descriptors. Give it an empty best-only Grid or CVTGrid with the objective direction and meaningful bounds for the predicted values.

import numpy as np

from qdpy.algorithms import OfflineMAPElites
from qdpy.containers import Grid

def measure(point, seed):
    x, y = point
    return (1. + .25 * x - (y - .7)**2,), (x, .2 * x + .8 * y)

designs = np.random.default_rng(7).random((40, 2))
log = [measure(row, 0) for row in designs]
grid = Grid(shape=(5, 5), fitness_domain=((0., 2.),),
            features_domain=((0., 1.), (0., 1.)), fitness_weights=(1.,))
search = OfflineMAPElites(grid, designs, [f[0] for f, _ in log],
                          [bc for _, bc in log], uncertainty_weight=-.5, seed=7)
predicted = search.run(180)
verified = search.verify(predicted, measure, 10, seed=27)
print(predicted.predictions, verified.evaluations, verified.cell_matches)

run() scores every proposal with the frozen model. Positive uncertainty_weight favors uncertainty in either fitness direction. Negative values favor conservative predictions. Archive fitness stores that acquisition score and scores["predicted_fitness"] stores the raw predicted mean. Choose an archive fitness range that can admit the acquisition values you expect. Proposals outside the configured fitness or descriptor domains do not enter the archive.

verify() samples at most ten elites in this example. The measured descriptor determines the cell in a separate archive. Review cell_matches, failed_evaluations, and out_of_domain before using the retained designs. The Gaussian process has cubic fit cost in the number of logged genomes. For large logs, select training rows before fitting. The uncertainty estimates depend on the kernel and the distribution of the log.

Hagg et al. describe search over frozen surrogates and exact reevaluation.

Cardinality-indexed MAP-Elites

Pass the number of available items and the largest allowable subset size. The objective receives sorted indices. The archive stores a bit vector per visited size, and the empty subset is evaluated first.

from qdpy.algorithms import CardinalityMAPElites

regions = [{0, 1}, {1, 3}, {0, 2, 4}, {3, 5}, {1, 4, 6}]

def coverage(selected):
    return len(set().union(*(regions[i] for i in selected)))

search = CardinalityMAPElites(len(regions), max_items=3,
                              fitness_domain=(0., 7.), seed=7)
stats = search.run(coverage, budget=160)
elite = search.best_at_most(2)
print(search.subset(elite), elite.fitness.values[0], stats.evaluations)

Oversize proposals consume a proposal slot and skip the objective. Set proposal_limit to bound these attempts. Repeated admissible subsets count as objective calls, so the evaluator can manage caching if appropriate. With a negative fitness_weight, best-at-most selects the smallest measured objective among the eligible bins.

Greedy selection can be efficient for monotone submodular objectives. This search can revise earlier choices and return subsets outside the greedy chain. The approximation bounds in the paper have specific assumptions on the objective and budget.

Bossek and Sudholt analyze MAP-Elites with one niche per cardinality.

VQ-Elites

Return the objective along with a fixed number of observation values. This example records a small trace of two coupled controls. The learned code ID is the descriptor, so archive is a one-dimensional QDpy Grid.

from qdpy.algorithms import VQElites

def evaluate(point):
    x, y = point
    return 1.5 - (x - .4)**2, (x, y, x * y, x - y)

search = VQElites(2, 4, cells=8, fitness_domain=(0., 2.),
                  training_period=16, training_capacity=80, seed=7)
stats = search.run(evaluate, 64)
print(stats.evaluations, stats.refits, len(search.archive))

Warm-up draws uniformly from the genome domain. Once the codebook has been trained, Iso+LineDD chooses genomes from the learned archive. Each refit trains on a rolling buffer of measured observations. QDpy reassigns the stored elites with the updated encoder and codebook, keeping the fitter elite when two move to the same code. The first refit can place any of the warm-up observations in the buffer. No extra objective evaluations are needed for these remaps. Read search.archive after each run or refit to obtain the current grid. observe(genome, fitness, observation) accepts measurements from an external evaluator or a fixed replay stream.

Code IDs can change meaning during training. To compare searches, place elites in a shared reporting grid using descriptors computed from their recorded observations. Occupancy of the learned codes alone cannot establish coverage of physical behavior. For the first refit, QDpy initializes codes by clustering encoded observations when enough distinct rows are available.

Tsakonas and Chatzilygeroudis describe visit-based learning and discrete niches.

CCQD

CCQD combines several live policy encoders with decision layers drawn from a measured archive. Each encoder has its own pair of critics and samples from the same replay buffer. Critics receive decision weights as additional inputs. Genetic mutation and a policy gradient produce new decisions. Completed episodes determine the return and descriptor under which the full policies are stored.

Run this snippet from the QDpy checkout to import the example Gymnasium environment. For your own environment, supply a factory with numeric Box observations and bounded Box actions and choose a descriptor from the recorded episode.

from examples.vq_ccqd import TwoAxisControl, action_descriptor
from qdpy.containers import Grid
from qdpy.rl import CCQD, ContinuousPolicy, PolicyConfig, TD3Config

archive = Grid(shape=(5, 5), fitness_domain=((-8., 16.),),
               features_domain=((-1., 1.), (-1., 1.)), fitness_weights=(1.,))
search = CCQD(TwoAxisControl, archive, descriptor=action_descriptor,
              policy=PolicyConfig((12,)), td3=TD3Config(batch_size=16, learning_starts=24),
              representations=2, batch_size=6, critic_steps=2, pg_steps=2,
              max_episode_steps=8, seed=7)
stats = search.train(288)
audit = search.audit(160, seed=27)
print(stats.env_steps, search.representation_counts, audit.steps, audit.archive.qd_score())
search.best_policy().save("ccqd-policy.npz")
policy = ContinuousPolicy.load("ccqd-policy.npz")

The interaction budget counts all steps, including a partial episode at the end of a call. The replay buffer keeps these transitions. A later call can retry the policy. Archive admissions happen at the end of each generation, when the initial batch has finished. The audit has its own step budget and leaves training costs unchanged. Use the exported full policy directly with policy.act(observation).

QDpy uses an MLP critic that receives the full final-layer parameter vector. Keep decision heads small when getting started, since this vector grows with the hidden width and number of actions. A slot without elites is seeded from the slot with the most elites. Previously measured policies retain the complete actor weights used during their original evaluation.

Xue et al. describe the cooperative representation and decision updates.