Archive repair, ensembles, and policy reuse¶
The first three examples run with the base package. Install
qdpy[rl] for MASQD and policy diffusion. The
Archive repair, ensembles, and policy reuse benchmarks page records the CPU comparisons and
links to individual runs.
ARIA¶
An elite can land in several cells across stochastic evaluations.
ARIA starts with the best elite in each occupied cell and uses
Gaussian evolution strategies to make its behavior more reproducible.
It ranks perturbations that hit the target by fitness. Among misses,
it prefers those closest to the cell center. Completion starts with
a neighboring cell’s refined vector and targets an empty cell. ARIA
uses orthogonal neighbors in a regular grid and Delaunay adjacency
between CVT centroids, computed in their affine span.
Use a fixed Grid or CVTGrid, real parameter vectors of the same length, and a scalar fitness objective. The evaluator takes an individual and an independent rollout seed. It returns fitness and descriptors in the archive’s physical units.
import numpy as np
from qdpy.algorithms import ARIA, reevaluate_archive
from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
source = Grid(shape=(5,), features_domain=((0., 1.),),
fitness_domain=((0., 2.),), fitness_weights=(1.,))
source.add(Individual([.5], fitness=Fitness((1.,), weights=(1.,)),
features=Features((.5,))))
def evaluate(individual, seed):
rng = np.random.default_rng(seed)
position = individual[0]
return (1.,), (position + rng.normal(0., .04),)
result = ARIA(source, steps=4, population_size=10, samples=8,
ind_domain=(0., 1.), seed=7).run(evaluate, budget=240)
audit = reevaluate_archive(result.archive, evaluate, samples=32,
seed=500, estimator="mean")
print(result.rollouts, result.successful_targets, audit.corrected_coverage)
Each target uses steps * population_size + samples rollout attempts,
including failures. The last samples estimate the mean fitness and
descriptor of the final ES center. A center enters the returned archive
when that estimate maps to its intended cell. ARIA remembers attempted
centers for completion even when their estimate misses. Original elites
remain in cells the budget leaves untouched. Audit the resulting
archive separately and report the number of audit rollouts alongside
search cost.
The method follows Algorithm 2 and the two phases of the
ARIA paper.
See the runnable pilot with python examples/archive_reuse.py aria.
QDO-ES¶
Use QDO-ES to combine classifiers whose predictions you already have.
Pass probabilities from the same validation rows and class order for
every model. An integer repetition vector encodes the relative
ensemble weights. Its active models determine two descriptors, the
mean correlation of their per-row losses and their mean pairwise
Gower configuration distance. A constant error vector contributes
zero to its pairwise correlations. Missing configuration keys are
skipped pairwise and a singleton has coordinates (0., 0.).
import numpy as np
from qdpy.algorithms import QDOES
validation = np.array([
[[.9, .1], [.2, .8], [.7, .3]],
[[.6, .4], [.1, .9], [.8, .2]],
[[.8, .2], [.4, .6], [.9, .1]],
])
labels = [0, 1, 0]
configurations = [{"family": "linear"}, {"family": "tree"},
{"family": "neural"}]
search = QDOES(validation, labels, configurations=configurations, seed=7)
result = search.fit(60)
test = np.array([[[.5, .5]], [[.3, .7]], [[.2, .8]]])
print(result.weights, result.predict_proba(test))
The sliding archive periodically remaps descriptor bins. The algorithm
initializes with singleton ensembles and adapts the probability of
random parent selection, crossover, and mutation after crossover
using recent validation losses. The default objective is log loss.
A custom loss must be finite and nonnegative. Work on a fixed pool of
trained classifiers and compare fit(budget, mode="greedy") and
fit(budget, mode="quality") at the same number of loss calls. Evaluate
each result on untouched test predictions. Use the same model and
class order even when the number of test rows differs.
The Q(D)O-ES paper
gives additional initialization, pool preprocessing, and parent selection
options. The runnable pilot uses the built-in modes with
python examples/archive_reuse.py ensemble.
Surprise Search with Local Competition¶
Surprise measures how far a descriptor falls from the behaviors forecast from the last two population snapshots. SS-LC combines that distance with the number of nearby candidates it outperforms. Steady-state NSGA-II selects parents and removes one candidate after each successful child evaluation. The grid records observed elites for plotting. Parent selection reads the breeding population.
from qdpy.algorithms import SurpriseSearchLC
from qdpy.containers import Grid
archive = Grid(shape=(8, 8), features_domain=((0., 1.),) * 2,
fitness_domain=((0., 1.),), fitness_weights=(1.,))
def evaluate(candidate, seed):
x, y = candidate
return (1. - ((x - .5)**2 + (y - .5)**2),), (x, y)
result = SurpriseSearchLC(archive, 2, population_size=20,
clusters=5, seed=7).run(evaluate, budget=160)
print(result.forecasts, archive.filled_bins)
Use descriptor coordinates on comparable scales because both
objectives use Euclidean neighborhoods. This adapter uses bounded
real-vector crossover and Gaussian mutation. The paper uses a
maze-navigation controller representation. The runnable example
compares SS-LC with QDpy’s native novelty archive search at the same
evaluation cap. See the Surprise-based Quality Diversity paper and run
python examples/archive_reuse.py surprise.
See Combine novelty and surprise for variants that use both novelty and surprise with local competition.
MASQD¶
MASQD searches for teams of cooperating continuous-action policies.
Expose a joint Gymnasium environment with the agent axis first in
both Boxes. For example, two agents with three observation coordinates
and one action coordinate each use shapes (2, 3) and (2, 1).
Each agent acts on its own observation through a shared encoder and
a role-specific head. Return a single, nonnegative team reward per
step and define a team descriptor from a complete episode.
import numpy as np
from qdpy.containers import Grid
from qdpy.rl import MASQD, PolicyConfig, TD3Config
from examples.team_policy_reuse import CooperativeBox
archive = Grid(shape=(7, 7), features_domain=((-1., 1.),) * 2,
fitness_domain=((0., 8.),), fitness_weights=(1.,))
trainer = MASQD(
CooperativeBox, archive,
descriptor=lambda episode: np.asarray(episode.actions).mean(axis=0).ravel(),
policy=PolicyConfig((8,)), population_size=8,
td3=TD3Config(batch_size=16, learning_starts=16),
gradient_steps=2, critic_steps=4, seed=7,
)
stats = trainer.train(128)
print(stats.env_steps, stats.pg_offspring, archive.filled_bins)
policy = trainer.best_policy()
CEM periodically reanchors the Gaussian search distribution on an
archived team. After warm-up, the learner refines half of each
population toward the current target using descriptor-conditioned
twin critics, with separate TD3 heads per agent. All complete
candidates contribute to CEM selection. Replay remains synchronized
by joint transition and each role samples its own view. For refined
teams, relabelled achieved targets and original desired targets
provide examples with different reward similarities. A persistent
TD3 actor supplies delayed targets and is separate from the
archived teams. Set gradient_steps=0 for the CEM-only control.
A cut episode spends interactions and cannot enter the archive or
replay. A later training call retries that queued team from a fresh
reset. Use policy.save(path) and TeamPolicy.load(path) for
deployment without the simulator or learner. Agents with different
tensor extents need a wrapper that pads their observation and action
coordinates into a common Box and translates the resulting action.
See the MASQD paper and run
python examples/team_policy_reuse.py team for a two-agent
comparison with Team CEM and Mix-ME.
Policy diffusion¶
Policy diffusion takes a homogeneous archive of deterministic
continuous policies and learns to generate their weights from a
desired descriptor. QDpy trains a dense variational autoencoder on
standardized flat weights, then fits a descriptor-conditioned
denoiser on its frozen latent codes. Train with measured descriptors.
Use a common PolicyConfig, Box layout, and observation preprocessing
for every source and generated actor.
import gymnasium as gym
import numpy as np
from qdpy.rl import PolicyConfig, PolicyDiffusion, PolicyDiffusionConfig
obs = gym.spaces.Box(-1., 1., shape=(1,), dtype=np.float32)
act = gym.spaces.Box(-1., 1., shape=(1,), dtype=np.float32)
goals = np.linspace(-.8, .8, 17)
weights = np.column_stack([np.zeros_like(goals), np.arctanh(goals)])
model = PolicyDiffusion(
obs, act, ((-1., 1.),), policy=PolicyConfig(()),
config=PolicyDiffusionConfig(latent_size=2, diffusion_steps=24),
seed=7,
)
model.fit(weights, goals[:, None], vae_epochs=10, diffusion_epochs=20)
actor = model.sample_policy((.35,), seed=13)
print(actor.act(np.zeros(1, dtype=np.float32)))
Use fit_archive(grid) when a native Grid already holds the genomes
and measured descriptors. Save the generator with model.save(path)
and load it with PolicyDiffusion.load(path). Draw a policy once per
rollout. Change the seed to sample alternatives at the same goal.
Evaluate generated policies in the environment before use. Compare
descriptor error, achieved coverage, return, and artifact size with
the original archive or a nearest-elite lookup.
The policy diffusion paper
uses layer-aware encoders, a graph hypernetwork decoder, and optional
observation normalization or text conditioning. This fixed-layout
implementation uses dense models and numerical descriptors. Run the
small audit with
python examples/team_policy_reuse.py diffusion --output policy-diffusion.npz.