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.
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.
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.
# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Compare neural MAP-Elites and PPO in a custom MultiDiscrete environment.
"""Train and export three categorical policies on a small navigation task."""
import argparse
from dataclasses import asdict
import json
from pathlib import Path
import gymnasium as gym
import numpy as np
import torch
from qdpy.containers import Grid
from qdpy.rl import CategoricalPolicy, NeuralMAPElites, PPO, PPOAssistedMAPElites, PPOConfig, PolicyConfig
## @brief A bounded navigation task with six independent categorical controls.
class Navigation(gym.Env):
"""Use two directions to move. Each of the four switches has a small cost."""
observation_space = gym.spaces.Box(low=0, high=1, shape=(3,), dtype=np.float32)
action_space = gym.spaces.MultiDiscrete([3, 3, 2, 2, 2, 2])
horizon = 8
def _observation(self):
return np.array([*self.position, 1. - self.turn / self.horizon], dtype=np.float32)
def reset(self, *, seed=None, options=None):
super().reset(seed=seed)
self.turn = 0
self.position = self.np_random.uniform(0.4, 0.6, size=2)
return self._observation(), {}
def step(self, action):
if not self.action_space.contains(action):
raise ValueError("Invalid categorical action.")
direction = np.asarray(action[:2]) - 1
self.position = np.clip(self.position + direction * 0.10, 0, 1)
self.turn += 1
distance = np.linalg.norm(self.position - (0.8, 0.7))
reward = 1. - distance / np.sqrt(2) - 0.005 * float(sum(action[2:]))
return self._observation(), float(reward), self.turn == self.horizon, False, {}
def descriptor(episode):
"""Use the final position as the two-dimensional archive descriptor."""
return episode.observations[-1, :2]
def make_archive():
return Grid(shape=(8, 8), max_items_per_bin=1, fitness_domain=((0., 8.),),
features_domain=((0., 1.), (0., 1.)), fitness_weights=(1.,))
## @brief Evaluate a saved actor in an application-owned environment.
def replay(path, seed):
"""Run one held-out episode with deterministic actions."""
policy = CategoricalPolicy.load(path)
env = Navigation()
try:
observation, _ = env.reset(seed=seed)
total = 0.0
for step in range(1, env.horizon + 1):
action = policy.act(observation, deterministic=True)
observation, reward, terminated, truncated, _ = env.step(action)
total += reward
if terminated or truncated:
break
return {"steps": step, "return": total, "descriptor": observation[:2].tolist()}
finally:
env.close()
def main(steps, seed, output_dir):
torch.set_num_threads(1)
output_dir.mkdir(parents=True, exist_ok=True)
architecture = PolicyConfig(hidden_sizes=(32, 32))
ppo = PPOConfig(rollout_steps=32, epochs=2, batch_size=16, learning_rate=0.003)
common = dict(policy=architecture, max_episode_steps=Navigation.horizon, seed=seed)
searches = {
"ppo": PPO(Navigation, config=ppo, **common),
"neural_map_elites": NeuralMAPElites(Navigation, make_archive(), descriptor=descriptor,
initial_policies=4, **common),
"ppo_assisted_map_elites": PPOAssistedMAPElites(
Navigation, make_archive(), descriptor=descriptor, initial_policies=4,
ppo=ppo, ppo_probability=0.5, **common,
),
}
for method, search in searches.items():
stats = search.train(steps)
actor = search.policy if method == "ppo" else search.best_policy()
path = output_dir / f"{method}.npz"
actor.save(path)
report = {"method": method, "seed": seed, "env_steps": stats.env_steps, **asdict(stats),
"policy": path.name, "heldout": replay(path, seed + 10000)}
if method != "ppo":
report.update(occupied_cells=search.archive.filled_bins,
qd_score=search.archive.qd_score(normalized=False),
best_fitness=search.archive.best_fitness.values[0])
print(json.dumps(report), flush=True)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--steps", type=int, default=512, help="Environment-step budget for each method.")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--output-dir", type=Path, default=Path("results.discrete-qd-rl"))
arguments = parser.parse_args()
if arguments.steps < Navigation.horizon:
parser.error(f"--steps must be at least {Navigation.horizon} for an archived elite")
main(arguments.steps, arguments.seed, arguments.output_dir)
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.
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.
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 the nine pilot records.
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.
PPO-assisted MAP-Elites here is a baseline that alternates genetic variation and PPO improvement of copied parents.