Learned density, design portfolios, and shared controllers¶
These examples cover continuous density search, Pareto optimization of
whole portfolios, policy sharing across designs, and two ways to
generate diverse outputs with a solver. Three examples use the base
QDpy package. Install qdpy[dms] for the DDS comparison or
qdpy[rl] for shared-controller co-design.
Fit a continuous descriptor density¶
qdpy.algorithms.dds_cnf() uses a continuous normalizing flow to
estimate the density of previously measured descriptors. CMA-ES ranks
the new candidates by increasing density. The passive archive records
what the search finds and uses the supplied fitness for admission.
DDS-KDE is the corresponding kernel density baseline. [Lee2024]
from qdpy.algorithms import dds_cnf
from qdpy.containers import Grid
archive = Grid(shape=(8, 8), features_domain=((0., 1.),) * 2,
fitness_domain=((0., 1.),), fitness_weights=(1.,))
def evaluate(genome):
x, y = genome
return (1. - 0.4 * (x - .6) ** 2,), (x, y)
result = dds_cnf(
archive, evaluate, x0=(.5, .5), budget=80, batch_size=8,
model_width=16, fit_steps=10, integration_steps=6, seed=11,
)
print(archive.filled_bins, result.model_fits, result.fit_seconds)
The QDpy variant fits a small CPU PyTorch velocity network by
conditional flow matching. It integrates descriptors back to a
standard Gaussian and uses the velocity divergence for the density
correction. The network sees only the reservoir from earlier batches.
The first batch uses equal ranks, and subsequent refits use
fit_period and fit_steps. The result separates evaluation attempts,
model updates, density evaluations, and wall time for each model phase.
The paper uses a different CNF training procedure based on OT-Flow.
Evolve sets with a quality and diversity trade-off¶
qdpy.algorithms.evolutionary_portfolios() treats a whole set of
binary designs as the unit of evolution. Score a set with either mean
member quality or its worst member quality. Measure diversity as the
sum of Hamming distances across unordered member pairs. The output
is a Pareto front of portfolios. [Do2024]
from qdpy.algorithms import evolutionary_portfolios
result = evolutionary_portfolios(
sum, dimension=5, portfolio_size=3, budget=300,
population_size=10, quality="worst", method="nsga2", seed=11,
)
for row in result.portfolios:
print(row.quality, row.diversity, row.members)
print(result.member_evaluations)
The second parent’s member ordering is shuffled before uniform
crossover. Use method="spea2" for strength-based selection or
method="uniform" for randomly generated portfolios. For
constrained problems, supply a repair(bits) callback or return
None for invalid members. Set descriptor(bits) to compare
designs in a binary space derived from the genome. The evaluator
charges each member slot, and a failed member excludes the whole
portfolio from selection. The search spends only complete
portfolio evaluations and reports the final population’s unique
nondominated objective pairs.
Train a shared controller for similar designs¶
qdpy.rl.LOKI clusters a finite catalog of designs using supplied
embeddings. Train one PPO actor and critic per cluster across its
active designs. At scheduled rounds, score sampled non-pool designs
and the incumbents under the current actor with common seeds. The
best sampled designs replace the lowest-scoring incumbents and the
same controller continues training on the updated pool. [Jeon2025]
from qdpy.rl import LOKI, PPOConfig
# make_environment(design) returns a fresh Gymnasium environment.
# design_embedding(design) returns a fixed-length numeric vector.
search = LOKI(
training_catalog, env_factory=make_environment, descriptor=design_embedding,
clusters=2, pool_size=4, max_episode_steps=60, seed=11,
ppo=PPOConfig(rollout_steps=120, batch_size=30),
)
print(search.train(12_000), search.pools)
audit = search.evaluate(held_out_designs, episodes_per_design=5)
if audit.measurements:
member = audit.measurements[0]
search.policy(member.cluster).save("shared-actor.npz")
All design environments must expose the same numeric Box observation
shape and action layout. The wrapper flattens the observation, appends
the normalized design embedding, and rotates through the active pool
on episode resets. Use observation(design, raw_observation) before
calling the exported actor. For independent deployment, keep the
design encoder and embedding_scale with the policy.
cluster_centers can route unseen designs to the nearest controller.
This finite-catalog variant accepts a learned morphology embedding
from the caller. The paper trains a morphology encoder and uses a
limb-aware Transformer controller.
train() charges PPO rollouts and competition evaluations against
one hard interaction budget. It reserves enough steps for a complete
round before starting it. Each round starts a fresh episode. A rollout
of at least pool_size * max_episode_steps can visit every active
design before the PPO update even when each episode reaches the horizon.
evaluate() is a separate common-seed audit and can assign held-out
designs to the nearest cluster.
Set search_period=None for a control with fixed training pools.
Collect diverse near-optimal mixed-integer designs¶
qdpy.algorithms.solve_diversitree() first certifies an optimum
with the existing SciPy MILP backend. It then searches a tree of
partial binary projections under an additive quality cutoff. Node
priority combines an inherited objective bound, the agreement of the
node’s fixed bits with completed designs, and its depth. [Ahanor2024]
from scipy.optimize import Bounds, LinearConstraint
from qdpy.algorithms import solve_diversitree
# The last coordinate is continuous. Retain diversity over the two binary coordinates.
result = solve_diversitree(
(-.1, -.2, 1.), Bounds([0, 0, 0], [1, 1, 4]),
size=3, budget=12, integrality=(1, 1, 0), quality_loss=2.1,
constraints=LinearConstraint([[-1., -2., 1.]], -float("inf"), 0.),
seed_solutions=1,
)
print(result.status, result.qualities, result.mean_binary_distance)
The QDpy variant uses separate MILP solves for nodes of an outer
tree. When a solve yields a representative, it partitions the
remaining node by the first binary coordinate where a design
could differ from it. Each verified design meets the shared cutoff,
and duplicate binary projections are excluded. Select
alpha=beta=0.0 for the objective-bound priority control. The
method reports whether the requested size was reached, the tree
was exhausted, the call budget was exhausted, or an oracle result
was unresolved. The reference optimum has a solver certificate.
The diversity score describes the returned set.
Select diverse plans under a cost ceiling¶
qdpy.algorithms.forbid_iterative_planning() uses a shared
uniform-cost frontier as the plan oracle for a deterministic simulator.
It treats equal action multisets as the same plan by default, and it
can preserve action order when needed. The bounded-depth search
continues from different action prefixes even when they reach the same
physical state. [Katz2020]
from qdpy.algorithms import forbid_iterative_planning
edges = {0: {"river": (1, 1.), "hill": (1, 1.4), "road": (1, 1.2)}}
result = forbid_iterative_planning(
0, actions=lambda state: edges[state],
simulate=lambda state, action: edges[state][action], goal=lambda state: state == 1,
size=2, max_depth=1, budget=3, cost_ceiling=1.5, distance_floor=.9,
)
print(result.plans, result.minimum_distance, result.simulator_calls)
Use greedy selection to start from the most distant pair and grow the
set. With distance_floor, QDpy solves the cheapest subset of the
requested size whose pairwise distances all meet that floor. The
bound applies to the recorded pool, which the transition, depth,
cost, and candidate limits can restrict. Report simulator calls
and the subset solver call separately. The default distance is
one minus the multiset Jaccard similarity of two plans’ actions.
Reproduce the CPU comparisons¶
The example script
writes one JSON object per method and seed. The measurements below
used CPython 3.12, NumPy 2.5.5, SciPy 1.18.1, scikit-learn 1.9.1,
pycma 4.6.0, PyTorch 2.15.0 (CPU), and Gymnasium 1.4.0 on Linux x86-64.
python examples/portfolio_codesign.py density --seeds 11 22 33 44 55
python examples/portfolio_codesign.py portfolio --seeds 11 22 33 44 55
python examples/portfolio_codesign.py codesign --seeds 11 22 33 44 55
python examples/portfolio_codesign.py tree --seeds 11 22 33 44 55
python examples/portfolio_codesign.py planning --seeds 11 22 33 44 55
Both density methods used 144 evaluations per seed on 48 reference cells. KDE filled 34.4 cells on average in two dimensions and 36.6 in six. CNF filled 31.0 and 33.4. Median total wall times for KDE were 0.058 and 0.063 seconds. CNF took 0.160 and 0.205 seconds, including median model fitting of about 0.07 seconds in either case.
The coverage portfolio has three exact Pareto objective pairs. At 1,200 member calls, uniform search recovered 0.6 of those pairs on average, NSGA-II recovered 1.4, and SPEA2 recovered 1.2.
At 1,152 environment steps, average held-out return was 5.60 with dynamic shared controllers, 5.77 with static shared controllers, and 5.51 with one controller per original design. Dynamic LOKI used 576 of its steps to compare design candidates and completed 24 replacements per seed. Each audit used 96 separate steps.
Both mixed-integer priorities collected all six requested designs, each within five objective units of its reference optimum. Diversity-guided branching increased mean normalized Hamming distance from 0.313 to 0.348 and used 6.8 solver calls on average, compared with 6.2 for the objective-bound priority.
All planning methods scored the same five candidate routes using 11 simulator calls. The cheapest three had mean total cost 3.625 and minimum action distance 0.5. Both diverse panels had mean total cost 4.999 and minimum action distance 1.0. The diversity-floor option used one additional MILP call.