Discrete policy search with PPO and MAP-Elites ============================================== The optional ``qdpy.rl`` package trains policies in a caller-supplied Gymnasium environment. Choose standalone PPO to train a policy for reward, neural MAP-Elites to fill a behaviour grid by genetic variation, or PPO-assisted MAP-Elites to try fresh PPO updates on copies of selected elites before evaluating them for the grid. Install and run the example --------------------------- Install the extra from a checkout containing this tutorial, using pip or uv. .. code-block:: sh python -m pip install -e ".[rl]" # Or in an activated uv environment uv pip install -e ".[rl]" Run the bundled navigation example from the repository root. .. code-block:: sh python examples/discrete_qd_rl.py --seed 42 --steps 512 --output-dir results.navigation Each method receives the same step budget and prints one JSON record. The example writes a policy per method and reloads it for one held-out episode. The two archive methods use a policy's final position as its descriptor. Reward makes some positions more valuable than others, and the grid can retain policies for several of those positions. .. literalinclude:: ../examples/discrete_qd_rl.py :language: python Connect your own environment ---------------------------- Pass a callable that creates one fresh Gymnasium environment. QDpy opens an instance to read the spaces at setup and a fresh instance on each ``train()`` call. It closes each instance. Observations use a numeric ``Box`` with a fixed shape and finite values. Inputs are flattened to float32. The three methods accept ``Discrete`` and unmasked ``MultiDiscrete`` actions. For ``MultiDiscrete``, the actor produces one categorical distribution per entry in ``nvec``. Joint log probability and entropy are the sums of the factor values. Stochastic actions sample every factor independently. Deterministic actions choose each factor's mode. QDpy restores the shape, integer dtype, and start offsets declared by the environment. An archive search accepts an empty native one-elite ``Grid`` or ``CVTGrid`` with one maximizing objective. Configure fitness and descriptor bounds for your task. The descriptor callable receives an ``Episode`` with observations from reset through the true final observation, actions, rewards, reset and final info, and termination flags. QDpy copies the two info mappings and their nested values. Use values that support ``copy.deepcopy``. The optional fitness callable receives the same record. The default fitness is the undiscounted sum of rewards. Set ``evaluation_episodes`` to average fitness and descriptors over several complete episodes. PPO updates use the environment reward. Choose an archive objective compatible with that signal when comparing the hybrid with standalone PPO. An equal policy genome can occupy multiple cells when repeated evaluations reach different measured descriptors. Within a cell, the higher-fitness measurement wins. .. code-block:: python from qdpy.rl import CategoricalPolicy result = search.train(max_env_steps=2_048) search.best_policy(device="cpu").save("elite.npz") actor = CategoricalPolicy.load("elite.npz") action = actor.act(observation, deterministic=True) Here ``search`` is either archive algorithm. Use ``search.policy_for(elite)`` for a particular archive entry, or ``learner.policy`` with standalone ``PPO``. Saved files use a versioned numeric format and contain the actor architecture, parameters, and action layout. Loading needs no simulator. Keep a copy of the run configuration when sharing an actor. The artifact stores an inference policy. Repeated calls to ``train`` can continue a live search and, for standalone PPO, its optimizer. Each call opens a fresh environment. Accounting for interactions --------------------------- ``train(max_env_steps)`` grants that many additional calls to ``env.step()`` and returns cumulative ``TrainingStats``. The total ``env_steps`` is the sum of PPO data collection (``training_steps``) and policy scoring for the archive (``evaluation_steps``). Optimization uses multiple minibatches of the same freshly collected on-policy data and reports optimizer steps separately. Archive evaluations count toward search because they influence the archive. Measure held-out replay with a separate environment and seed, as the example does. External episode horizons count as truncations. PPO bootstraps from the actual last observation on truncation and stops the advantage trace at the episode boundary. A search budget cut before all scoring episodes complete leaves the measured steps charged and the candidate out of the archive. The hybrid reserves enough steps for the configured scoring episodes before it starts a PPO update. Reduce the external horizon to the declared maximum episode length when the environment has a known tighter limit. Set ``ppo_probability=0`` to run the genetic control with the same search settings. Call ``search.train`` again to advance the search, or pass ``on_step(archive, stats)`` to observe completed candidate evaluations. Use the archive's ``filled_bins``, ``qd_score()``, and ``best_fitness`` for progress reports. For cross-method QD scores, document the fitness domain and whether you sum raw or normalized scores. Standalone PPO has no archive. The current implementation uses a single synchronous environment at a time. CPU is the default. The policy accepts a CUDA device when the installed Torch build and hardware support it. Supported actions are Discrete and unmasked MultiDiscrete. The caller owns any controller conversion, action repetition, wrappers, and simulator replay. CPU pilot --------- The example ran with seeds 42, 43, and 44 using 2,048 search steps per method and one held-out eight-step episode per exported policy. These medians describe the toy navigation task on Linux with CPython 3.12, PyTorch 2.15.0 CPU, and Gymnasium 1.4.0. .. list-table:: :header-rows: 1 :widths: 36 12 12 12 13 15 * - Method - PPO steps - Archive steps - Cells out of 64 - Raw QD score - Held-out return * - Standalone PPO - 2,048 - 0 - — - — - 6.745 * - Neural MAP-Elites - 0 - 2,048 - 36 - 198.748 - 6.839 * - PPO-assisted MAP-Elites - 1,336 - 712 - 22 - 123.855 - 6.569 The hybrid trained 41, 42, and 44 offspring across the three seeds. Its PPO updates consumed steps that neural MAP-Elites spent on archive evaluations. Each run's JSON records those costs and the reloaded actor's result. :download:`Download the nine pilot records `. .. code-block:: sh for seed in 42 43 44; do python examples/discrete_qd_rl.py --steps 2048 --seed "$seed" \ --output-dir "results.navigation-$seed" > "navigation-$seed.jsonl" done References ---------- * Mouret and Clune, `Illuminating search spaces by mapping elites `__. * Schulman and colleagues, `Proximal Policy Optimization Algorithms `__. * `Gymnasium's guide to time limits `__. PPO-assisted MAP-Elites here is a baseline that alternates genetic variation and PPO improvement of copied parents.