QDpy
Loading...
Searching...
No Matches
refqd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Continuous-action RefQD using the native TD3 learner and rollout budget."""
6
7from collections import Counter, deque
8from copy import deepcopy
9from dataclasses import dataclass
10from math import isfinite
11from types import MappingProxyType
12
13import numpy as np
14import torch
15from torch import nn
16
17from qdpy.algorithms.task_search import _validate_grid
18from qdpy.containers import Grid
19from qdpy.phenotype import Features, Fitness, _CellIndividual
20from qdpy.tools import iso_line_dd
21from .policy import ContinuousPolicy, _integer
22from .rollout import _Cursor, _StepBudget, _check_spaces, _evaluate_episode, _open_environment, _seed
23from .td3 import TD3Config, _TD3Learner
24
25__all__ = ["RefQD", "RefQDHead", "RefQDStats", "RefQDAudit"]
26
27
28
29@dataclass(frozen=True, eq=False)
31 """Keep the archived head bytes and its last genuine measurement."""
32
33 parameters: np.ndarray
34 fitness: float
35 descriptor: tuple[float, ...]
36 encoder_version: int
37
38
39
40@dataclass(frozen=True)
42 """Evaluation and refresh steps share the hard training budget."""
43
44 evaluation_steps: int = 0
45 refresh_steps: int = 0
46 candidate_attempts: int = 0
47 evaluated_policies: int = 0
48 refreshed_heads: int = 0
49 refreshes: int = 0
50 generations: int = 0
51 critic_updates: int = 0
52 actor_updates: int = 0
53 policy_gradient_steps: int = 0
54
55 @property
56 def env_steps(self):
57 """Count all steps taken during training."""
58 return self.evaluation_steps + self.refresh_steps
59
60
61
62@dataclass(frozen=True)
64 """Only completed evaluations with the current encoder enter the reporting grid."""
65
66 archive: Grid
67 steps: int
68 evaluated_heads: int
69
70
72 """Borrow the live encoder while exposing only the private head to PG."""
73
74 @classmethod
75 def borrow(cls, shared):
76 actor = cls.__new__(cls)
77 actor.__dict__.update(shared.__dict__)
78 layers = list(shared._network)
79 actor._network = nn.Sequential(*layers[:-1], deepcopy(layers[-1])).eval()
80 return actor
81
82 def _trainable_parameters(self):
83 return tuple(self._network[-1].parameters())
84
85
86def _insert(archive, cell, entry, depth):
87 """Insert a measured head by fitness with stable ties and per-cell identity."""
88 front = archive.setdefault(cell, [])
89 existing = next((i for i, other in enumerate(front) if
90 np.array_equal(entry.parameters, other.parameters)), None)
91 if existing is not None:
92 previous = front[existing]
93 if entry.encoder_version < previous.encoder_version or (
94 entry.encoder_version == previous.encoder_version and entry.fitness <= previous.fitness):
95 return
96 del front[existing]
97 rank = next((i for i, other in enumerate(front) if entry.fitness > other.fitness), len(front))
98 front.insert(rank, entry)
99 del front[depth:]
100
101
102
103class RefQD:
104 """Run RefQD with continuous Box actions and replay-based variation.
105
106 Reuse a caller's empty Grid or CVTGrid as reporting geometry. The
107 training archive stores ranked heads according to their last measured
108 returns. Periodic refreshes replace selected measurements using the
109 current shared encoder. Use audit() to measure current performance.
110
111 :param env_factory: Callable returning a fresh single environment.
112 :param archive: Empty, parentless, best-only reporting geometry.
113 :param descriptor: Function of a completed episode returning descriptor coordinates.
114 :param policy: ContinuousPolicy configuration with at least one hidden layer.
115 :param td3: Optional TD3Config.
116 :param depth: Maximum decision heads in each cell.
117 :param refresh_top: Number of highest-ranked heads to reevaluate per occupied cell.
118 :param refresh_every: Number of generations between re-evaluations.
119 :param batch_size: Offspring per generation.
120 :param critic_steps: TD3 updates per eligible generation.
121 :param pg_steps: Updates for each gradient offspring.
122 :param pg_learning_rate: Adam step size for gradient offspring.
123 :param encoder_decay: Per-generation multiplier for the encoder learning rate.
124 :param max_episode_steps: Hard horizon for one evaluation.
125 :param seed: Local root random seed.
126 :param device: CPU or CUDA for policy and learner networks.
127 """
128
129 def __init__(self, env_factory, archive, *, descriptor, policy=None, td3=None, depth=4, refresh_top=1,
130 refresh_every=50, batch_size=8, critic_steps=16, pg_steps=4, pg_learning_rate=.001, encoder_decay=.995,
131 max_episode_steps=300, seed=0, device="cpu"):
132 _validate_grid(archive)
133 if archive.fitness_score_names or archive.features_score_names or (
134 archive.fitness_weights is not None and archive.fitness_weights[0] <= 0):
135 raise ValueError("Use a maximizing grid with ordinary fitness and descriptors.")
136 if not callable(env_factory) or not callable(descriptor):
137 raise TypeError("Supply environment and descriptor callables.")
138 self.depth = _integer(depth, "depth")
139 self.refresh_top = _integer(refresh_top, "refresh_top")
140 self.refresh_every = _integer(refresh_every, "refresh_every")
141 self.batch_size = _integer(batch_size, "batch_size", 2)
142 self.critic_steps = _integer(critic_steps, "critic_steps")
143 self.pg_steps = _integer(pg_steps, "pg_steps")
144 if not 0 < pg_learning_rate < np.inf:
145 raise ValueError("Use a finite positive policy-gradient step size.")
146 self._pg_rate = pg_learning_rate
147 self._horizon = _integer(max_episode_steps, "max_episode_steps")
148 if self.refresh_top > self.depth or not 0 < encoder_decay <= 1:
149 raise ValueError("refresh_top must fit the archive depth, and encoder_decay must be in (0, 1].")
150 self._decay = encoder_decay
151 self._factory, self._descriptor = env_factory, descriptor
152 self._geometry = deepcopy(archive)
153 self._geometry._set_fitness_weights((1.,))
154 self._cells = {}
155 self._pending = deque()
156 self._refresh_due = False
157 self._version = 0
158 self._counts = Counter()
159 self._selection, self._eval, self._refresh_rng = (
160 np.random.default_rng(s) for s in np.random.SeedSequence(seed).spawn(3))
161 self.td3 = TD3Config() if td3 is None else td3
162 if not isinstance(self.td3, TD3Config):
163 raise TypeError("td3 must be a TD3Config.")
164 with _open_environment(env_factory) as env:
165 self._actor = ContinuousPolicy(env.observation_space, env.action_space,
166 config=policy, seed=_seed(self._selection), device=device)
167 if len(self._actor._network) == 1:
168 raise ValueError("RefQD requires at least one hidden layer for the shared encoder.")
169 self._candidate = _DecisionActor.borrow(self._actor)
170 encoder = tuple(self._actor._network[:-1].parameters())
171 head = tuple(self._actor._network[-1].parameters())
172 self._encoder_bytes = sum(p.numel() * p.element_size() for p in encoder)
173 self._learner = _TD3Learner(self._actor, self.td3, _seed(self._selection), Counter())
174 self._learner.actor_optimizer = torch.optim.Adam(
175 [{"params": encoder}, {"params": head}], lr=self.td3.actor_learning_rate)
176
177 @property
178 def stats(self):
179 """Snapshot training counters, including the TD3 updates."""
180 return RefQDStats(**{field: self._counts[field] + self._learner.counts[field]
181 for field in RefQDStats.__dataclass_fields__})
182
183 @property
184 def heads(self):
185 """Read an immutable snapshot of the ranked heads in occupied cells."""
186 return MappingProxyType({cell: tuple(front) for cell, front in self._cells.items()})
187
188 @property
190 """Return the version shared by candidates in the current generation."""
191 return self._version
192
193 @property
195 """Count the encoder once and the stored float32 decision vectors."""
196 return self._encoder_bytes + sum(e.parameters.nbytes for front in self._cells.values() for e in front)
197
198 def _random_head(self):
199 layer = self._candidate._network[-1]
200 radius = layer.in_features ** -0.5
201 return self._selection.uniform(-radius, radius, size=layer.weight.numel() + layer.bias.numel())
202
203 def _proposals(self):
204 pool = [entry.parameters for front in self._cells.values() for entry in front]
205 if not pool or not self._learner.ready(self._counts["evaluation_steps"] + self._counts["refresh_steps"]):
206 return [self._random_head() for _ in range(self.batch_size)]
207 self._learner.actor_optimizer.param_groups[0]["lr"] = (
208 self.td3.actor_learning_rate * self._decay ** self._counts["generations"])
209 before = self._learner.counts["actor_updates"]
210 for _ in range(self.critic_steps):
211 self._learner.update()
212 self._version += self._learner.counts["actor_updates"] > before
213 proposals = [self._actor._parameters()[-len(pool[0]):]]
214 for _ in range(self.batch_size // 2):
215 a, b = self._selection.integers(len(pool), size=2)
216 proposals.append(iso_line_dd(pool[a], pool[b], rng=self._selection))
217 while len(proposals) < self.batch_size:
218 self._candidate._set_parameters(pool[self._selection.integers(len(pool))])
219 self._learner.improve_offspring(self._candidate, self.pg_steps, self._pg_rate)
220 proposals.append(self._candidate._parameters())
221 return proposals
222
223 def _location(self, episode):
224 descriptor = tuple(map(float, self._descriptor(episode)))
225 fitness = episode.return_
226 if (len(descriptor) != len(self._geometry.features_domain) or not all(map(isfinite, descriptor))
227 or not isfinite(fitness)):
228 raise ValueError("Expected finite fitness and one descriptor per grid axis.")
229 if not self._geometry.in_bounds((fitness,), self._geometry.fitness_domain) or not self._geometry.in_bounds(
230 descriptor, self._geometry.features_domain):
231 return None
232 return self._geometry.index_grid(descriptor), fitness, descriptor
233
234 def _measure(self, episode):
235 location = self._location(episode)
236 if location is None:
237 return None
238 cell, fitness, descriptor = location
239 weights = np.frombuffer(self._candidate._parameters().tobytes(), dtype=np.float32)
240 return cell, RefQDHead(weights, fitness, descriptor, self._version)
241
242 def _refresh(self, cursor, budget):
243 staged = {cell: front[self.refresh_top:] for cell, front in self._cells.items()}
244 for front in self._cells.values():
245 for entry in front[:self.refresh_top]:
246 self._candidate._set_parameters(entry.parameters)
247 episode = _evaluate_episode(cursor, self._candidate, budget, self._learner.record,
248 phase="refresh_steps")
249 if episode is None:
250 return False
251 self._counts["refreshed_heads"] += 1
252 measured = self._measure(episode)
253 if measured is not None:
254 _insert(staged, *measured, self.depth)
255 self._cells = {cell: front for cell, front in staged.items() if front}
256 self._counts["refreshes"] += 1
257 return True
258
259
260 def train(self, max_env_steps):
261 """Return cumulative stats. A budget-cut refresh leaves the archive intact."""
262 budget = _StepBudget(max_env_steps, self._counts)
263 with _open_environment(self._factory) as env:
264 _check_spaces(env, self._actor)
265 cursor = _Cursor(env, self._candidate, self._horizon, self._eval)
266 refresh = _Cursor(env, self._candidate, self._horizon, self._refresh_rng)
267 while budget.remaining:
268 if self._refresh_due:
269 if not self._refresh(refresh, budget):
270 break
271 self._refresh_due = False
272 if not budget.remaining:
273 break
274 if not self._pending:
275 self._pending.extend(self._proposals())
276 self._candidate._set_parameters(self._pending.popleft())
277 self._counts["candidate_attempts"] += 1
278 episode = _evaluate_episode(cursor, self._candidate, budget, self._learner.record)
279 if episode is not None:
280 self._counts["evaluated_policies"] += 1
281 measured = self._measure(episode)
282 if measured is not None:
283 _insert(self._cells, *measured, self.depth)
284 if not self._pending:
285 self._counts["generations"] += 1
286 self._refresh_due = bool(self._cells) and self._counts["generations"] % self.refresh_every == 0
287 return self.stats
288
289
290 def policy_for(self, cell, rank=0, *, device=None):
291 """Reconstruct a policy that can be saved with ContinuousPolicy.save()."""
292 head = self._cells[cell][_integer(rank, "rank", 0)].parameters
293 actor = self._actor._new(0, device)
294 actor._set_parameters(np.concatenate((self._actor._parameters()[:-len(head)], head)))
295 return actor
296
297
298 def audit(self, max_env_steps, *, seed=0):
299 """Return a fresh grid of measured results without changing training state."""
300 archive, counts = deepcopy(self._geometry), Counter()
301 budget = _StepBudget(max_env_steps, counts)
302 candidate = _DecisionActor.borrow(self._actor)
303 completed = 0
304 with _open_environment(self._factory) as env:
305 _check_spaces(env, self._actor)
306 cursor = _Cursor(env, candidate, self._horizon, np.random.default_rng(seed))
307 for front in self._cells.values():
308 head = front[0]
309 candidate._set_parameters(head.parameters)
310 episode = _evaluate_episode(cursor, candidate, budget)
311 if episode is None:
312 break
313 completed += 1
314 location = self._location(episode)
315 if location is not None:
316 cell, fitness, descriptor = location
317 if archive.free >= 1 or archive.solutions[cell]:
318 archive.add(_CellIndividual(head.parameters.tolist(), cell, features=Features(descriptor),
319 fitness=Fitness((fitness,), weights=(1.,))))
320 return RefQDAudit(archive, counts["evaluation_steps"], completed)
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Definition policy.py:337
Independently audited measurements with their environment cost.
Definition refqd.py:63
A measured decision head and the version of its shared encoder.
Definition refqd.py:30
Cumulative RefQD training costs and optimizer activity.
Definition refqd.py:41
Train one shared policy encoder and archive lightweight decision heads.
Definition refqd.py:103
_location(self, episode)
Definition refqd.py:223
audit(self, max_env_steps, *, seed=0)
Measure the top heads using a separate seed and step budget.
Definition refqd.py:298
parameter_bytes(self)
Definition refqd.py:194
encoder_version(self)
Definition refqd.py:189
_refresh(self, cursor, budget)
Definition refqd.py:242
train(self, max_env_steps)
Spend an additional hard budget on offspring and archive refreshes.
Definition refqd.py:260
policy_for(self, cell, rank=0, *, device=None)
Combine the current encoder and a selected head in an independent actor.
Definition refqd.py:290
_measure(self, episode)
Definition refqd.py:234
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25