QDpy
Loading...
Searching...
No Matches
mome_p2c.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Train policies for different objective trade-offs in each descriptor cell."""
6
7from collections import deque
8from copy import deepcopy
9from dataclasses import dataclass
10from math import prod
11
12import numpy as np
13import torch
14from torch import nn
15from torch.nn import functional as F
16
17from qdpy.containers import ParetoGrid
18from qdpy.containers.pareto import _crowding_distance
19from qdpy.phenotype import Features, Fitness, _CellIndividual
20
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
26
27__all__ = ["MOMEP2C", "MOMEP2CStats", "PreferenceConditionedPolicy"]
28
29
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()
36
37
38
40 """Use nonnegative preferences summing to one to choose an objective trade-off."""
41
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)
45
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)
50
51
52 def act(self, observation, preference):
53 """Return an action in the physical action-space units."""
54 return super().act(observation, _preference(preference, len(self.descriptor_domain)))
55
56
57 def specialize(self, preference, *, device=None):
58 """Return an independent unconditioned actor for one preference."""
59 return super().specialize(_preference(preference, len(self.descriptor_domain)), device=device)
60
61
62
63@dataclass(frozen=True)
65 """Cumulative interaction, optimizer, Pareto admission and replay counts."""
66
67 genetic_offspring: int = 0
68
69
71 """Keep raw objective vectors in replay and maintain running reward moments."""
72
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)
76 self.count = 0
77 self.mean = np.zeros(objectives)
78 self.m2 = np.zeros(objectives)
79
80 def add_episode(self, actor, episode, rewards):
81 count = episode.steps
82 start = max(0, count - self.capacity)
83 rows = (self.position + np.arange(start, count)) % self.capacity
84 observations = episode.observations.reshape(count + 1, -1)
85 actions = np.asarray(episode.actions, dtype=np.float64).reshape(count, -1)
86 self.observations[rows], self.next_observations[rows] = observations[start:-1], observations[start + 1:]
87 self.actions[rows] = actor._encode_actions(actions[start:])
88 self.rewards[rows] = rewards[start:]
89 self.terminated[rows] = False
90 self.terminated[rows[-1]] = episode.terminated
91 self.position = (self.position + count) % self.capacity
92 self.size = min(self.size + count, self.capacity)
93
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
99 self.count = total
100
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
106
107
108def _scalar_values(network, conditioned, actions, preference):
109 vector = network(torch.cat((conditioned, actions), dim=-1))
110 return (vector * preference).sum(dim=-1)
111
112
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)
117
118
120 """Learn one actor and twin vector-valued critics across preferences."""
121
122 def __init__(self, shared, replay, td3, direction, counts, seed):
123 self.actor, self.replay, self.config, self.counts = shared, replay, td3, counts
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)
129 self.critics = nn.ModuleList([_mlp(units, self.width, PolicyConfig(td3.critic_hidden_sizes),
130 _seed(self.rng), shared.device, nn.ReLU) for _ in range(2)])
131 self.targets = deepcopy(self.critics).requires_grad_(False)
132 self.actor_target = deepcopy(shared._network).requires_grad_(False)
133 self.critic_optimizer = torch.optim.Adam(self.critics.parameters(), lr=td3.critic_learning_rate)
134 self.actor_optimizer = torch.optim.Adam(shared._trainable_parameters(), lr=td3.actor_learning_rate)
135
136 def preferences(self, count):
137 return self.actor._tensor(self.rng.dirichlet(np.ones(self.width), size=count))
138
139 def _condition(self, obs, weights):
140 return torch.cat((obs, 2 * weights - 1), dim=-1)
141
142 def improve(self, actor, optimizer, obs, weights, *, shared=False):
143 conditioned = self._condition(obs, weights)
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
153
154 def update(self):
155 td3 = self.config
156 obs, actions, rewards, successors, terminated = self.replay.sample(
157 td3.batch_size, self.rng, self.actor.device)
158 weights = self.preferences(td3.batch_size)
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.")
170 self.critic_optimizer.zero_grad(set_to_none=True)
171 loss.backward()
172 _checked_step(self.critic_optimizer)
173 self.counts["critic_updates"] += 1
174 self.counts["optimizer_steps"] += 1
175 if self.counts["critic_updates"] % td3.policy_delay == 0:
176 self.improve(self.actor, self.actor_optimizer, obs, weights, shared=True)
177 self.counts["actor_updates"] += 1
178 _polyak(self.actor._network, self.actor_target, td3.tau)
179 _polyak(self.critics, self.targets, td3.tau)
180
181
183 """Share continuous rollouts and vector return admission between MOME methods."""
184
185 @staticmethod
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'.")
190
191 def _build_actor(self, env, config, seed, device):
192 return ContinuousPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
193
194 def _collect(self, cursor, budget):
195 rewards = []
196
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)
203
204 episode = _evaluate_episode(cursor, self._actor, budget, transition_info=record)
205 if episode is None:
206 return None, None
207 rows = np.stack(rewards)
208 self._replay.add_episode(self._actor, episode, rows)
209 return episode, rows.sum(axis=0)
210
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
221 self._admit_candidate(None)
222 return
223 cell = self.archive.index_grid(features)
224 candidate = _CellIndividual(self._actor._parameters().tolist(), cell,
225 name=f"{operator}-{self._counts['candidate_attempts']}",
226 fitness=Fitness(values, weights=self.archive.fitness_weights),
227 features=Features(features))
228 self._admit_candidate(candidate)
229
230 def _admit_candidate(self, candidate):
231 if candidate is None:
232 return
233 before = self.archive.nb_added
234 self.archive.add(candidate)
235 self._counts["archive_updates"] += self.archive.nb_added - before
236
237
238 def train(self, max_env_steps):
239 """Return cumulative stats. Budget-cut evaluations do not enter the archive."""
240 budget = _StepBudget(max_env_steps, self._counts)
241 with _open_environment(self._factory) as env:
242 _check_spaces(env, self._actor)
243 cursor = _Cursor(env, self._actor, self._horizon, self._evaluation_rng)
244 while budget.remaining:
245 operator, parameters = self._proposal()
246 self._counts["candidate_attempts"] += 1
247 if operator != "random":
248 self._counts[operator] += 1
249 self._actor._set_parameters(parameters)
250 episodes, returns = [], []
251 for _ in range(self._episodes):
252 episode, values = self._collect(cursor, budget)
253 if episode is None:
254 break
255 episodes.append(episode)
256 returns.append(values)
257 if len(episodes) != self._episodes:
258 break
259 self._counts["evaluated_policies"] += 1
260 self._offer_returns(episodes, returns, operator)
261 if self._on_step is not None:
262 self._on_step(self.archive, self.stats)
263 return self.stats
264
265
266
268 """Multi-objective MAP-Elites with preference-conditioned policy gradients.
269
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.
273
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.
288 """
289
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.")
298 self.td3 = TD3Config() if td3 is None else td3
299 if not isinstance(self.td3, TD3Config):
300 raise TypeError("td3 must be a TD3Config.")
301 self.reward_vector = reward_vector
302 self.genetic_offspring = _integer(genetic_offspring, "genetic_offspring", 0)
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")
305 self.pg_learning_rate = pg_learning_rate
306 super().__init__(env_factory, archive, descriptor=descriptor, **kwargs)
307 self._objectives = len(archive.fitness_domain)
308 self.injections = self._objectives + 1 if injections is None else _integer(injections, "injections", 0)
309 if not self.genetic_offspring + self.pg_offspring + self.injections:
310 raise ValueError("Allocate at least one candidate per generation.")
311 domain = _DescriptorDomain(((0., 1.),) * self._objectives)
312 self._conditioned = PreferenceConditionedPolicy._from_layout(
313 self._actor._obs_shape, self._actor._actions, domain, self._actor.config,
314 _seed(self._training_rng), self._actor.device,
315 )
316 self._replay = _VectorReplay(self.td3.replay_capacity, self._actor, self._objectives)
317 self._learner = _PreferenceLearner(self._conditioned._model, self._replay, self.td3,
318 np.sign(archive.fitness_weights), self._counts,
319 _seed(self._training_rng))
320 self._proposals = deque()
321
322 @property
323 def stats(self):
324 """Return cumulative interactions, update counts, and current replay size."""
325 return MOMEP2CStats(**self._counts, replay_size=self._replay.size)
326
327
328 def conditioned_policy(self, *, device=None):
329 """Return a standalone actor accepting a simplex preference."""
330 source = self._conditioned
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())
335 return policy
336
337 def _parent(self):
338 fronts = [front for front in self.archive.solutions.values() if front]
339 front = fronts[self._selection_rng.integers(len(fronts))]
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)]
344
345 def _improve_parent(self):
346 actor = self.policy_for(self._parent())
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)
349 for _ in range(self.pg_steps):
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()
354
355 def _proposal(self):
356 if self._proposals:
357 return self._proposals.popleft()
358 if not self._can_select():
359 return "random", self._new_actor(_seed(self._actor_rng))._parameters()
360 if self.pg_offspring or self.injections:
361 if self._replay.size < self.td3.batch_size or self._counts["evaluation_steps"] < self.td3.learning_starts:
362 return "random", self._new_actor(_seed(self._actor_rng))._parameters()
363 for _ in range(self.critic_steps):
364 self._learner.update()
365 self._proposals.extend(("genetic_offspring", self._genetic_parameters()) for _ in range(self.genetic_offspring))
366 self._proposals.extend(("pg_offspring", self._improve_parent()) for _ in range(self.pg_offspring))
367 if self.injections:
368 count = min(self.injections, self._objectives)
369 objectives = (np.arange(self._objectives) if count == self._objectives
370 else self._training_rng.choice(self._objectives, count, replace=False))
371 weights = self._learner.preferences(self.injections - count).cpu().numpy()
372 for preference in np.concatenate((np.eye(self._objectives)[objectives], weights)):
373 actor = self._conditioned.specialize(preference)
374 self._proposals.append(("actor_injections", actor._parameters()))
375 return self._proposals.popleft()
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405
A bounded continuous actor that takes a target behavior descriptor.
Count genetic candidates alongside policy gradients and actor injection.
Definition mome_p2c.py:64
Train preference-conditioned continuous policies for per-cell Pareto fronts.
Definition mome_p2c.py:267
conditioned_policy(self, *, device=None)
Copy the shared actor for preference-conditioned inference or export.
Definition mome_p2c.py:328
A portable continuous actor conditioned on a simplex of objective weights.
Definition mome_p2c.py:39
act(self, observation, preference)
Act using the provided relative objective weights.
Definition mome_p2c.py:52
specialize(self, preference, *, device=None)
Fold a fixed preference into a standalone continuous actor.
Definition mome_p2c.py:57
_collect(self, cursor, budget)
Definition mome_p2c.py:194
train(self, max_env_steps)
Spend an additional budget of environment steps and score completed candidates.
Definition mome_p2c.py:238
_offer_returns(self, episodes, returns, operator)
Definition mome_p2c.py:211
improve(self, actor, optimizer, obs, weights, *, shared=False)
Definition mome_p2c.py:142
_condition(self, obs, weights)
Definition mome_p2c.py:139
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Definition policy.py:337
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Illuminate a fixed QDpy archive by evaluating and mutating neural policies.
Definition search.py:24
policy_for(self, individual, *, device=None, seed=0)
Rebuild an independent inference actor from an archived genome.
Definition search.py:226
_new_actor(self, seed, device=None)
Definition search.py:112
Cumulative optimizer, offspring, and replay counts for off-policy learners.
Definition td3.py:76
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25