Continuous control with PPO, TD3, and PGA-MAP-Elites

The optional qdpy.rl package accepts Gymnasium environments with fixed numeric Box observations and bounded floating-point Box actions. Each action coordinate can have its own lower and upper bound. The actor returns the original action shape and dtype. For categorical actions, see Discrete policy search with PPO and MAP-Elites. For separate quality and state-novelty gradients, see Quality-diversity policy gradient. For policies that take target descriptors, see Descriptor-conditioned MAP-Elites.

Install from a checkout that includes the continuous-control methods.

python -m pip install -e '.[rl]'
# Or install into your active uv environment:
uv pip install -e '.[rl]'

Choose a method

Method

Use it to

PPO

Learn one policy from fresh rollouts using a squashed Gaussian.

TD3

Learn one deterministic policy using off-policy replay and two critics.

NeuralMAPElites

Search a descriptor grid using random initialization and Iso+LineDD.

PPOAssistedMAPElites

Improve selected copies of archive elites using fresh PPO rollouts.

PGAMAPElites

Use shared replay to train a greedy actor and to improve copies of elites. Combine those policies with Iso+LineDD offspring in the same generation.

Train and export a policy

Pass a factory that creates a fresh environment. Pendulum-v1 runs the following example without a rendering dependency.

import gymnasium as gym

from qdpy.rl import ContinuousPolicy, PPO, TD3, TD3Config

def make_env():
    return gym.make("Pendulum-v1")

learner = TD3(make_env, config=TD3Config(batch_size=64, learning_starts=256), seed=42)
# To use PPO in the same Box environment, use PPO(make_env, seed=42).
stats = learner.train(max_env_steps=4_000)
learner.policy.save("pendulum.npz")

actor = ContinuousPolicy.load("pendulum.npz")
with make_env() as env:
    observation, _ = env.reset(seed=100)
    action = actor.act(observation)
    observation, reward, terminated, truncated, info = env.step(action)

The files contain the actor’s weights, observation shape, and action bounds. For PPO they also hold the learned log standard deviations. PPO clamps the log standard deviation to [-12, 2] for float32 sampling and training. Pass deterministic=False to sample a PPO policy or pass seed to ContinuousPolicy.load to reproduce its initial sampling stream. TD3’s exploration noise is applied during training, so its saved policy always uses the squashed mean. Policy files are inference artifacts. Keep the trainer instance to retain its optimizer and replay state across training calls.

PPO applies tanh to Gaussian samples before mapping them to the Box. It uses the original Gaussian samples to compute the likelihood ratio with the tanh and affine density corrections. The entropy bonus uses a sample from the transformed distribution. TD3 trains in normalized action coordinates. Its target uses the smaller of the two target critics, with clipped Gaussian smoothing. The actor and target networks update on the delayed schedule. At a time-limit truncation the target bootstraps from the actual final observation. A true termination ends bootstrapping.

Illuminate a behavior space with PGA-MAP-Elites

descriptor measures a finished episode. For Pendulum, the following descriptor records the mean horizontal and vertical pole coordinates. Use a parentless, best-only Grid or CVTGrid with one maximized objective.

from qdpy.containers import Grid
from qdpy.rl import PGAMAPElites, TD3Config

def behavior(episode):
    return episode.observations[1:, :2].mean(axis=0)

archive = Grid(shape=(12, 12),
               features_domain=((-1., 1.), (-1., 1.)),
               fitness_domain=((-4_000., 0.),))
search = PGAMAPElites(make_env, archive, descriptor=behavior, seed=42,
                      batch_size=8, critic_steps=32,
                      td3=TD3Config(batch_size=64, learning_starts=256))
stats = search.train(max_env_steps=8_000)
search.best_policy().save("best-elite.npz")
# For another elite, use search.policy_for(archive[index]).

PGA-MAP-Elites starts with random policies. Once the archive has a parent and replay has reached its warmup threshold, each generation starts by optimizing a single shared greedy actor and twin critics on past rollouts. With eight slots, the default schedule evaluates one greedy actor snapshot, four Iso+LineDD offspring, and three policy-gradient offspring. The offspring and their training observations are drawn before generation evaluation starts. Each gradient offspring trains a copy of an elite with its own optimizer, using the first critic to estimate the gradient.

Every candidate is scored in the environment. The default fitness is the mean raw episodic return. If you supply a different archive fitness, the critics still learn from the rewards returned by env.step, so the gradient operator may optimize a different objective. Set evaluation_episodes to average the descriptor and fitness across multiple complete episodes.

train(max_env_steps=...) spends additional environment steps, including all scoring attempts. PGA-MAP-Elites puts transitions from rejected or interrupted candidates in replay. Only fully scored candidates can enter the archive. If the budget ends partway through a generation, unstarted proposals stay queued for the next training call. The reported optimizer counts include the gradient work used to prepare those proposals. Each call opens a fresh environment and retains the current archive, learner, and replay.

Run the comparison

From a QDpy checkout, run the example with CPU PyTorch.

python examples/continuous_qd_rl.py --steps 2048 --seeds 11 29 47 \
    --output-dir build/continuous-qd-rl

The environment rewards tracking a seeded target velocity with two asymmetrically bounded controls. Its descriptor is the final position. The run uses 2,048 search steps per method and seed. Each reported held-out return comes from one separate 16-step deterministic episode using a reloaded policy. QD methods use the best policy stored in their archive. The ranges below span three seeds on CPython 3.12, Gymnasium 1.4, and PyTorch 2.15+cpu. The maximum possible return is 16.

Method

Occupied cells of 64

Held-out return

PPO

—

15.555–15.757

TD3

—

14.323–14.756

Neural MAP-Elites

14–19

15.407–15.934

PPO-assisted MAP-Elites

7–11

15.586–15.808

PGA-MAP-Elites

10–14

15.867–15.957

Each PGA run performed 480 critic updates and started 15 greedy evaluations and 45 gradient offspring. Neural MAP-Elites matched or exceeded both assisted variants in occupied cells on all three seeds. These short runs check algorithm execution, budget accounting, and exported inference on a common task. Download the raw JSONL results.

References