Sequence search, outcome distributions, and continuing control¶
The example runs Gram-Elites on original tile sequences and compares mean and distribution-valued descriptors on a stochastic task. With the RL extra, it also compares three methods on a navigation task. See Sequence search, outcome distributions, and continuing control for results and budgets.
python -m pip install .
python -I examples/sequence_distribution_qd.py --task base
python -m pip install ".[rl]"
python -I examples/sequence_distribution_qd.py --task navigation
Gram-Elites¶
Fit qdpy.algorithms.NGramSequenceSpace on sequences that
contain local patterns you want the search to use. A token can be
a character, a categorical identifier, or an immutable tuple
representing a tile column. Supply fitness and behavioral descriptors
through the usual QDpy evaluator.
from qdpy.algorithms import GramElites, NGramSequenceSpace
from qdpy.containers import Grid
space = NGramSequenceSpace(["abbacaba", "abacbaba", "acabbaca"], n=3, length=12)
archive = Grid(
shape=(13,), features_domain=((0, 13),),
fitness_domain=((0., 1.),),
)
def evaluate(candidate):
transitions = set(zip(candidate, candidate[1:]))
return (len(transitions) / 11,), (candidate.count("c"),)
search = GramElites(archive, 128, space, mutation_probability=.2, seed=7)
best = search.optimise(evaluate)
Generation draws from the observed transition counts and checks that each selected edge can reach the requested length. Crossover joins a prefix and suffix with a shortest path through the context graph. Mutation first substitutes one token, then reconnects the suffix. When a splice is too long, the operator trims its tail. If it is short, it tries to extend from the same model. A splice that cannot be completed keeps its first parent.
An n-gram checks local support. In the tile example, a separate
playability test tracks keys across the entire level and checks
climb height. Use native ask() and tell(..., tell_container=False)
when an evaluated proposal should consume budget without entering
the archive. Use a corpus that covers the structures you want the
algorithm to explore.
Biemer2021
Distribution MAP-Elites¶
Use this workflow when two candidates with the same average outcome can behave differently. The descriptor is the empirical distribution of one scalar outcome, measured across repeated rollouts. The evaluator also returns scalar fitness, whose average determines whether the candidate replaces its niche’s elite.
import numpy as np
from qdpy.algorithms import (
DistributionMAPElites, EmpiricalDistribution, MedoidArchive,
wasserstein_descriptor_distance,
)
archive = MedoidArchive(
[EmpiricalDistribution([0.]), EmpiricalDistribution([-2., 2.])],
wasserstein_descriptor_distance,
)
def evaluate(spread, seed):
rng = np.random.default_rng(seed)
return 1., spread * rng.choice([-1., 1.])
search = DistributionMAPElites(
archive, propose=lambda rng: 0.,
mutate=lambda spread, rng: 2. - spread, rollouts=20, seed=7,
)
search.optimise(evaluate, budget=12)
for row in search.audit(evaluate, rollouts=80):
print(row.search_niche, row.audit_niche, row.stable)
print(search.nb_rollouts, search.nb_audit_rollouts)
Use references with meaningful differences in outcome units. To
learn fixed medoids from previously measured outcome distributions,
call MedoidArchive.fit(reference_panel, count, wasserstein_descriptor_distance).
Include the cost of generating a new reference panel in any
experiment that learns it from scratch.
The first Wasserstein distance implements one-dimensional moving
mass with absolute distance as the cost. Samples can repeat and
panels can have unequal sizes. Search and audit use separate
seed streams. The audit uses a shared, fixed held-out panel and
returns reassignment records without updating the archive. Count
rollouts with nb_rollouts and nb_audit_rollouts when comparing
against a method that uses averaged descriptors. This is a QDpy
workflow using ideas from uncertain QD and optimal transport.
Flageat2024 and
Peyré2019
Reset-Free QD¶
A continuing task gives each selected policy the actual final state of the preceding one. In the example, the simulator drifts while a policy moves it around a bounded training region. A skill is four consecutive steps, and its descriptor is the displacement during those steps.
Supply a Gymnasium environment factory with numeric Box observations,
bounded floating-point Box actions, and no time-limit wrapper. Define
a finite signed safety margin, an action for recovery, and a model
reward with arguments (observation, action, successor). Keep the
descriptor and fitness callbacks compatible with measured and
imagined episodes. Imagined episodes have empty info mappings.
import gymnasium as gym
import numpy as np
from qdpy.containers import Grid
from qdpy.rl import PolicyConfig, ResetFreeQD
def reward(observation, action, successor):
return .5 + abs(float(successor[0] - observation[0]))
class Track(gym.Env):
observation_space = gym.spaces.Box(-2., 2., (1,), dtype=np.float32)
action_space = gym.spaces.Box(-1., 1., (1,), dtype=np.float32)
def reset(self, *, seed=None, options=None):
super().reset(seed=seed)
self.x = np.zeros(1, dtype=np.float32)
return self.x.copy(), {}
def step(self, action):
successor = np.clip(self.x + .15 * action + .025, -2., 2.)
score = reward(self.x, action, successor)
self.x = successor
return self.x.copy(), score, False, False, {}
archive = Grid(
shape=(9,), features_domain=((-1., 1.),),
fitness_domain=((0., 4.),),
)
rng = np.random.default_rng(7)
def recover(observation):
return np.clip(-3. * observation, -1., 1.)
def warmup(observation):
if abs(observation[0]) > .4:
return recover(observation)
return rng.uniform(-1., 1., 1).astype(np.float32)
with ResetFreeQD(
Track, archive, skill_steps=4, descriptor=lambda episode:
episode.observations[-1] - episode.observations[0],
model_reward=reward, safety_margin=lambda x: .75 - abs(x[0]),
fallback_action=recover, warmup_action=warmup, safety_buffer=.10,
policy=PolicyConfig(()), model_policy=PolicyConfig((16,)),
min_model_steps=24, model_updates=6, model_learning_rate=.01,
imagined_candidates=16, seed=7,
) as search:
search.train(64)
stats = search.train(96) # Same simulator and current observation.
if archive:
search.best_policy().save("track-skill.npz")
Warm-up collects real transitions for the dynamics ensemble. Once the model can fit, QDpy predicts skills from the current state, filters imagined paths by the safety buffer, and prioritizes novelty among surviving niches. A real trajectory that crosses the safety boundary stops and stays out of the archive. Recovery first looks for a measured policy predicted to improve the margin. The fallback controller acts when no such policy is available or recovery fails to improve the margin.
The reported safety outcomes come from actual transitions. The
learned gate is heuristic and can admit a skill that crosses the
boundary. Simulation or an independent safety system is needed
for settings where a violation has consequences. Each call to
train reserves a complete skill before model-based selection,
so up to skill_steps - 1 steps may remain unused. Gymnasium
termination or truncation ends the session. The context manager
closes it and leaves archived policies available for export.
Lim2022