5"""Train policies for different objective trade-offs in each descriptor cell."""
7from collections
import deque
8from copy
import deepcopy
9from dataclasses
import dataclass
21from .descriptor_policy
import DescriptorConditionedPolicy, _DescriptorDomain
22from .policy
import ContinuousPolicy, PolicyConfig, _integer, _mlp
23from .rollout
import _Cursor, _StepBudget, _check_spaces, _evaluate_episode, _open_environment, _seed
24from .search
import NeuralMAPElites
25from .td3
import OffPolicyStats, TD3Config, _Replay, _bellman_target, _checked_step, _polyak
27__all__ = [
"MOMEP2C",
"MOMEP2CStats",
"PreferenceConditionedPolicy"]
30def _preference(values, width):
31 weights = np.asarray(values, dtype=float)
32 if weights.shape != (width,)
or not np.all((0. <= weights) & (weights <= 1.))
or not np.isclose(
33 weights.sum(), 1., rtol=0., atol=1e-6):
34 raise ValueError(
"Provide one nonnegative preference per objective, summing to one.")
35 return weights / weights.sum()
40 """Use nonnegative preferences summing to one to choose an objective trade-off."""
42 def __init__(self, observation_space, action_space, objectives, **kwargs):
43 domain = ((0., 1.),) * _integer(objectives,
"objectives", 2)
44 super().__init__(observation_space, action_space, domain, **kwargs)
46 def _initialize(self, shape, actions, domain, config, seed, device):
47 if len(domain.bounds) < 2
or any(bounds != (0., 1.)
for bounds
in domain.bounds):
48 raise ValueError(
"Preference policies require at least two unit-interval inputs.")
49 super()._initialize(shape, actions, domain, config, seed, device)
52 def act(self, observation, preference):
53 """Return an action in the physical action-space units."""
58 """Return an independent unconditioned actor for one preference."""
63@dataclass(frozen=True)
65 """Cumulative interaction, optimizer, Pareto admission and replay counts."""
67 genetic_offspring: int = 0
71 """Keep raw objective vectors in replay and maintain running reward moments."""
73 def __init__(self, capacity, actor, objectives):
74 super().__init__(capacity, prod(actor._obs_shape), prod(actor._actions.shape))
75 self.
rewards = np.empty((capacity, objectives), dtype=np.float32)
77 self.
mean = np.zeros(objectives)
78 self.
m2 = np.zeros(objectives)
80 def add_episode(self, actor, episode, rewards):
82 start = max(0, count - self.
capacity)
84 observations = episode.observations.reshape(count + 1, -1)
85 actions = np.asarray(episode.actions, dtype=np.float64).reshape(count, -1)
87 self.
actions[rows] = actor._encode_actions(actions[start:])
88 self.
rewards[rows] = rewards[start:]
94 batch_mean = rewards.mean(axis=0)
95 total = self.
count + count
96 delta = batch_mean - self.
mean
97 self.
m2 += np.sum((rewards - batch_mean) ** 2, axis=0) + delta ** 2 * self.
count * count / total
98 self.
mean += delta * count / total
101 def normalized(self, rewards, direction):
102 dtype, device = rewards.dtype, rewards.device
103 mean = torch.as_tensor(self.
mean, device=device)
104 std = torch.as_tensor(np.sqrt(self.
m2 / self.
count + 1e-8), device=device)
105 return ((rewards - mean) / std).to(dtype) * direction
108def _scalar_values(network, conditioned, actions, preference):
109 vector = network(torch.cat((conditioned, actions), dim=-1))
110 return (vector * preference).sum(dim=-1)
113def _preference_target(rewards, terminated, first, second, preferences, gamma):
114 """Scalarize each entire vector before picking the more conservative critic."""
115 return _bellman_target((rewards * preferences).sum(dim=-1), terminated,
116 (first * preferences).sum(dim=-1), (second * preferences).sum(dim=-1), gamma)
120 """Learn one actor and twin vector-valued critics across preferences."""
122 def __init__(self, shared, replay, td3, direction, counts, seed):
124 self.
rng = np.random.default_rng(seed)
125 self.
torch_rng = torch.Generator(device=shared.device).manual_seed(_seed(self.
rng))
126 self.
width = len(direction)
127 self.
direction = shared._tensor(direction)
128 units = prod(shared._obs_shape) + prod(shared._actions.shape)
130 _seed(self.
rng), shared.device, nn.ReLU)
for _
in range(2)])
132 self.
actor_target = deepcopy(shared._network).requires_grad_(
False)
134 self.
actor_optimizer = torch.optim.Adam(shared._trainable_parameters(), lr=td3.actor_learning_rate)
136 def preferences(self, count):
137 return self.
actor._tensor(self.
rng.dirichlet(np.ones(self.
width), size=count))
139 def _condition(self, obs, weights):
140 return torch.cat((obs, 2 * weights - 1), dim=-1)
142 def improve(self, actor, optimizer, obs, weights, *, shared=False):
144 action = actor._normalized(conditioned
if shared
else obs)
145 loss = -_scalar_values(self.
critics[0], conditioned, action, weights).mean()
146 if not torch.isfinite(loss):
147 raise ValueError(
"MOME-P2C produced a nonfinite actor loss.")
148 parameters = tuple(actor._trainable_parameters())
149 for parameter, gradient
in zip(parameters, torch.autograd.grad(loss, parameters)):
150 parameter.grad = gradient
151 _checked_step(optimizer)
152 self.
counts[
"optimizer_steps"] += 1
156 obs, actions, rewards, successors, terminated = self.
replay.sample(
157 td3.batch_size, self.
rng, self.
actor.device)
159 conditioned, next_conditioned = self.
_condition(obs, weights), self.
_condition(successors, weights)
160 with torch.no_grad():
161 noise = torch.randn(actions.shape, device=actions.device, generator=self.
torch_rng)
162 noise = (noise * td3.target_noise).clamp(-td3.noise_clip, td3.noise_clip)
163 next_actions = (self.
actor_target(next_conditioned).tanh() + noise).clamp(-1, 1)
164 joined = torch.cat((next_conditioned, next_actions), dim=-1)
165 target = _preference_target(self.
replay.normalized(rewards, self.
direction), terminated,
166 self.
targets[0](joined), self.
targets[1](joined), weights, td3.gamma)
167 loss = sum(F.mse_loss(_scalar_values(critic, conditioned, actions, weights), target)
for critic
in self.
critics)
168 if not torch.isfinite(loss):
169 raise ValueError(
"MOME-P2C produced a nonfinite critic loss.")
173 self.
counts[
"critic_updates"] += 1
174 self.
counts[
"optimizer_steps"] += 1
175 if self.
counts[
"critic_updates"] % td3.policy_delay == 0:
177 self.
counts[
"actor_updates"] += 1
183 """Share continuous rollouts and vector return admission between MOME methods."""
186 def _validate_archive(archive):
187 if (
not isinstance(archive, ParetoGrid)
or len(archive)
or archive.parents
188 or getattr(archive,
"truncation",
"random") !=
"crowding"):
189 raise ValueError(
"Supply an empty parentless ParetoGrid with truncation='crowding'.")
191 def _build_actor(self, env, config, seed, device):
192 return ContinuousPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
194 def _collect(self, cursor, budget):
197 def record(observation, action, reward, successor, terminated, truncated, info):
198 values = np.array(self.reward_vector(observation, action, successor, info), dtype=float, copy=
True)
199 if (values.shape != (self._objectives,)
or not np.isfinite(values).all()
200 or np.any(np.abs(values) > np.finfo(np.float32).max)):
201 raise ValueError(
"Provide one finite float32-representable reward per objective.")
202 rewards.append(values)
204 episode = _evaluate_episode(cursor, self.
_actor, budget, transition_info=record)
207 rows = np.stack(rewards)
208 self._replay.add_episode(self.
_actor, episode, rows)
209 return episode, rows.sum(axis=0)
211 def _offer_returns(self, episodes, returns, operator):
212 values = tuple(np.mean(returns, axis=0))
213 descriptors = np.array([self.
_descriptor(episode)
for episode
in episodes], dtype=float)
214 if descriptors.shape != (len(episodes), len(self.
archive.features_domain))
or not np.isfinite(descriptors).all():
215 raise ValueError(
"Return one finite descriptor per archive axis.")
216 features = tuple(np.mean(descriptors, axis=0))
217 if (
not np.isfinite(features).all()
218 or not self.
archive.in_bounds(values, self.
archive.fitness_domain)
219 or not self.
archive.in_bounds(features, self.
archive.features_domain)):
220 self.
_counts[
"out_of_domain"] += 1
223 cell = self.
archive.index_grid(features)
225 name=f
"{operator}-{self._counts['candidate_attempts']}",
230 def _admit_candidate(self, candidate):
231 if candidate
is None:
239 """Return cumulative stats. Budget-cut evaluations do not enter the archive."""
241 with _open_environment(self.
_factory)
as env:
242 _check_spaces(env, self.
_actor)
244 while budget.remaining:
245 operator, parameters = self._proposal()
246 self.
_counts[
"candidate_attempts"] += 1
247 if operator !=
"random":
249 self.
_actor._set_parameters(parameters)
250 episodes, returns = [], []
252 episode, values = self.
_collect(cursor, budget)
255 episodes.append(episode)
256 returns.append(values)
259 self.
_counts[
"evaluated_policies"] += 1
268 """Multi-objective MAP-Elites with preference-conditioned policy gradients.
270 A shared actor and twin vector critics learn from step-level objectives.
271 Genetic variation, preference-weighted gradient updates and actor injection
272 supply candidates. Archive admission uses original objective returns.
274 :param env_factory: Factory for a single Gymnasium environment with Box spaces.
275 :param archive: Empty ParetoGrid configured with crowding truncation.
276 :param reward_vector: Callable (observation, action, successor, info)
277 supplying one raw reward for each archive objective.
278 :param descriptor: Callable from a completed Episode to behavior descriptors.
279 :param td3: Optional TD3Config for replay, optimizer, and target settings.
280 :param genetic_offspring: Number of Iso+LineDD candidates per generation.
281 :param pg_offspring: Number of gradient-mutated archive policies per generation.
282 :param injections: Total actor injections per generation. The default
283 reserves one per objective and one random preference.
284 :param critic_steps: Number of learner updates per generation.
285 :param pg_steps: Gradient steps per mutated policy.
286 :param pg_learning_rate: Learning rate for gradient mutation.
287 :param kwargs: Native neural MAP-Elites policy, evaluation, and seed arguments.
290 def __init__(self, env_factory, archive, *, reward_vector, descriptor, td3=None, genetic_offspring=4,
291 pg_offspring=2, injections=None, critic_steps=4, pg_steps=2, pg_learning_rate=.005, **kwargs):
292 if not callable(reward_vector):
293 raise TypeError(
"reward_vector must be callable.")
294 if not 0 < pg_learning_rate < np.inf:
295 raise ValueError(
"pg_learning_rate must be finite and positive.")
296 if "fitness" in kwargs:
297 raise TypeError(
"MOME-P2C uses the vector of measured episode returns.")
299 if not isinstance(self.
td3, TD3Config):
300 raise TypeError(
"td3 must be a TD3Config.")
303 self.
pg_offspring = _integer(pg_offspring,
"pg_offspring", 0)
304 self.
critic_steps, self.
pg_steps = _integer(critic_steps,
"critic_steps"), _integer(pg_steps,
"pg_steps")
306 super().__init__(env_factory, archive, descriptor=descriptor, **kwargs)
308 self.
injections = self.
_objectives + 1
if injections
is None else _integer(injections,
"injections", 0)
310 raise ValueError(
"Allocate at least one candidate per generation.")
312 self.
_conditioned = PreferenceConditionedPolicy._from_layout(
318 np.sign(archive.fitness_weights), self.
_counts,
324 """Return cumulative interactions, update counts, and current replay size."""
329 """Return a standalone actor accepting a simplex preference."""
331 policy = PreferenceConditionedPolicy._from_layout(
332 source._obs_shape, self.
_actor._actions, source._domain, self.
_actor.config, 0,
333 self.
_actor.device
if device
is None else device)
334 policy._model._set_parameters(source._model._parameters())
338 fronts = [front
for front
in self.
archive.solutions.values()
if front]
340 crowding = _crowding_distance([ind.fitness.values
for ind
in front])
341 finite = crowding[np.isfinite(crowding)]
342 weights = np.where(np.isfinite(crowding), crowding, max(1., float(finite.max(initial=0.))))
343 return front[self.
_selection_rng.choice(len(front), p=weights / weights.sum()
if np.any(weights)
else None)]
345 def _improve_parent(self):
347 optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=self.
pg_learning_rate)
348 weights = self.
_learner.preferences(1).expand(self.
td3.batch_size, -1)
350 obs = self.
_replay.sample_observations(self.
td3.batch_size, self.
_learner.rng, actor.device)
351 self.
_learner.improve(actor, optimizer, obs, weights)
352 self.
_counts[
"policy_gradient_steps"] += 1
353 return actor._parameters()
361 if self.
_replay.size < self.
td3.batch_size
or self.
_counts[
"evaluation_steps"] < self.
td3.learning_starts:
372 for preference
in np.concatenate((np.eye(self.
_objectives)[objectives], weights)):
374 self.
_proposals.append((
"actor_injections", actor._parameters()))
:param obj: Slice indicating on which objectives the domination is tested.
A bounded continuous actor that takes a target behavior descriptor.
Count genetic candidates alongside policy gradients and actor injection.
Train preference-conditioned continuous policies for per-cell Pareto fronts.
conditioned_policy(self, *, device=None)
Copy the shared actor for preference-conditioned inference or export.
A portable continuous actor conditioned on a simplex of objective weights.
act(self, observation, preference)
Act using the provided relative objective weights.
specialize(self, preference, *, device=None)
Fold a fixed preference into a standalone continuous actor.
_collect(self, cursor, budget)
train(self, max_env_steps)
Spend an additional budget of environment steps and score completed candidates.
_offer_returns(self, episodes, returns, operator)
_admit_candidate(self, candidate)
improve(self, actor, optimizer, obs, weights, *, shared=False)
_condition(self, obs, weights)
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Architecture of the actor and, for PPO, the separate value network.
Illuminate a fixed QDpy archive by evaluating and mutating neural policies.
policy_for(self, individual, *, device=None, seed=0)
Rebuild an independent inference actor from an archived genome.
_genetic_parameters(self)
_new_actor(self, seed, device=None)
Cumulative optimizer, offspring, and replay counts for off-policy learners.
Settings for the shared TD3 actor, critics, and replay buffer.