Gradient, imitation, and dynamics-aware policy search¶

From a checkout, install the optional RL extra with pip install '.[rl]' or uv sync --extra rl. The methods below use PyTorch and a factory that returns one Gymnasium environment. The environment must have finite numeric observations and bounded floating-point Box actions. Use an empty one-elite Grid or CVTGrid with one maximized objective.

For a runnable task, examples/advanced_policy_qd.py defines TargetControl, a two-axis system with seeded resets. The archive is indexed by the mean position of a policy over an episode. You can substitute your own environment and descriptor callbacks.

PPGA with timestep measures¶

Proximal Policy Gradient Arborescence uses PPO updates to estimate a direction for each measure and the objective. Exponential Natural Evolution Strategies (xNES) explores their coefficients. A separate PPO learner then moves the search policy along the updated mean coefficient direction. This implementation runs one environment at a time and uses fresh deterministic episodes to score the center and its branches. See Batra et al. (ICLR 2024).

from qdpy.containers import Grid
from qdpy.rl import PPGA, PPOConfig, PolicyConfig
from examples.advanced_policy_qd import TargetControl

def make_archive():
    return Grid(shape=(10, 10), max_items_per_bin=1,
                fitness_domain=((-float("inf"), float("inf")),),
                features_domain=((-1., 1.), (-1., 1.)))

def measure(observation, action, successor, info):
    return successor

search = PPGA(TargetControl, make_archive(), measure=measure,
              max_episode_steps=12, policy=PolicyConfig((12,)),
              population_size=7, sigma0=.7, seed=11,
              ppo=PPOConfig(rollout_steps=24, epochs=2, batch_size=24))
print(search.generation_step_limit)
stats = search.train(1152)
print(stats.training_steps, stats.evaluation_steps)
search.best_policy().save("policy.npz")

The measure callback sees physical actions and unflattened observations with the environment’s declared shape. Supply one scalar per descriptor dimension. If your reward can be negative, set threshold_min below the initial returns so those policies can contribute to search. A call to train starts a generation only if the remaining budget can cover every PPO collection and candidate evaluation. Inspect stats.env_steps to find the actual expenditure.

GAIL with Extrinsic Behavioral Curiosity¶

Supply demonstrations as a pair of arrays with a row per transition. The first array contains pre-action observations. The second contains the physical actions that produced those transitions, using the original action shape and units. No expert returns or expert policies are required. If a completed PPO episode falls in an empty cell, every transition gets the same curiosity bonus. See Wan et al. (ICML 2025).

from qdpy.rl import GAILEBC
from examples.advanced_policy_qd import demonstrations

imitation = GAILEBC(
    lambda: TargetControl(reveal_reward=False),
    make_archive(), demonstrations=demonstrations(),
    measure=measure, curiosity_weight=.5, max_episode_steps=12,
    population_size=7, sigma0=.7, seed=11,
    ppo=PPOConfig(rollout_steps=24, epochs=2, batch_size=24),
)
stats = imitation.train(1152)
print(stats.discriminator_updates, stats.curiosity_episodes)

Set curiosity_weight=0 for a matched GAIL run. Both configurations collect complete PPO episodes, so set rollout_steps at least as large as max_episode_steps. The discriminator is held fixed for a generation and updated from expert and recent agent transitions afterward. Archives keep each elite’s imitation score at insertion time. Re-evaluate the policies on common held-out seeds with your task’s validation reward to compare archives across generations or algorithms. The reference paper also studies VAIL and DiffAIL; this implementation covers GAIL.

Dynamics-Aware QD¶

The dynamics ensemble learns observation deltas from every real evaluation, including rejected candidates. It builds a temporary repertoire by rolling out and mutating policies in the model. The method then tests selected policies in the real environment before offering them to the reporting archive. See Lim et al. (ICRA 2022).

For real-data policy-gradient mutations within this workflow, see Gradient-assisted Dynamics-Aware QD.

from qdpy.rl import DynamicsAwareQD
import numpy as np

def descriptor(episode):
    return episode.observations[1:].mean(axis=0)

def model_reward(observation, action, successor):
    target = np.array([.55, -.35])
    return 1. - .15 * np.square(successor - target).sum()

model_search = DynamicsAwareQD(
    TargetControl, make_archive(), descriptor=descriptor,
    model_reward=model_reward, initial_policies=6, min_model_steps=72,
    max_episode_steps=12, imagined_candidates=24, max_transfers=4, seed=11,
)
stats = model_search.train(1152)
print(stats.evaluation_steps, stats.imagined_steps, stats.transferred_policies)

Imagined rollouts start from previously observed reset states. Use a descriptor that can be computed from the simulated trajectory. Its info mappings are empty. Supply model_terminated for predictable early stopping. By default the model uses the ensemble mean. Set sample_dynamics=True to sample from the ensemble’s predicted Gaussians. Transfer ordering uses the disagreement between member means. Set max_transfers=None to verify every imagined elite.

All three methods inherit policy_for and best_policy. Load a saved Box actor with ContinuousPolicy.load using only the policy file. See the Scalable emitters and continuous policy search benchmarks for example comparison budgets and held-out results.

python examples/advanced_policy_qd.py ppga gail gail-ebc da-qd neural-me

qdpy

Navigation

Contents:

  • Choose your first QDpy search
  • Run your first searches from PyPI
  • Validation for recommended methods
  • Run a seeded MAP-Elites search
  • Run a seeded NSLC search
  • Choose a QD method
  • Choose a QD algorithm
  • Compare three QD baselines
  • Run reference QD benchmarks
  • Reference QD benchmark results
  • MAP-Elites with Iso+LineDD
  • CMA-MAE with a best-only result grid
  • Dominated Novelty Search
  • Multi-Objective MAP-Elites
  • CMA-MAEGA with analytic gradients
  • Bayesian optimisation of elites
  • Discount Model Search
  • Constrained MAP-Elites with mixed variables
  • Conditional design search with HiGeME
  • Generational Adversarial MAP-Elites
  • Multi-Task Multi-Behavior MAP-Elites
  • Parametric-Task MAP-Elites
  • Learn descriptors from trajectories with AutoQD
  • MOUR-QD for unbounded descriptors
  • Mix-ME for cooperative teams
  • Quality diversity through human feedback
  • Graph-path quality diversity
  • Dynamic MAP-Elites
  • Multiple descriptors and CMA-based search
  • Case-wise selection and policy repertoires
  • Case-wise search and policy repertoire benchmarks
  • Conditional designs and task repertoires
  • Conditional designs and task repertoire benchmarks
  • Offline search and diverse plans
  • Offline search and diverse planning benchmarks
  • Compact repertoires and skill composition
  • Compact repertoire benchmarks
  • Deep archives and scenario discovery
  • Deep archives and scenario discovery benchmarks
  • Adaptive exploration, operator selection, and phased diversity
  • Residual regression and focused QD search
  • Learned density, design portfolios, and shared controllers
  • Refine diverse starts and coevolve complementary solutions
  • Guide search with task feedback and local adaptation
  • Build repertoires for classifiers, schedules, and skills
  • Search across age layers, decoders, and learned behaviors
  • Dynamic mutation and learned novelty
  • Encodings, behavior spaces, and design prototypes
  • Editable archives, preference drift, and component credit
  • Composite designs, surrogate niching, and heuristics
  • Composite design and heuristic search benchmarks
  • Solver-backed archives, graph policies, and self-play
  • Solver-backed archives, graph controllers, and parent selection
  • Few-shot priors, basin search, and semantic trade-offs
  • Language models for context rewrites, ideas, and benchmark tasks
  • Changing constraints, structured niches, fidelity, and replay
  • Changing constraints, structured niches, fidelity, and replay
  • Hierarchical archives, counterfactuals, and generative QD
  • Hierarchical archives, counterfactuals, and generative QD
  • Constraint programming, safe exploration, and diffusion search
  • Constraint programming, safe exploration, and diffusion search
  • Sequence search, outcome distributions, and continuing control
  • Sequence search, outcome distributions, and continuing control
  • Counterexamples, design symmetries, and learned policy variation
  • Counterexamples, design symmetries, and learned policy variation
  • Few-shot priors, basin search, and semantic trade-offs
  • Feasible Pareto fronts, analytic gradients, and diverse breeding
  • Feasible fronts, gradients, and diverse breeding
  • Quality thresholds, measured surrogates, and comparable policies
  • Quality thresholds, measured surrogates, and comparable policies
  • Metric archives, peer exchange, and structured variation
  • Metric archives, peer exchange, and structured variation
  • Pareto fronts, noisy elites, and policy gradients
  • Pareto fronts, noisy elites, and policy gradients on CPU
  • Model merging, subset selection, and planning
  • CPU comparisons for model merging, subset selection, and planning
  • Binary swarms, geometric policies, and budgeted archives
  • CPU pilots for binary, geometric, and budgeted search
  • Reference niches, repertoire selection, and model-based skills
  • CPU pilots for reference repertoires and model-based skills
  • Case novelty, linked variation, and discovered skills
  • CPU pilots for case novelty, linked variation, and discovered skills
  • Near-optimal portfolios, novelty, and policy reuse
  • CPU pilots for portfolios, novelty–surprise search, and policy reuse
  • Guided variation, reward coverage, and offline priors
  • Objective voting, structural diversity, and transfer
  • CPU pilots for guided search
  • Batch acquisition, benchmark instances, feasibility, and scenario risk
  • CPU pilots for batch acquisition, benchmark instances, feasibility, and risk
  • Discrete policy search with PPO and MAP-Elites
  • Continuous control with PPO, TD3, and PGA-MAP-Elites
  • Batched neural MAP-Elites
  • Quality-diversity policy gradient
  • Descriptor-conditioned MAP-Elites
  • Quality-Diversity Actor-Critic
  • Discrete QDAC variants
  • Control evaluation with ask and tell
  • Run a QDpy seed sweep with Rundra
  • Evaluate a MAP-Elites search with Ray
  • Replay a saved search
  • Save and resume a portable run
  • Compare multi-seed runs
  • Plot archive geometry and evolution
  • Genealogy and stepping stones
  • MC-AURORA with learned descriptors
  • MAP-Elites with noisy evaluations
  • Audit a noisy archive
  • Shared noisy Rastrigin validation
  • How QDpy runs a search
  • Core Python API
  • QDpy source reference
  • QDpy release notes
  • Run the release preflight
  • Benchmark search throughput
  • QDpy parallelism benchmarks
  • Compare MAP-Elites, CVT-MAP-Elites, and CMA-MAE
  • Shared QD benchmark panels
  • Modern QD pilot results
  • Differentiable, Bayesian, and high-dimensional QD pilots
  • Constrained search and GAME pilots
  • Fixed-task and dynamic QD pilots
  • Local Pareto, team, feedback, graph, and Bayesian QD pilots
  • Joint population optimization with SQUAD
  • Segment crossover in MAP-Elites
  • Learned competition rules
  • Share policy representations with RefQD
  • Co-design bodies and controllers with Pollination
  • Population objectives, learned selection, and policy transfer
  • Adapt a repertoire with M-BOA
  • Two-objective MO-CMA-MAE
  • Gradient-informed search on categorical genomes
  • Behavior-regulated policy gradients
  • Return to promising states with Go-Explore
  • Repertoire adaptation, gradient search, and exploration benchmarks
  • Multifidelity search, adaptive grids, and curricula
  • Train controllers for objective trade-offs
  • Multifidelity search, adaptive grids, and curricula benchmarks
  • Scalable covariance search and learned genome variation
  • Gradient, imitation, and dynamics-aware policy search
    • PPGA with timestep measures
    • GAIL with Extrinsic Behavioral Curiosity
    • Dynamics-Aware QD
  • Scalable emitters and continuous policy search benchmarks
  • Targeted search, balanced designs, and adversarial tournaments
  • SAC populations and search over frozen policy latents
  • Targeted search and policy population benchmarks
  • Interactive search, scheduling rules, and repertoire reuse
  • Distill a repertoire with the Quality-Diversity Transformer
  • Interactive and repertoire workflow benchmarks
  • Symbolic regression with MAP-Elites
  • Symbolic regression benchmark
  • Parent selection, surrogate search, and diverse skills
  • Parent selection, surrogate search, and skill pilots
  • Archive repair, ensembles, and policy reuse
  • Archive repair, ensembles, and policy reuse benchmarks
  • Differential evolution, mixed variables, and learned preferences
  • Differential evolution, mixed variables, and learned preferences
  • Solver repair, repertoire selection, and cross-component search
  • Solver repair, repertoire selection, and cross-component search
  • Offline search, learned niches, and cooperating policy parts
  • Offline search, learned niches, and cooperating policies benchmarks
  • Trace-Elites, MEMES, and asymmetric islands
  • Trace-Elites, MEMES, and AIM benchmarks
  • Deep QD, Voronoi-Elites, and occupancy CVT-MAP-Elites
  • Deep QD, Voronoi-Elites, and occupancy benchmarks
  • Sparse rewards, interpretable trees, and population diversity
  • Sparse rewards, decision trees, and determinant diversity
  • Ordered trajectories and model-guided variation
  • Ordered trajectories and model-guided variation

Related Topics

  • Documentation overview
    • Previous: Scalable covariance search and learned genome variation
    • Next: Scalable emitters and continuous policy search benchmarks
©2018, Leo Cazenille. | Powered by Sphinx 9.2.0 & Alabaster 1.0.0 | Page source