QDpy
Loading...
Searching...
No Matches
ccqd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""CCQD for bounded continuous policies and a measured decision archive."""
7
8from collections import Counter, deque
9from copy import deepcopy
10from dataclasses import dataclass
11from math import isfinite, prod
12
13import numpy as np
14import torch
15from torch import nn
16
17from qdpy.algorithms.sampling import _stage_archive
18from qdpy.containers import Grid
19from qdpy.phenotype import Features, Fitness, _CellIndividual
20from qdpy.tools import iso_line_dd
21from .policy import ContinuousPolicy, PolicyConfig, _integer, _mlp
22from .refqd import _DecisionActor
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, _critic,
26 _critic_loss, _polyak, _step_actor)
27
28
29
30@dataclass(frozen=True)
32 """Report step, update, and dormant-representation replacement counts."""
33
34 generations: int = 0
35 representation_replacements: int = 0
36 prefix_steps: int = 0
37
38
39
40@dataclass(frozen=True)
42 """Store measured policies in a fresh native grid of the same geometry."""
43
44 archive: Grid
45 steps: int
46 policies: int
47
48
49def _head_vector(actor):
50 return nn.utils.parameters_to_vector(actor._network[-1].parameters()).detach()
51
52
53def _apply_heads(hidden, heads, actions):
54 weights, bias = heads[:, :-actions], heads[:, -actions:]
55 weights = weights.reshape(len(hidden), actions, hidden.shape[1])
56 return (torch.bmm(weights, hidden.unsqueeze(-1)).squeeze(-1) + bias).tanh()
57
58
60 """Train policy-conditioned TD3 critics for a single representation slot."""
61
62 def __init__(self, actor, config, replay, counts, seed):
63 self.actor, self.config, self.replay, self.counts = actor, config, replay, counts
64 self.rng = np.random.default_rng(seed)
65 self.noise = torch.Generator(device=actor.device).manual_seed(_seed(self.rng))
66 self.action_size = prod(actor._actions.shape)
67 self.head_size = _head_vector(actor).numel()
68 self.encoder = actor._network[:-1]
69 self.target_encoder = deepcopy(self.encoder).requires_grad_(False)
70 width = prod(actor._obs_shape) + self.action_size + self.head_size
71 self.critics = nn.ModuleList(_mlp(width, 1, PolicyConfig(config.critic_hidden_sizes),
72 _seed(self.rng), actor.device, nn.ReLU) for _ in range(2))
73 self.targets = deepcopy(self.critics).requires_grad_(False)
74 self.actor_optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=config.actor_learning_rate)
75 self.critic_optimizer = torch.optim.Adam(self.critics.parameters(), lr=config.critic_learning_rate)
76 self.updates = 0
77
78 def update(self, heads):
79 config, actor = self.config, self.actor
80 state, action, rewards, next_state, terminated = self.replay.sample(
81 config.batch_size, self.rng, actor.device)
82 head = actor._tensor(heads[self.rng.integers(len(heads), size=len(state))])
83 critic_state = torch.cat((state, head), dim=-1)
84 with torch.no_grad():
85 noise = torch.randn(action.shape, generator=self.noise, device=actor.device)
86 noise = (noise * config.target_noise).clamp(-config.noise_clip, config.noise_clip)
87 next_actions = (_apply_heads(self.target_encoder(next_state), head, self.action_size) + noise).clamp(-1, 1)
88 target_state = torch.cat((next_state, head), dim=-1)
89 first, second = (_critic(target, target_state, next_actions) for target in self.targets)
90 target = _bellman_target(rewards, terminated, first, second, config.gamma)
91 loss = _critic_loss(self.critics, critic_state, action, target)
92 self.critic_optimizer.zero_grad(set_to_none=True)
93 loss.backward()
94 _checked_step(self.critic_optimizer)
95 self.updates += 1
96 self.counts["critic_updates"] += 1
97 self.counts["optimizer_steps"] += 1
98 if self.updates % config.policy_delay == 0:
99 hidden = self.encoder(state)
100 cooperative = _apply_heads(hidden, head, self.action_size)
101 greedy_head = _head_vector(actor).expand(len(state), -1)
102 greedy_state = torch.cat((state, greedy_head), dim=-1)
103 greedy = actor._network[-1](hidden).tanh()
104 loss = -.5 * (_critic(self.critics[0], critic_state, cooperative).mean()
105 + _critic(self.critics[0], greedy_state, greedy).mean())
106 if not torch.isfinite(loss):
107 raise ValueError("CCQD produced a nonfinite representation loss.")
108 parameters = actor._trainable_parameters()
109 for parameter, grad in zip(parameters, torch.autograd.grad(loss, parameters)):
110 parameter.grad = grad
111 _checked_step(self.actor_optimizer)
112 _polyak(self.encoder, self.target_encoder, config.tau)
113 _polyak(self.critics, self.targets, config.tau)
114 self.counts["actor_updates"] += 1
115 self.counts["optimizer_steps"] += 1
116
117 def improve(self, head, steps):
118 actor = _DecisionActor.borrow(self.actor)
119 actor._set_parameters(head)
120 optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=self.config.actor_learning_rate)
121 for _ in range(steps):
122 state = self.replay.sample_observations(self.config.batch_size, self.rng, actor.device)
123 context = _head_vector(actor).expand(len(state), -1)
124 _step_actor(actor, optimizer, self.critics[0], state,
125 critic_observations=torch.cat((state, context), dim=-1))
126 self.counts["policy_gradient_steps"] += 1
127 self.counts["optimizer_steps"] += 1
128 return actor._parameters()
129
130 def replace_from(self, other):
131 self.actor._network.load_state_dict(other.actor._network.state_dict())
132 self.target_encoder.load_state_dict(other.target_encoder.state_dict())
133 self.critics.load_state_dict(other.critics.state_dict())
134 self.targets.load_state_dict(other.targets.state_dict())
135 self.actor_optimizer.state.clear()
136 self.critic_optimizer.state.clear()
137 self.updates = 0
138
139
140
141class CCQD:
142 """Cooperatively evolve fixed-layout deterministic Box policies.
143
144 Each representation has a greedy actor and policy-conditioned twin
145 TD3 critics. The critics consume raw decision-head weights as context,
146 with shared environment replay. At each generation archived heads
147 pair with current representations. Decision variation uses Iso+LineDD
148 or actor gradients. The fixed reporting archive stores the measured
149 full policy weights, so changing a representation cannot mutate
150 previously measured policies.
151
152 :param env_factory: Factory for a single Gymnasium environment.
153 :param archive: Empty parentless maximizing Grid or CVTGrid.
154 :param descriptor: Callback mapping a complete episode to its measured descriptors.
155 :param policy: PolicyConfig with at least one hidden layer.
156 :param td3: TD3Config for all representation learners.
157 :param representations: Number of live policy representations.
158 :param batch_size: Completed policies per generation, at least the number of representations.
159 :param critic_steps: TD3 minibatch updates per representation per eligible generation.
160 :param pg_steps: Gradient updates of each gradient offspring.
161 :param iso_sigma: Independent Iso+LineDD noise for genetic heads.
162 :param line_sigma: Shared direction noise for genetic heads.
163 :param max_episode_steps: Hard maximum steps per episode.
164 :param seed: Separate seed streams for initialization and rollouts.
165 :param device: CPU or CUDA Torch device.
166 """
167
168 def __init__(self, env_factory, archive, *, descriptor, policy=None, td3=None, representations=3,
169 batch_size=12, critic_steps=4, pg_steps=2, iso_sigma=.02, line_sigma=.2,
170 max_episode_steps=300, seed=0, device="cpu"):
171 NeuralMAPElites._validate_archive(archive)
172 if not callable(env_factory) or not callable(descriptor):
173 raise TypeError("env_factory and descriptor must be callable.")
174 if not 0. <= iso_sigma < np.inf or not 0. <= line_sigma < np.inf:
175 raise ValueError("Use finite nonnegative mutation scales.")
176 self._factory, self._descriptor, self.archive = env_factory, descriptor, archive
177 self._iso_sigma, self._line_sigma = iso_sigma, line_sigma
178 self._count = _integer(representations, "representations", 2)
179 self._batch = _integer(batch_size, "batch_size", self._count)
180 self._critic_steps = _integer(critic_steps, "critic_steps")
181 self._pg_steps = _integer(pg_steps, "pg_steps")
182 self._horizon = _integer(max_episode_steps, "max_episode_steps")
183 self._config = TD3Config() if td3 is None else td3
184 if not isinstance(self._config, TD3Config):
185 raise TypeError("td3 must be a TD3Config.")
186 self._rng, self._rollouts = (np.random.default_rng(stream) for stream in
187 np.random.SeedSequence(_integer(seed, "seed", 0)).spawn(2))
188 with _open_environment(env_factory) as env:
189 self._actor = ContinuousPolicy(env.observation_space, env.action_space, config=policy,
190 seed=_seed(self._rng), device=device)
191 if not self._actor.config.hidden_sizes:
192 raise ValueError("Use at least one hidden layer for the shared representation.")
193 self._counts = Counter()
194 self._replay = _Replay(self._config.replay_capacity, prod(self._actor._obs_shape),
195 prod(self._actor._actions.shape))
196 self._learners = [_RepresentationLearner(self._actor._new(_seed(self._rng)), self._config,
197 self._replay, self._counts, _seed(self._rng))
198 for _ in range(self._count)]
199 self._head_size = self._learners[0].head_size
200 self._queue, self._measured = deque(), []
201
202 @property
203 def stats(self):
204 """Return cumulative costs, including all representation learner updates."""
205 return CCQDStats(**self._counts, replay_size=self._replay.size)
206
207 @property
209 """Count archived full policies associated with each representation slot."""
210 counts = Counter(ind.scores["ccqd_representation"] for ind in self.archive)
211 return tuple(counts[i] for i in range(self._count))
212
213 def _plan(self):
214 ready = (len(self.archive) and self._replay.size >= self._config.batch_size
215 and self._counts["evaluation_steps"] >= self._config.learning_starts)
216 if ready:
217 pool = np.asarray([ind[-self._head_size:] for ind in self.archive], dtype=np.float32)
218 for learner in self._learners:
219 for _ in range(self._critic_steps):
220 learner.update(pool)
221 encoders = [learner.actor._parameters()[:-self._head_size] for learner in self._learners]
222 head_radius = self._actor._network[-1].in_features ** -.5
223 for index in range(self._batch):
224 slot = int(self._rng.integers(self._count)) if ready else index % self._count
225 learner = self._learners[slot]
226 if ready:
227 first, second = self._rng.integers(len(pool), size=2)
228 if index % 2:
229 head = learner.improve(pool[first], self._pg_steps)
230 gradient = True
231 else:
232 head = iso_line_dd(pool[first], pool[second], iso_sigma=self._iso_sigma,
233 line_sigma=self._line_sigma, rng=self._rng)
234 gradient = False
235 else:
236 head = self._rng.uniform(-head_radius, head_radius, size=self._head_size)
237 gradient = False
238 parameters = np.concatenate((encoders[slot], head))
239 self._queue.append((slot, parameters.astype(np.float32), gradient))
240
241 def _measure(self, archive, episode):
242 descriptor = np.asarray(self._descriptor(episode), dtype=float)
243 quality = episode.return_
244 if (descriptor.shape != (len(archive.features_domain),) or not np.isfinite(descriptor).all()
245 or not isfinite(quality)):
246 raise ValueError("CCQD needs finite return and a descriptor for each grid dimension.")
247 if not (archive.in_bounds((quality,), archive.fitness_domain)
248 and archive.in_bounds(descriptor, archive.features_domain)):
249 return None
250 return quality, tuple(descriptor)
251
252 @staticmethod
253 def _offer(archive, measurement, parameters, representation):
254 quality, descriptor = measurement
255 cell = archive.index_grid(descriptor)
256 if archive.free < 1 and not archive.solutions[cell]:
257 return False
258 return archive.add(_CellIndividual(parameters.tolist(), cell, fitness=Fitness((quality,), weights=(1.,)),
259 features=Features(descriptor),
260 scores={"ccqd_representation": representation})) is not None
261
262 def _finish(self):
263 for slot, parameters, measurement in self._measured:
264 self._counts["archive_updates"] += self._offer(self.archive, measurement, parameters, slot)
265 self._measured.clear()
266 counts = self.representation_counts
267 if any(counts):
268 source = int(np.argmax(counts))
269 for slot, count in enumerate(counts):
270 if not count:
271 self._learners[slot].replace_from(self._learners[source])
272 self._counts["representation_replacements"] += 1
273 self._counts["generations"] += 1
274
275 def _record(self, observation, action, reward, successor, terminated):
276 self._replay.add(observation, self._actor._encode(action), reward, successor, terminated)
277
278
279 def train(self, max_env_steps):
280 """Retain replay from budget-cut episodes and retry their candidates."""
281 budget = _StepBudget(max_env_steps, self._counts)
282 with _open_environment(self._factory) as env:
283 _check_spaces(env, self._actor)
284 cursor = _Cursor(env, self._actor, self._horizon, self._rollouts)
285 while budget.remaining:
286 if not self._queue:
287 self._plan()
288 slot, parameters, gradient = self._queue[0]
289 self._actor._set_parameters(parameters)
290 self._counts["candidate_attempts"] += 1
291 before = budget.remaining
292 episode = _evaluate_episode(cursor, self._actor, budget, on_transition=self._record)
293 if episode is None:
294 self._counts["prefix_steps"] += before - budget.remaining
295 break
296 measurement = self._measure(self.archive, episode)
297 self._counts["evaluated_policies"] += 1
298 self._counts["pg_offspring"] += gradient
299 self._queue.popleft()
300 if measurement is None:
301 self._counts["out_of_domain"] += 1
302 else:
303 self._measured.append((slot, parameters, measurement))
304 if not self._queue:
305 self._finish()
306 return self.stats
307
308
309 def policy_for(self, individual, *, device=None):
310 """Return a portable ContinuousPolicy with the original measured weights."""
311 actor = self._actor._new(0, device)
312 actor._set_parameters(individual)
313 return actor
314
315
316 def best_policy(self, *, device=None):
317 """Return an independently exportable actor after at least one archive admission."""
318 if self.archive.best is None:
319 raise RuntimeError("The decision archive has no measured elite.")
320 return self.policy_for(self.archive.best, device=device)
321
322
323 def audit(self, max_env_steps, *, seed=0):
324 """Return fresh measured placements without updating replay or the decision archive."""
325 archive = _stage_archive(self.archive)
326 archive.clear()
327 counts = Counter()
328 budget = _StepBudget(max_env_steps, counts)
329 actor = self._actor._new(0)
330 episodes = 0
331 with _open_environment(self._factory) as env:
332 _check_spaces(env, actor)
333 rng = np.random.default_rng(_integer(seed, "seed", 0))
334 for record in self.archive:
335 actor._set_parameters(record)
336 cursor = _Cursor(env, actor, self._horizon, rng)
337 episode = _evaluate_episode(cursor, actor, budget)
338 if episode is None:
339 break
340 episodes += 1
341 measurement = self._measure(archive, episode)
342 if measurement is not None:
343 self._offer(archive, measurement, actor._parameters(), record.scores["ccqd_representation"])
344 return CCQDAudit(archive, counts["evaluation_steps"], episodes)
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405
Independently measured CCQD elites and the cost of their audit.
Definition ccqd.py:41
Count representation training and completed decision archive generations.
Definition ccqd.py:31
Combine live representations with archived decision heads and measure the resulting policies.
Definition ccqd.py:141
_finish(self)
Definition ccqd.py:262
audit(self, max_env_steps, *, seed=0)
Remeasure archived full policies with separate reset and interaction budgets.
Definition ccqd.py:323
train(self, max_env_steps)
Train on an additional hard environment-step budget.
Definition ccqd.py:279
list _head_size
Definition ccqd.py:199
_record(self, observation, action, reward, successor, terminated)
Definition ccqd.py:275
_measure(self, archive, episode)
Definition ccqd.py:241
policy_for(self, individual, *, device=None)
Recover a complete measured actor from the decision archive.
Definition ccqd.py:309
tuple _rollouts
Definition ccqd.py:186
best_policy(self, *, device=None)
Recover the highest-return archived policy.
Definition ccqd.py:316
representation_counts(self)
Definition ccqd.py:208
_offer(archive, measurement, parameters, representation)
Definition ccqd.py:253
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
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