Reference niches, repertoire selection, and model-based skills¶
Use reference examples to define a repertoire, keep a fixed-size subset for deployment, or change which descriptors guide search. The optional RL extra adds a skill-conditioned actor trained with imagined rollouts.
Define niches with a dataset of measures¶
Quality Diversity with Datasets of Measures (QDDM) uses examples of the desired behaviours as archive targets. Flatten raw examples or embed them once, then apply the same transformation to each candidate. The closest reference row in Euclidean distance determines the niche. Target IDs follow the input order.
from qdpy.algorithms import IsoLineMAPElites, audit_reference_cvt, reference_cvt
from qdpy.simple import run
targets = [[0., 1.], [0.5, 0.5], [1., 0.]]
archive = reference_cvt(targets)
def evaluate(genome):
x, = genome
return (1. - 0.4 * (x - 0.7)**2,), (x, 1. - x)
search = IsoLineMAPElites(archive, budget=48, dimension=1, iso_sigma=0.12,
optimisation_task="maximisation")
run(search, evaluate, seed=11)
report = audit_reference_cvt(archive, distance_limit=0.15)
print(report.coverage, report.matched_coverage, report.mean_distance)
Ordinary coverage counts niches with an elite. Matched coverage
counts only elites close enough to their reference, divided by the
number of targets. Check both when the data contain isolated examples.
The default descriptor domain is unbounded. For
qdpy.algorithms.DiscountModelSearch, supply finite,
positive-width descriptor bounds and install the optional DMS extra.
The synthetic rendering example places soft disks against a dataset of 8-by-8 reference images. It uses the same targets with Iso+LineDD and DMS. See Tjanaka et al., ICLR 2026, section 6.2.
Select a fixed-size repertoire¶
qdpy.algorithms.select_dpp() chooses exactly the requested
number of measured candidates. Each step adds the candidate with
the largest increase in the quality-weighted kernel determinant.
A Gaussian similarity kernel gives less credit to an alternative
that resembles alternatives already selected. A positive ridge
allows a panel to include repeated embeddings if necessary.
from qdpy.algorithms import select_dpp
positions = {"left": (-1.,), "centre": (0.,), "near-left": (-0.95,), "right": (1.,)}
quality = {"left": 0.9, "centre": 0.6, "near-left": 1., "right": 0.8}
panel = select_dpp(positions, 2, embedding=positions.__getitem__, quality=quality.__getitem__,
bandwidth=0.6, quality_strength=1.0)
print(panel.members, panel.similarity_logdet)
Pass an archive directly to use its active fitness weights and
descriptors, including named scores. For other candidate collections
provide the embedding and quality functions. Scale embeddings when
their axes use different units and use a bandwidth in that scaled
space. Set quality_strength=0 for diversity-only selection.
The reported objective combines the similarity log-determinant
with log weights based on quality. Compare these scores on the
same input pool. The selector uses cached measurements and consumes
zero evaluations.
The implementation uses the incremental Cholesky update in Chen et al., NeurIPS 2018. Greedy selection gives a reproducible approximate solution for a fixed-size panel.
Rotate between descriptor spaces¶
In qdpy.algorithms.ScheduledCVTMAPElites, the active
CVT archive supplies both parents for a whole phase. The evaluator
returns all descriptor views for each candidate. At a switch,
the search re-bins outgoing elites in the incoming archive using
those cached values. The destination also retains its existing
elites from earlier phases.
from qdpy.algorithms import ScheduledCVTMAPElites, reference_cvt
archives = {
"position": reference_cvt([[0.], [0.5], [1.]]),
"shape": reference_cvt([[0., 0.], [0.5, 0.5], [1., 1.]]),
}
search = ScheduledCVTMAPElites(archives, 2, phase_evaluations=12, seed=11)
def evaluate(genome, seed):
x, y = genome
return 1. - (y - 0.5)**2, {"position": (x,), "shape": (x * y, y)}
stats = search.run(evaluate, 48)
print(stats.evaluations_by_view, stats.switches)
The mapping’s order determines the schedule. Further calls to run
continue the current phase. A switch happens before the next proposal,
so a budget that ends exactly at a phase boundary leaves the outgoing
view active until another evaluation is requested. A failed attempt
counts toward the schedule and propagates its error. Transfers use no
evaluator calls.
Use shared_feedback=True for a simultaneous feedback control with
the same active-parent schedule. Set the phase width to the full
budget for a fixed-view control. The transfer policy is inspired by
Usui, Suzuki and Arita, ALIFE 2023.
Train and export QDAC-MB¶
Install qdpy[rl] for the PyTorch implementation. QDAC-MB uses a
recurrent state-space model with categorical latents. Real replay
trains observation, reward, feature, and continuation predictions.
The actor, reward critic, successor-feature critic, and skill
multiplier learn from imagined rollouts, each with a sampled goal.
The actor differentiates through the model’s predicted rewards
and features to optimize imagined lambda returns.
A custom environment supplies a fixed-shape numeric Box observation, finite Box action bounds, and a pre-action feature callback. The callback receives the current observation, the physical action about to be applied, and the current info mapping. Return one physical feature per desired skill coordinate. Terminations end continuation. Time limits still provide the final observation and reset recurrent state at the next episode.
import gymnasium as gym
from qdpy.rl import (
PolicyConfig, QDACMB, QDACMBConfig, QDACMBPolicy, QDACMBWorldConfig, evaluate_skills,
)
def env():
return gym.make("Pendulum-v1")
def angular_velocity(observation, action, info):
return (float(observation[2]),)
config = QDACMBConfig(
world=QDACMBWorldConfig(recurrent_size=24, latent_variables=4, latent_classes=4, hidden_size=32),
batch_size=4, sequence_length=8, learning_starts=24, train_every=8,
imagination_batch_size=8, imagination_horizon=5, critic_hidden_sizes=(32,),
)
search = QDACMB(env, feature=angular_velocity, skill_bounds=((-8., 8.),), config=config,
policy=PolicyConfig((32,)), max_episode_steps=32, seed=11)
stats = search.train(96)
print(stats.env_steps, stats.replay_transitions, stats.imagined_steps)
search.policy.save("pendulum-qdac-mb.npz")
policy = QDACMBPolicy.load("pendulum-qdac-mb.npz")
result = evaluate_skills(env, policy, [(-2.,), (0.,), (2.,)], feature=angular_velocity,
episodes=2, tolerance=0.25, max_episode_steps=32, seed=202)
print(result.mean_distance, result.satisfaction_rate)
For direct use, call session = policy.new_episode() at each
environment reset. Call session.act(observation, desired_skill)
once per step and apply the returned action. Set deterministic=False
for stochastic execution and supply the session’s seed to reproduce
it. evaluate_skills creates a new session for every evaluation
episode. The NPZ artifact holds the recurrent model and actor
weights for inference.
The implementation follows Grillotti et al., ICML 2024, appendix C.2 and Hafner et al.’s DreamerV3. It uses a compact GRU encoder, scalar symlog prediction heads, a squashed Gaussian policy, and a fixed entropy coefficient for numeric observations. It uses the existing Gymnasium adapters and skill audit. The paper’s Brax training configurations are a separate reproduction target.
python examples/reference_niches.py
python examples/reference_niches.py qddm --dms
python examples/qdac_mb.py --steps 2048
See CPU pilots for reference repertoires and model-based skills for measurements and controls.