Case novelty, linked variation, and discovered skills¶
Some searches have an error for every test case. Others know that variables interact or need to evolve new tasks alongside solvers. The methods here use those signals for search. SMERL uses a separate return threshold to learn a repertoire of latent skills.
Novelty-lexicase selection¶
qdpy.algorithms.novelty_lexicase_index() treats each error and
each output rarity count as a separate case. A parent draw uses a
fresh shuffle. For every case, it keeps the candidates with the lowest
error or the rarest output among the remaining candidates. Earlier
populations can contribute to the rarity counts.
import numpy as np
from qdpy.algorithms import novelty_lexicase_index
from qdpy.symbolic import symbolic_regression
rng = np.random.default_rng(11)
errors = [[0., 1.], [0.5, 0.], [0.1, 0.8]]
outputs = [["even", "high"], ["odd", "low"], ["even", "high"]]
print(novelty_lexicase_index(errors, outputs, rng, history=[["even", "low"]]))
x = np.linspace(-1., 1., 24)[:, None]
y = np.sin(x[:, 0]) + x[:, 0] ** 2
fitted = symbolic_regression(
x, y, mode="novelty-lexicase", budget=120, population_size=12,
novelty_binner=lambda values: np.floor(4 * np.arctan(values)).astype(int),
novelty_history=32, seed=11,
)
print(fitted.best.training_rmse, fitted.stats.case_evaluations)
For categorical outputs, use the labels directly. For continuous outputs, use bins or another grouping rule with a meaningful scale. The default symbolic regression mode groups compressed predictions in 16 bins. The bounded history keeps one sampled output vector per completed generation. All three lexicase modes in symbolic regression also report a passive structural grid. The novelty counts reuse the same prediction pass as the case errors.
See Jundt and Helmuth, Comparing and Combining Lexicase Selection and Novelty Search.
Gene-pool optimal mixing for MAP-Elites¶
qdpy.algorithms.GOMMAPElites fits a linkage tree from the
archive’s measured genomes. Each variable starts in a singleton
group. The tree joins groups whose values tend to depend on one
another across those genomes. A mix copies linked groups from
donors, tests the resulting genome, and continues from it when scalar
fitness holds or improves.
from qdpy.algorithms import GOMMAPElites
from qdpy.containers import Grid
archive = Grid(shape=(3, 3), features_domain=((0., 2.), (0., 2.)),
fitness_domain=((0., 4.),), fitness_weights=(1.,))
def evaluate(bits):
first, second = sum(bits[::2]), sum(bits[1::2])
return float(2 * ((first == 2) + (second == 2))), (first, second)
search = GOMMAPElites(archive, (2, 2, 2, 2), initial_samples=8, seed=11)
stats = search.run(evaluate, 64)
print(stats.evaluations, stats.block_evaluations, stats.accepted_blocks)
The archive receives every measured block probe. This allows a trial
with lower scalar fitness to add a useful alternative in a different
cell. Each test spends one objective call. A donor must differ in the
chosen group to trigger evaluation. Random proposals introduce categories
that the current archive has yet to see. Set learn_linkage=False
to compare with singleton mixing. Use explicit archive fitness weights
to set the direction of improvement.
QDpy adapts the mixing rule in Thierens and Bosman, Optimal Mixing Evolutionary Algorithms to a native scalar best-only Grid or CVTGrid.
Resource-limited coevolution¶
qdpy.algorithms.MinimalCriterionCoevolution maintains
separate task and solver populations. A new task needs a live solver
that passes its criterion. A new solver needs to pass on a live task
with a resource available. A successful solver admission spends one
resource from its supporting task.
from qdpy.algorithms import MinimalCriterionCoevolution
def mutate_task(task, rng):
return max(1, task + int(rng.choice([-1, 1])))
def mutate_solver(solver, rng):
return max(1, solver + int(rng.choice([-1, 1])))
search = MinimalCriterionCoevolution(
[1], [1], mutate_task=mutate_task, mutate_solver=mutate_solver,
task_capacity=6, solver_capacity=6, task_resources=2, seed=11,
)
stats = search.run(lambda task, solver, seed: solver >= task, budget=30)
print(stats.evaluations, stats.solver_admissions, search.tasks)
Provide viable, distinct founders. The search budgets calls to the
pair evaluator, with a separate cap on proposed offspring. After a
budget cut, another run call resumes any unfinished set of partner
tests. Populations evict the oldest entries at capacity. A task’s
resources apply to its current lifetime in the population. Use
task_resources=None for the uncapped control.
The maze example measures both live task diversity and solver success on a fixed panel of unseen mazes. It compares capped and uncapped MCC with Enhanced POET. The admission and resource rules follow Brant and Stanley, GECCO 2017 and their resource-limitation study, GECCO 2020.
Learn and audit SMERL skills¶
Install qdpy[rl] to train SMERL with numeric Box observations and
continuous Box actions. Sample one skill ID per episode. The actor
receives a one-hot skill input, and the discriminator predicts that
ID from successor observations. Task reward is used on every replay
row. The discriminator bonus is added when the complete episode’s
undiscounted task return reaches the threshold.
import gymnasium as gym
from qdpy.containers import Grid
from qdpy.rl import PolicyConfig, SMERL, SMERLConfig, SMERLPolicy, evaluate_discovered_skills
def env():
return gym.make("Pendulum-v1")
search = SMERL(
env, return_threshold=-180., max_episode_steps=24, seed=11,
policy=PolicyConfig((16,)),
config=SMERLConfig(skills=4, batch_size=8, learning_starts=24,
critic_hidden_sizes=(16,), discriminator_hidden_sizes=(16,)),
)
stats = search.train(97)
print(stats.env_steps, stats.eligible_episodes, stats.incomplete_episode_steps)
search.policy.save("pendulum-smerl.npz")
actor = SMERLPolicy.load("pendulum-smerl.npz")
grid = Grid(shape=8, features_domain=((-8., 8.),), fitness_domain=((-400., 0.),))
audit = evaluate_discovered_skills(
env, actor, descriptor=lambda ep: (ep.observations[1:, 2].mean(),),
archive=grid, episodes=2, max_episode_steps=24, seed=1011, qd_offset=400.,
)
print(audit.mean_return, audit.archive_coverage)
Choose a threshold based on a reference policy’s task return and the loss you can tolerate. Record any interactions used to train or measure that reference separately. Transitions from a budget-cut episode count as real interactions and are left out of replay. A Gymnasium time limit completes the episode for the return gate and preserves bootstrapping from the final observation.
The exported actor takes a zero-based skill ID via
actor.act(observation, skill). These labels refer to learned
behaviours. Supply an episode descriptor to assess the behaviours
on the same geometry as a skill-conditioned QDAC policy.
See Kumar et al., Structured Maximum Entropy Reinforcement Learning.
python examples/linked_skills.py
python examples/qdac_mb.py --methods smerl qdac qdac-mb --steps 2048
See CPU pilots for case novelty, linked variation, and discovered skills for measurements and controls.