Adaptive exploration, operator selection, and phased diversity

These methods adapt different parts of a QD search. Novelty ES moves a population of parameter vectors. QQD learns which variation operator to apply to an archived solution. Bayesian Deep QD decides how to distribute exact evaluations across design configurations. PDO trains a population of control policies. Visual pre-training learns representations with different responses to data augmentation.

Search a deceptive landscape with novelty ES

Use qdpy.algorithms.NoveltyES when the candidate is a real vector and you can measure both a scalar reward to maximize and a numeric behavior descriptor. The implementation follows Conti2018. Each step chooses a population member in proportion to its novelty, scores a batch of Gaussian probes, and measures the updated candidate before storing its descriptor in the shared novelty history. An optional Grid or CVTGrid reports the best measured centers by niche. Search selection uses the shared history independently of the reporting grid.

from qdpy.algorithms import NoveltyES

def evaluate(genome, seed):
    x, y = genome
    return 1.0 - (x - 0.8) ** 2 - (y - 0.3) ** 2, (x, y)

search = NoveltyES(
    [(0.2, 0.5), (0.3, 0.6)], mode="nsra-es",
    pairs=4, patience=8, ind_domain=(0.0, 1.0), seed=11,
)
stats = search.run(evaluate, budget=200)
print(search.best, stats)

ns-es gives all weight to novelty, nsr-es weights ranked reward and novelty equally, and nsra-es starts with reward and decreases its weight after patience steps without a new best center. A new best center raises the weight again. The two rankings are computed separately before mixing the gradient estimates. QDpy uses antithetic probes and one Adam state per population member. By default, novelty uses Euclidean distance and retains the whole history. Set history_capacity to bound memory and the cost of nearest-neighbor queries.

The evaluator accepts a rollout seed. Return None to record a failed attempt. An incomplete probe batch leaves the previous center in place. Allow one call per initial center and at least 2 * pairs + 1 calls for each complete update. An optional executor with submit() can evaluate probes concurrently, with feedback applied in proposal order.

Choose local search operators with QQD

qdpy.algorithms.QQD uses Qin2025’s tabular controller in a best-only Grid or CVTGrid. The state cycles over positions in a batch of local proposals. Each action chooses one named operator. Using the same state cycle after a pause lets you extend a run with another budget.

from qdpy.algorithms import QQD
from qdpy.containers import Grid

archive = Grid(shape=(8,), features_domain=((0., 1.),),
               fitness_domain=((0., 1.),), fitness_weights=(-1.,))

def sample(rng):
    return (rng.random(),)

def move(genome, rng, direction):
    x = genome[0] + direction * rng.uniform(0., 0.2)
    return (min(1., max(0., x)),)

search = QQD(archive, sample=sample, operators={
    "smaller": lambda x, rng: move(x, rng, -1),
    "larger": lambda x, rng: move(x, rng, 1),
}, batch_size=8, seed=11)
search.run(lambda genome, seed: ((genome[0] - 0.35) ** 2, genome), 100)
print(search.q_values, search.stats.operator_attempts)

Each evaluation yields a scalar objective and a descriptor. Use the grid’s fitness weight to set the optimization direction. The controller gets one unit for a new cell, up to one unit for relative improvement over the previous occupant, and zero for rejection. Q-learning updates the value for the selected operator using the successor position’s maximum Q-value. Change controller to "uniform" or "bandit" to use the same operators with uniform or UCB1 selection. The scheduling example supplies two lightweight operators for dispatch order and machine assignment, using transport counts and idle periods as descriptors.

Balance exact evaluations across design configurations

Use allocation="equal" with qdpy.algorithms.BayesianDeepQD to give each configuration nearly the same number of exact attempts. Configurations take turns, including during warm-up and when a model falls back to a random proposal. The totals differ by at most one. A failed attempt counts against its configuration’s turn. The default allocation="competitive" allows acquisition scores to compete globally.

from qdpy.algorithms import BayesianDeepQD, ConditionalConfiguration, RealVariable
from qdpy.containers import Grid

archive = Grid(shape=(8,), features_domain=((0., 1.),),
               fitness_domain=((0., 2.),), fitness_weights=(1.,))
configurations = [
    ConditionalConfiguration({"frame": family}, ("span",), ("load",))
    for family in ("solid", "ribbed")
]
search = BayesianDeepQD(
    archive, 40, {"span": RealVariable(0., 1.)},
    configurations=configurations, allocation="equal", seed=11,
)

def evaluate(genome):
    design = search.decode(genome)
    span = design["span"]
    strength = 0.8 if design["frame"] == "solid" else 0.95
    return (1. + strength - span ** 2,), (span,), {"load": span - strength}

search.optimise(evaluate)
print(search.configuration_attempts, search.deep_archive.configuration_counts)

Following Baraton2026, exact measurements populate one layer per configuration. The supplied grid shows the best feasible design across the layers. Here both allocation modes use the same finite-pool, EIDA-inspired estimates based on each candidate’s predicted descriptor and probability of feasibility. Inspect layer counts as well as grid QD score when configuration representation matters.

Train a policy population in phases

Install qdpy[rl] for PDO. Use a factory that returns a fresh Gymnasium environment with a finite continuous Box action space. The optional descriptor callback receives a complete Episode. Supply a best-only Grid or CVTGrid if you want local competition in descriptor space. The default bounded archive prioritizes measured return.

from qdpy.rl import PDO, PPOConfig

# make_environment returns a fresh bounded continuous Gymnasium environment.
search = PDO(
    make_environment,
    descriptor=lambda episode: (episode.observations[-1, 0],),
    population_size=3, evaluation_episodes=2, max_episode_steps=100,
    ppo=PPOConfig(rollout_steps=256, batch_size=64), seed=11,
)
stats = search.train(20_000)
audit = search.evaluate(episodes_per_policy=8, seed=32)
if audit.measurements:
    search.policies()[0].save("tracking-policy.npz")

The synchronous PPO variant follows the two phases in Jiang2024. The reward phase updates each live learner and evaluates it. Periodically, it copies an archived policy into the worst-performing live learner. The auxiliary phase updates copies of the highest-return archived PPO policies, reusing observations from the reward phase. It compares their diagonal Gaussian action distributions in pre-squash coordinates with a Wasserstein kernel and a fixed bandwidth. A regularized determinant measures the diversity of the group. A fresh environment evaluation decides which copies enter the archive.

The training cost includes PPO rollouts and archive evaluations. initialization_cost and round_cost show how many steps to reserve. Early terminations or an archive with fewer than two policies can leave some of that reservation unused. evaluate() uses a separate common-seed panel and reports its own cost. The exported actor loads with ContinuousPolicy.load(). Set diversity_updates=0 for the reward-only population-based training control.

Pre-train encoders with different invariances

Install PyTorch for qdpy.vision. Start with the same clean examples and transformed versions for each encoder. The three tensor axes for clean features are encoder, sample, and embedding coordinate. Insert an augmentation axis after encoder for the transformed features.

from qdpy.vision import invariance_descriptors, visual_qd_loss

# Shapes: clean (M, B, D), transformed (M, T, B, D), losses (M,).
profiles = invariance_descriptors(clean, transformed)
result = visual_qd_loss(losses, profiles, diversity_weight=0.5)
optimizer.zero_grad()
result.total.backward()
optimizer.step()

The objective follows Chavhan2023 and the authors’ reference code. It averages aligned clean and transformed cosine similarities over the batch. Each encoder pair contributes the exponential of its negative mean absolute invariance gap. Add the sum of these terms to the mean of your per-encoder training losses. Pass a predictive loss, contrastive loss, or quality loss that already includes teacher distillation. Since the diversity term sums over pairs, tune its coefficient when changing the number of encoders. The demo fits downstream linear probes on frozen features and measures their accuracy on a held-out dataset.

Reproduce the CPU comparisons

From a source checkout with QDpy installed, run these commands. The example scripts print one JSON object per method and seed.

python examples/adaptive_diversity.py maze --seeds 11 22 33 44 55
python examples/adaptive_diversity.py schedule --seeds 11 22 33 44 55
python examples/adaptive_diversity.py depth --seeds 11 22 33 44 55
python examples/phasic_invariance.py pdo --seeds 11 22 33 44 55
python examples/phasic_invariance.py vision --seeds 11 22 33 44 55

The maze used 302 calls per method and seed, including all probes. The goal is any measured endpoint within 0.1 of the target. The table reports mean QD score and the median discovery call across successful runs, including discoveries from probe evaluations.

Method

Mean occupied cells

Mean QD score

Goal discoveries

Median first discovery

NS-ES

22.6

14.65

5/5

25

NSR-ES

18.2

13.27

4/5

25.5

NSRA-ES

15.2

10.69

4/5

39

ME-ES

17.8

13.37

5/5

107

On the four-job schedule at 300 calls, Q-learning, uniform, and UCB1 averaged QD scores of 11.27, 10.88, and 11.02. UCB1 had the lowest mean best energy at 70.4, followed by Q-learning at 71.4 and uniform at 73.0. On the frame design at 83 calls, equal allocation gave each configuration 28, 28, and 27 calls for every seed. Competitive allocation averaged 13.0, 47.8, and 22.2. Competitive had a higher mean grid QD score of 18.34 compared with 17.65 under equal allocation.

PDO and its control each used 666 training and archive interactions, plus 384 separately counted audit interactions per seed. PDO averaged 3.6 audit cells and a QD score of 3.09, compared with 2.6 and 2.25 for the control. The audit score sums the best return in each cell divided by the maximum episode return. Both methods had the same number of environment interactions. PDO spent more of those steps on evaluating archive candidates and completed nine reward rounds compared with twelve for the control.

At 60 optimizer steps, the visual QD encoders reduced the invariance penalty from 2.97 to 0.91. Frozen probe accuracy rose from 79.4% to 100% on bar orientation and from 88.0% to 99.1% on patch appearance. The mean base training loss increased from 0.0012 to 0.190. These small CPU experiments exercise the implementation on controlled tasks.