Hierarchical archives, counterfactuals, and generative QD¶
Run the hierarchical, counterfactual, and soft-prompt comparisons with the base installation. Add PyTorch for the GFlowNet sampler. The Hierarchical archives, counterfactuals, and generative QD page lists budgets and results.
python -I examples/hierarchical_generative_qd.py all
python -I examples/hierarchical_generative_qd.py gflownet
Hierarchical MAP-Elites¶
Use qdpy.algorithms.HierarchicalArchive when users will first
choose a broad operating range and then compare alternatives within
that range. The example bins schedules by overtime. Each occupied
overtime bin has a second grid for staffing proportions.
from qdpy.algorithms import HierarchicalArchive, HierarchicalMAPElites
from qdpy.containers import Grid
unit = ((0., 1.),)
coarse = Grid(shape=(3,), features_domain=unit, fitness_domain=unit)
def staffing_grid(cell):
return Grid(shape=(2, 3), features_domain=unit * 2, fitness_domain=unit)
archive = HierarchicalArchive(coarse, staffing_grid)
# measure_schedule returns (fitness, coarse descriptor, fine descriptor).
search = HierarchicalMAPElites(
archive, propose=start_schedule, mutate=mutate_schedule, seed=11,
)
search.run(measure_schedule, budget=180)
together = archive.alternatives((.15,))
within_limit = archive.query(((0., .3),))
The hierarchy keeps a fine grid once its first valid design enters.
All branches use the same fitness domain and weights. The
coarse grid supplies geometry. Each stored elite keeps its original
genome at index zero, its fine features, and the coarse descriptor used
for routing. Use alternatives(point) for the matching coarse niche or
query(bounds) for an exact inclusive filter over retained designs.
Parents are sampled first by branch, then by occupied fine niche, so a
branch with few elites still contributes offspring.
Thoma2026
Counterfactual MOME¶
Use qdpy.algorithms.CounterfactualMOME when aggregate
descriptors hide differences in how policies interact with their
surroundings. Supply a rollout that returns objectives and a trace.
Describe the trace with one or more virtual reference agents. For
example, measure how many of the same locations a learned route and a
scripted patrol visit.
from qdpy.algorithms import CounterfactualMOME
from qdpy.containers import ParetoGrid
grid = ParetoGrid(
shape=(4, 4), max_items_per_bin=3, fitness_weights=(1., 1.),
fitness_domain=((0., 1.),) * 2, features_domain=((0., 1.),) * 2,
)
search = CounterfactualMOME(grid, budget=192, dimension=8, batch_size=8)
search.run(observation_trace, references=((0, 1, 2, 7), (1, 4, 5, 6)), describe=overlap)
Descriptor blocks follow the order of the references. An optional
base(trace) callback returns measurements to prepend. The framework
calls the rollout once per candidate. For agents that observe the
virtual patrol during their rollout, include it in your simulator and
return the learning agent’s trace. The example overlays the references
on the recorded trace. The original objectives feed the native
per-cell Pareto fronts in either case. Use a shared held-out descriptor
panel when comparing algorithms with different search descriptors.
Nickelson2023
Constructive GFlowNets¶
qdpy.algorithms.PreferenceGFlowNet learns a sampler over a
finite qdpy.algorithms.ConstructiveDAG. States may be
reached by several valid action sequences. The sampler assigns terminal
probability according to the total probability of all those paths.
This is useful when solutions are sets or graphs and the order of
construction is incidental.
from qdpy.algorithms import ConstructiveDAG, PreferenceGFlowNet
graph = ConstructiveDAG(
"start",
{"start": ("a", "b"), "a": ("ab", "a-only"),
"b": ("ab", "b-only"), "ab": (), "a-only": (), "b-only": ()},
)
scores = {"ab": (2., 5.), "a-only": (5., 1.), "b-only": (1., 5.)}
flow = PreferenceGFlowNet(graph, scores.__getitem__, objectives=2, seed=11)
panel = ((1., 0.), (.5, .5), (0., 1.))
flow.fit(panel, updates=300, batch_size=40)
print(flow.distribution((.5, .5)), flow.target_distribution((.5, .5)))
print(flow.sample((.5, .5), size=5))
# Flow proposals can also be measured into a scalar-quality Grid.
# flow.illuminate(grid, evaluate, panel, budget=30)
This CPU implementation uses trajectory balance, a uniform backward
policy over each state’s predecessors, and a learned forward sampler
conditioned on objective weights. Reward is a weighted sum of strictly
positive objectives raised to the configured power. Supply stable
objective values because the trainer caches terminal measurements.
Optimizer updates, sampled training trajectories, terminal reward
calls, and archive evaluations are counted separately.
distribution() sums learned path probabilities without calling the
reward function. target_distribution() enumerates the exact target
and measures any terminals still missing from the cache.
The graph and its legal actions are stored explicitly. Use it on a
small graph or a bounded constructive subproblem.
Jain2023 and
Malkin2022
Soft-prompt MAP-Elites¶
qdpy.algorithms.SoftPromptMAPElites evolves the embedding
vectors of virtual input tokens for a frozen decoder. Supply a fixed
grid or CVT, an initial token-by-embedding matrix, and two callbacks.
The decoder receives the embedding and a seed. The evaluator scores
the resulting text and measures descriptors such as length, style, or
semantic coordinates.
from qdpy.algorithms import SoftPromptMAPElites
search = SoftPromptMAPElites(archive, initial_embedding, seed=11)
search.run(generate, assess_text, budget=120, mode="targeted")
elite = next(iter(archive))
text, soft_prompt = elite[0], search.embedding(elite)
Targeted variation chooses a descriptor target and probes directions
with paired finite differences. Each pair receives the same decoding
seed. The resulting step aims to reduce the descriptor distance.
The search also interpolates between two prompts and tries Gaussian
mutations. Every probe spends one generation and can enter the
archive. Use mode="gaussian" and mode="fixed" as controls.
The implementation uses fixed archive geometry and one assessment
per decoded text. The original paper also adapts its centroid set,
uses text crossover, and buffers reevaluations.
Guo2026
The model example uses the actual inputs_embeds interface. Its
default decoder is a tiny randomly initialized GPT-2, so the smoke
run needs no checkpoint download. Supply a local causal model and
tokenizer directory with --model to optimise a trained decoder.
Install the model dependencies in the example environment.
python -m pip install torch "transformers>=4.50,<5"
python -I examples/soft_prompt_local_model.py --budget 24 --tokens 8
python -I examples/soft_prompt_local_model.py --model /path/to/checkpoint --budget 24