Guide search with task feedback and local adaptation¶
A repertoire can earn its space by helping a task solver, by carrying models that solve different examples, or by giving a planner several effective ways to act. The examples in this guide measure those properties on held-out inputs where the method permits an audit.
Use downstream feedback with RUDA¶
qdpy.algorithms.ruda_search() learns descriptors from raw
observations. At intervals, a downstream solver chooses behaviors
from a snapshot of the live repertoire. QDpy records the observations
of the behaviors the solver used in a bounded FIFO buffer. Descriptors
near the useful observations get larger outgoing distances and can
pack more densely into the repertoire. [Grillotti2022]
import numpy as np
from qdpy.algorithms import ruda_search
def evaluate(genome):
x, y = genome
return 1. - (x - .7)**2, (x, y, .2 * np.sin(6 * x))
def solve_task(archive, rng):
target = (.75, .7)
return (min(range(len(archive)), key=lambda i: np.linalg.norm(
np.subtract(archive[i].observation[:2], target))),)
result = ruda_search(
evaluate, solve_task, dimension=2, budget=144, capacity=24,
task_period=24, fit_period=24, seed=11,
)
print(result.evaluations, result.solver_calls, len(result.archive))
The solver returns indices into the snapshot. It can run a planner, minimize distance to a goal, or select a chain of primitives. Measure its work inside the callback when task execution has a separate cost. The runner counts QD evaluations and solver invocations separately.
The base implementation uses PCA. Pass encoder_factory to supply
a fresh model with fit(X) and transform(X), or set
fit_period=None to use the first observation coordinates. On a refit,
the archive and the useful buffer are re-encoded from raw observations.
A spacing-based eviction gives the variant a hard repertoire capacity.
The paired control sets guidance=False and keeps the same encoder
and solver call schedule.
Preserve complementary checkpoints with M2N2¶
qdpy.algorithms.m2n2() accepts checkpoints with the same tensor
shapes and parameter order. Score each model on the same panel and
return one number in [0, 1] for every example. Resource sharing
assigns less credit to successes shared by many models. The second
parent is sampled for weighted gains on the first parent’s weaker
examples. The eligible split-point and mixing-ratio ranges expand
during search. QDpy applies spherical interpolation with complementary
ratios on the two sides of the split. [Abrantes2025]
from qdpy.algorithms import m2n2
result = m2n2(
aligned_checkpoints, score_fixed_examples, budget=100,
population_size=10, competition="continuous", seed=11,
)
best_checkpoint = result.best.checkpoint
print(result.best.quality, result.replacements)
Use competition="binary" for a pass/fail panel. Continuous
competition assigns an example capacity equal to the best score in
the candidate pool. A common competition weight is applied to both
the child and incumbents before replacement. The result includes the
final population and the highest raw-scoring checkpoint seen during
the run. Measure either on examples reserved from search. Set
competition="mean", attraction=False to keep the merge operator
and turn off both competition and attraction. CycleQD can serve as
a second control when the panel has a known grouping into tasks.
Evolve portfolios of progressively unpruned planners¶
qdpy.algorithms.portfolio_mcts() accepts scripts that propose
legal actions with scores in [0, 1]. It sorts actions by the
strongest weighted score from any proposing script. A node starts
with the highest-priority fraction available to tree selection.
It opens additional actions at exponentially spaced visit counts.
The planner uses UCB with decaying script bias and samples rollouts
from the scripts. [PerezLiebana2021]
from qdpy.algorithms import portfolio_map_elites, portfolio_mcts
result = portfolio_mcts(
start, scripts=(collect, build, survey), weights=(.2, .9, .4),
simulate=transition, budget=64, horizon=8, seed=11,
)
print(result.plan.actions, result.simulator_calls)
repertoire = portfolio_map_elites(
archive, scenarios, scripts=(collect, build, survey),
simulate=transition, summarize=score_plans,
budget=80, plan_budget=64, horizon=8, seed=11,
)
Use a deterministic transition callable that returns
(successor, reward, terminated). The returned plan is the best
path measured under the transition cap. Cached tree edges do not
charge additional simulator calls. The outer runner uses a common
scenario and reset-seed panel. Its summarizer receives the plans and
returns ((fitness,), descriptors). It measures one-hot script
weights first, followed by random seeds and single-coordinate mutations
of archived weights. QDpy’s variant uses budgeted simulator plans
and begins with a restricted action set from the first visit.
Evolve controllers with rollout-local Hebbian learning¶
With HebbianEvaluator, the genome has five coefficients per neuron
and the policy learns its synapses during a rollout. Each weight update
uses the pre- and post-synaptic activations and the coefficients of the
two corresponding neurons. In the QDpy variant, the resulting weights
are clipped at a configurable bound. The evaluator uses NumPy.
[Ferigo2024] [Nielsen2026]
from qdpy.algorithms import HebbianEvaluator, hebbian_map_elites
evaluator = HebbianEvaluator((observation_width, 8, action_width), evaluate_policy)
run = hebbian_map_elites(archive, evaluator, budget=240, seed=11)
policy = evaluator.policy(run.archive.best)
controller = policy.start(seed=101)
action = controller.act(observation)
Start a fresh session for each episode. Call start(seed=..., plastic=False)
with the same seed to hold that session’s synapses at their initial values.
The controller returns a normalized tanh action. Scale it to the
environment’s physical bounds or apply a discrete action decoder.
For CMA-ME and CMA-MAE, construct the existing optimizer with
dimension=evaluator.dimension and coefficient bounds (-1., 1.),
then pass the callable evaluator to the usual runner.
Pretrain species with Speciated Skill Discovery¶
qdpy.rl.SSD gives each species a skill-conditioned SAC actor and
separate critics and replay. Species share a contrastive model that
predicts the joint species and skill label from successor states.
The intrinsic reward combines a contrastive likelihood bonus with
distances to nearby replay particles in the learned state embedding.
The published method is unsupervised. QDpy uses discrete skills on
fixed-shape Gymnasium Box observations and actions. [Wickman2025]
from qdpy.rl import SSD, SSDConfig, SSDPolicy
search = SSD(
make_environment, config=SSDConfig(species=2, skills=4),
max_episode_steps=60, seed=11,
)
print(search.train(12_000))
audit = search.evaluate(episodes=5, descriptor=describe_episode, seed=101)
search.policy(0).save("species-0.npz")
actor = SSDPolicy.load("species-0.npz")
Skills stay fixed within each episode. Every training transition counts against the step budget. The audit returns one record per species, using common reset seeds and reporting the achieved descriptors and actual environment returns. Compare several species against a single species with the same total number of skills and report both real interactions and optimizer updates.
Reproduce the paired CPU runs¶
The example script writes
one JSON row per method and seed. The skill comparison uses the
existing rl extra.
python examples/relevance_search.py relevance --seeds 11 22 33 44 55
python examples/relevance_search.py fusion --seeds 11 22 33 44 55
python examples/relevance_search.py planning --seeds 11 22 33 44 55
python examples/relevance_search.py hebbian --seeds 11 22 33 44 55
python examples/relevance_search.py skills --seeds 11 22 33 44 55
With 240 evaluations and ten task calls per seed, RUDA reached 82.9% of held-out waypoints within tolerance. The unguided control reached 30.4%. Mean waypoint distance fell from 0.080 to 0.036.
Each fusion method measured 72 checkpoints per seed. Mean held-out score was 0.803 with M2N2, 0.788 with its mean-fitness control, and 0.914 with CycleQD. The worst group’s mean score was 0.753, 0.689, and 0.868, respectively.
The planner variants both made 3,648 simulator calls per seed. Progressive unpruning yielded a higher best score (0.475 versus 0.455). The all-open tree filled more cells (13.6 versus 12.2) and achieved a higher archive QD score (5.03 versus 4.71).
The Hebbian search evaluated 132 genomes. After the dynamics changed on held-out episodes, the same selected genome averaged 0.939 with plasticity and 0.674 with its weights frozen.
SSD used 480 training steps and 120 audit steps per seed in each configuration. The two-species variant increased mean endpoint separation from 0.158 to 0.374 and reduced mean downstream goal distance from 0.681 to 0.567. The two-species run performed 112 contrastive updates and the one-species run performed 116.