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: 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)`_. .. code-block:: python 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: 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)`_. .. code-block:: python 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: 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 :ref:`gradient-dynamics-aware-qd`. .. code-block:: python 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 :doc:`scalable_qd_benchmarks` for example comparison budgets and held-out results. .. code-block:: bash python examples/advanced_policy_qd.py ppga gail gail-ebc da-qd neural-me .. _Batra et al. (ICLR 2024): https://proceedings.iclr.cc/paper_files/paper/2024/hash/99b1a49a4e889f6965f221660d32cac9-Abstract-Conference.html .. _Wan et al. (ICML 2025): https://proceedings.mlr.press/v267/wan25i.html .. _Lim et al. (ICRA 2022): https://arxiv.org/abs/2109.08522