Quality-diversity policy gradient

QD-PG uses two policy gradients to build an archive of continuous controllers. One trains elites to improve task return. The other trains elites to visit states that are rare in a separate state-descriptor archive. Use the QDPG class in the optional qdpy.rl package.

From a QDpy checkout, install with pip or uv in your active environment.

python -m pip install -e '.[rl]'
uv pip install -e '.[rl]'

Describe a state and an episode

Start with a numeric Box observation and a bounded floating-point Box action. Supply a timestep descriptor and an episode descriptor of the same length. Choose coordinates so that discovering new states is likely to produce new episode descriptors. For example, the tracking environment records position at each step and uses final position to classify a policy.

from examples.continuous_qd_rl import HORIZON, Tracking
from qdpy.containers import Grid
from qdpy.rl import QDPG, PolicyConfig

def state_descriptor(observation, info):
    # Position before the action. "info" belongs to this observation.
    return observation[:2]

def descriptor(episode):
    return episode.observations[-1, :2]

archive = Grid(
    shape=(8, 8),
    features_domain=((-1., 1.), (-1., 1.)),
    fitness_domain=((0., HORIZON),),
)
search = QDPG(
    Tracking, archive,
    descriptor=descriptor, state_descriptor=state_descriptor,
    policy=PolicyConfig((16, 16)), max_episode_steps=HORIZON, seed=11,
    population_size=4, novelty_threshold=0.05,
)
stats = search.train(max_env_steps=2048)
search.best_policy().save("tracking-elite.npz")

The state callback receives the same float32 observation values as the policy, in their original shape, and the corresponding reset or step info. The first transition uses the reset descriptor. The terminal observation can contribute to the episode descriptor. It has no associated pre-action state descriptor because the policy takes no action there. The archive stores measured episode descriptors and ranks elites by undiscounted return by default. Supply a fitness(episode) callback for discounted return or a custom ranking objective. The quality critic still learns from the raw step rewards.

State novelty and policy updates

The novelty archive admits its first descriptor. After that, a state must have a mean distance to its nearest neighbors strictly above novelty_threshold. While the archive is small, the mean uses the available neighbors. Once the archive reaches novelty_capacity, a new admission overwrites the oldest admitted descriptor. An admitted state can be one of its own neighbors during replay. The default distance is Euclidean. To change it, provide novelty_metric(queries, archive_points) returning a finite, nonnegative matrix with one row per query and one column per archive point. Set the threshold in the units of that distance.

QD-PG starts with random policy evaluations. When replay meets the warmup setting and the archive has an elite, it samples a generation of parents uniformly with replacement. Half of the copies train on diversity and half on quality. The optimizer runs a number of rounds equal to the previous batch’s collected steps times gradient_steps_ratio, rounded down. With very short episodes, rounding can yield zero rounds. Within each round, each half of the generation shares its own twin critic networks. QD-PG averages critic gradients within the group, and each policy has its own target network. The critic for diversity recomputes the mean k-nearest-neighbor distance for the sampled pre-action descriptors. Replaying the same transition after new states arrive can give it a different novelty reward. Replay retains the original task reward for the quality critic.

Each completed scoring episode contributes to the candidate’s fitness and descriptor. All transitions, including those from rejected candidates and budget-cut episodes, go into replay and are considered for novelty admission in the order they occurred. Each call to train opens a fresh environment and retains the archive, replay, and any unstarted proposals. Diversity proposals are evaluated first within the generation. A budget-cut evaluation cannot enter the policy archive. Offspring counts include evaluations started. Optimizer counts include updates already spent preparing proposals that are still queued.

Reference choices

QDpy follows the equal quality and diversity split of Algorithm 2 in Pierrot et al. It uses the mean of the nearest Euclidean distances for admission and reward as described in Appendix C.3. Equation 5 presents a sum. QDpy uses synchronous SGD updates, 32-bit normalized actions in replay, and shared QDpy episode and budget handling. Set fitness to discounted episode return to use the ranking shown in Algorithm 2. Diversity Policy Gradient for Sample Efficient Quality-Diversity Optimization, GECCO 2022.

The pinned QDax implementation adds a configurable genetic emitter and greedy actor evaluations. It uses the nearest distance for admission and the mean squared distances for its Euclidean novelty function. QDax v0.2.3 emitter and novelty implementation.

CPU comparison

Run the three archive methods on the same tracking task, with the same eight random-policy evaluations and 2,048 environment steps per seed.

python examples/continuous_qd_rl.py --seeds 11 29 47 --steps 2048 \
    --methods neural-map-elites pga-map-elites qd-pg --output-dir build/qd-pg/pilot

Each run evaluated 128 controllers. The table shows the range across three seeds on CPython 3.12, Gymnasium 1.4, and PyTorch 2.15+cpu. The nine runs took 16.67 seconds on an Intel Xeon E5-2630 v4 with one Torch thread, including policy export and replay. Each replay used the best exported archive elite on a separate 16-step episode with a held-out target. Its maximum possible return is 16.

Method

Occupied cells of 64

Held-out return

Neural MAP-Elites

14–19

15.407–15.934

PGA-MAP-Elites

10–14

15.867–15.957

QD-PG

4–6

15.707–15.942

Each QD-PG run evaluated 60 quality offspring and 60 diversity offspring, with 496 critic updates across the two objectives. QD-PG occupied fewer cells than the two comparison methods on this small dense-reward task. The published QD-PG study evaluated deceptive-reward locomotion and maze tasks. Raw comparison results.