Train controllers for objective trade-offs¶
MOME-P2C stores a Pareto front in each behavior cell. It trains a shared
actor on preference vectors, while twin critics estimate separate
objective values. A preference such as [0.75, 0.25] gives the first
objective more influence on the policy update. Genetic candidates,
policies improved by gradients, and specialized copies of the shared
actor all compete in the same archive.
Install the optional backend with pip install "qdpy[rl]" or
uv add "qdpy[rl]". This example has two conflicting rewards and
uses a second action coordinate as its behavior descriptor.
import gymnasium as gym
import numpy as np
from qdpy.containers import ParetoGrid
from qdpy.rl import MOMEP2C, PolicyConfig, TD3Config
class Control(gym.Env):
observation_space = gym.spaces.Box(-1, 1, (1,), dtype=np.float32)
action_space = gym.spaces.Box(-1, 1, (2,), dtype=np.float32)
def reset(self, *, seed=None, options=None):
super().reset(seed=seed)
self.steps = 0
return np.zeros(1, dtype=np.float32), {}
def step(self, action):
self.steps += 1
effort, position = map(float, action)
objectives = (1 - .25 * (effort - .7)**2,
1 - .25 * (effort + .7)**2)
return (np.zeros(1, dtype=np.float32), sum(objectives),
False, self.steps == 4, {"objectives": objectives})
archive = ParetoGrid(
shape=6, max_items_per_bin=6, features_domain=((-1, 1),),
fitness_domain=((0, 4), (0, 4)), fitness_weights=(1, 1),
truncation="crowding",
)
search = MOMEP2C(
Control, archive, reward_vector=lambda obs, act, nxt, info: info["objectives"],
descriptor=lambda episode: (np.mean(np.asarray(episode.actions)[:, 1]),),
policy=PolicyConfig((16,)), seed=11, max_episode_steps=4,
td3=TD3Config(batch_size=16, learning_starts=32, critic_hidden_sizes=(16,)),
)
stats = search.train(256)
actor = search.conditioned_policy()
print(stats.env_steps, archive.qd_hypervolume((0, 0)))
print(actor.act(np.zeros(1, dtype=np.float32), [0.75, 0.25]))
Keep the Gymnasium step reward scalar. Provide the objective vector through the separate callback, which sees the observation, action, successor, and step info. A negative archive fitness weight minimizes that objective. The learner normalizes and signs each reward coordinate for training. The front stores original returns for interpretation.
To export a policy, call actor.save("actor.npz") and reload it with
PreferenceConditionedPolicy.load("actor.npz"). Preferences must be
nonnegative and sum to one. actor.specialize(preference) folds one
preference into an independent actor. search.policy_for(elite)
rebuilds a particular archived controller. The vector replay and archive
support three or more objectives. The public hypervolume helper uses two
objectives.
Set pg_offspring=0, injections=0 for a genetic search with the same
evaluation and archive policy. See Multifidelity search, adaptive grids, and curricula benchmarks for a
comparison under a shared budget.
Janmohamed et al., Preference-Conditioned Gradient Variations for Multi-Objective Quality-Diversity.