QDpy
Loading...
Searching...
No Matches
sv_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""A compact PyTorch variant of structure–value coupled QD-RL."""
7
8from collections import Counter
9from copy import deepcopy
10from dataclasses import dataclass
11from math import prod
12
13import numpy as np
14import torch
15from torch import nn
16
17from .policy import ContinuousPolicy, PolicyConfig, _integer
18from .rollout import _Cursor, _StepBudget, _check_spaces, _evaluate_episode, _open_environment, _seed
19from .search import NeuralMAPElites
20from .td3 import OffPolicyStats, TD3Config, _TD3Learner, _critic
21
22__all__ = ["SVQDRL", "SVQDStats", "SVBranchSummary"]
23
24
25
26@dataclass(frozen=True)
28 """Replay size counts transitions separately within each retained branch."""
29
30 parameter_proposals: int = 0
31 mask_proposals: int = 0
32 continuations: int = 0
33 branch_updates: int = 0
34 live_branches: int = 0
35 distinct_masks: int = 0
36
37
38
39@dataclass(frozen=True)
41 """The tier indexes sparsity intervals from least to most sparse."""
42
43 cell: tuple[int, ...]
44 tier: int
45 fitness: float
46 descriptor: tuple[float, ...]
47 mask: tuple[bool, ...]
48 sparsity: float
49 value_profile: tuple[float, ...]
50
51
52class _Gate(nn.Module):
53 def __init__(self, bits, device):
54 super().__init__()
55 self.register_buffer("bits", torch.tensor(bits, device=device, dtype=torch.bool))
56
57 def forward(self, values):
58 return values * self.bits
59
60
61@dataclass
62class _Branch:
63 learner: _TD3Learner
64 mask: tuple[bool, ...]
65 steps: int = 0
66
67 @property
68 def actor(self):
69 return self.learner.actor
70
71
72
74 """Train sparse controllers with branch-private critics and memories.
75
76 Alternate diagonal CEM parameter proposals, branch continuation,
77 and Bernoulli mask proposals at explicit sparsity regimes. The
78 bounded training pool retains one branch per descriptor cell and
79 tier. Admission uses raw return and dissimilarity in behaviour, mask,
80 and critic predictions. Nearest-better roots guide continuation.
81 The native grid independently records raw evaluated return.
82
83 :param env_factory: Callable returning a fresh Box/Box environment.
84 :param archive: Empty, parentless, maximizing Grid or CVTGrid.
85 :param descriptor: Descriptor callback on each completed episode.
86 :param policy: PolicyConfig for a deterministic actor with a hidden layer.
87 :param td3: TD3Config for each branch's learning state.
88 :param branch_capacity: Maximum number of retained learning branches.
89 :param training_steps_per_candidate: Training interaction cap per proposal.
90 :param keep_fractions: Mean hidden-neuron keep fractions for mask proposals.
91 :param sparsity_edges: Increasing thresholds between structural tiers.
92 :param novelty_weight: Weight of normalized nearest-branch distance.
93 :param masks: Enable hidden-neuron masking.
94 :param private_critics: Keep a separate TD3 critic pair for each branch.
95 :param evaluation_episodes: Number of complete episodes per measurement.
96 :param max_episode_steps: External rollout horizon.
97 :param seed: Private initialization, proposal, collection, and evaluation seed.
98 :param device: Torch CPU or CUDA device.
99 """
100
101 def __init__(self, env_factory, archive, *, descriptor, policy=None, td3=None, branch_capacity=12,
102 training_steps_per_candidate=48, keep_fractions=(1., .5, .25),
103 sparsity_edges=(.10, .60, .85), novelty_weight=.25, masks=True,
104 private_critics=True, evaluation_episodes=1, max_episode_steps=300, seed=0, device="cpu"):
105 self.config = (TD3Config(replay_capacity=2048, batch_size=32, learning_starts=32,
106 critic_hidden_sizes=(32, 32)) if td3 is None else td3)
107 if not isinstance(self.config, TD3Config):
108 raise TypeError("td3 must be a TD3Config.")
109 if type(masks) is not bool or type(private_critics) is not bool:
110 raise TypeError("masks and private_critics must be Boolean.")
111 fractions, edges = tuple(map(float, keep_fractions)), tuple(map(float, sparsity_edges))
112 if (not fractions or not all(0. < value <= 1. for value in fractions)
113 or not all(lo < hi for lo, hi in zip((0., *edges), (*edges, 1.)))
114 or not 0. <= novelty_weight < np.inf):
115 raise ValueError("Use positive keep fractions, increasing sparsity edges and finite novelty weight.")
116 self._capacity = _integer(branch_capacity, "branch_capacity")
117 self._training_steps = _integer(training_steps_per_candidate, "training_steps_per_candidate")
118 self._fractions, self._edges, self._novelty_weight = fractions, edges, novelty_weight
119 self._masks, self._private = masks, private_critics
120 self._mask_rng = np.random.default_rng(np.random.SeedSequence(_integer(seed, "seed", 0), spawn_key=(4,)))
121 policy = PolicyConfig((32, 32)) if policy is None else policy
122 if not isinstance(policy, PolicyConfig) or not policy.hidden_sizes:
123 raise ValueError("Use a PolicyConfig with at least one hidden layer.")
124 super().__init__(env_factory, archive, descriptor=descriptor, policy=policy,
125 evaluation_episodes=evaluation_episodes, max_episode_steps=max_episode_steps,
126 seed=seed, device=device)
127 domain = np.asarray(archive.features_domain, dtype=float)
128 self._span = domain[:, 1] - domain[:, 0]
129 if not (self._span > 0.).all() or not np.isfinite(self._span).all():
130 raise ValueError("SV-QD-RL requires finite, increasing descriptor intervals.")
131 self._widths = policy.hidden_sizes
132 self._mean = self._actor._parameters().astype(float)
133 self._std = np.full_like(self._mean, .2)
134 self._frequency = np.full(sum(self._widths), .5)
135 self._entries = {}
136 self._shared = self._anchors = None
137
138 def _build_actor(self, env, config, seed, device):
139 return ContinuousPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
140
141 @property
142 def stats(self):
143 """Return real interaction counts, optimizer work, and live state size."""
144 pool = tuple(self._entries.values())
145 return SVQDStats(**self._counts, live_branches=len(pool),
146 distinct_masks=len({entry[0].mask for entry in pool}),
147 replay_size=sum(entry[1].learner.replay.size for entry in pool))
148
149 @property
150 def branches(self):
151 """Return measured branches in cell and tier order."""
152 return tuple(summary for _, (summary, _) in sorted(self._entries.items()))
153
154 def _sample_mask(self, structural):
155 keep = self._mask_rng.choice(self._fractions) if structural else 1.
156 if keep == 1.:
157 return (True,) * len(self._frequency)
158 mask = []
159 for frequency in np.split(self._frequency, np.cumsum(self._widths)[:-1]):
160 probabilities = np.clip(keep + frequency - frequency.mean(), .03, .97)
161 layer = self._mask_rng.random(len(frequency)) < probabilities
162 if not layer.any():
163 layer[int(self._mask_rng.integers(len(layer)))] = True
164 mask.extend(map(bool, layer))
165 return tuple(mask)
166
167 def _new_branch(self, structural):
168 mask = self._sample_mask(structural)
169 actor = self._new_actor(_seed(self._actor_rng))
170 actor._set_parameters(self._selection_rng.normal(self._mean, self._std).astype(np.float32))
171 offset = 0
172 for layer, width in enumerate(self._widths):
173 position = 2 * layer + 1
174 gate = _Gate(mask[offset:offset + width], actor.device)
175 actor._network[position] = nn.Sequential(actor._network[position], gate)
176 offset += width
177 learner = _TD3Learner(actor, self.config, _seed(self._training_rng), Counter())
178 if not self._private:
179 if self._shared is None:
180 self._shared = (learner.critics, learner.critic_targets, learner.critic_optimizer)
181 learner.critics, learner.critic_targets, learner.critic_optimizer = self._shared
182 return _Branch(learner, mask)
183
184 def _continue(self):
185 roots = []
186 for tier in sorted({key[1] for key in self._entries}):
187 group = [entry for key, entry in self._entries.items() if key[1] == tier]
188 distances = [min((self._behaviour(row, other) for other, _ in group
189 if other.fitness > row.fitness), default=np.inf) for row, _ in group]
190 finite = [distance for distance in distances if np.isfinite(distance)]
191 threshold = np.median(finite) if finite else np.inf
192 roots.extend(branch for (_, branch), distance in zip(group, distances, strict=True)
193 if not np.isfinite(distance) or distance > threshold)
194 branch = roots[int(self._selection_rng.integers(len(roots)))]
195 shared = {} if self._shared is None else {id(item): item for item in self._shared}
196 return deepcopy(branch, shared)
197
198 def _collect(self, env, budget, branch):
199 actor, learner = branch.actor, branch.learner
200 cursor = _Cursor(env, actor, self._horizon, self._training_rng)
201 allowed = min(self._training_steps, budget.remaining - self._episodes * self._horizon)
202 old_counts = learner.counts.copy()
203 for _ in range(allowed):
204 if cursor.ended:
205 cursor.reset()
206 observation = cursor.observation
207 with torch.no_grad():
208 mean = actor._normalized(actor._tensor(observation)).cpu().numpy()
209 noise = self._training_rng.normal(0., self.config.exploration_noise, prod(actor._actions.shape))
210 action = actor._decode(np.clip(mean + noise, -1., 1.))
211 recorded = action.copy()
212 reward, terminated, _, _ = cursor.step(action, budget, "training_steps")
213 learner.record(observation, recorded, reward, cursor.observation, terminated)
214 branch.steps += 1
215 if learner.ready(branch.steps):
216 learner.update()
217 self._counts.update(learner.counts - old_counts)
218
219 def _behaviour(self, first, second):
220 return float(np.linalg.norm((np.asarray(first.descriptor) - second.descriptor) / self._span)
221 / np.sqrt(len(self._span)))
222
223 def _score(self, summary, reference):
224 def separation(other):
225 mask = np.mean(np.not_equal(summary.mask, other.mask))
226 values, competitor = np.asarray(summary.value_profile), np.asarray(other.value_profile)
227 profile = np.mean(abs(values - competitor) / (1. + abs(values) + abs(competitor)))
228 return (self._behaviour(summary, other) + mask + profile) / 3.
229
230 return summary.fitness + self._novelty_weight * min(map(separation, reference), default=0.)
231
232 def _admit(self, summary, branch):
233 key = (summary.cell, summary.tier)
234 if key in self._entries or len(self._entries) == self._capacity:
235 rivals = [key] if key in self._entries else []
236 tiers = Counter(tier for _, tier in self._entries)
237 if not rivals:
238 crowded = max(tiers, key=lambda tier: (tiers[tier], -tier))
239 # Retain the only representative of each tier when possible.
240 tier = summary.tier if tiers[summary.tier] == 1 else crowded
241 rivals = [stored for stored in self._entries if stored[1] == tier]
242
243 def score(stored):
244 return self._score(self._entries[stored][0],
245 [item for coordinate, (item, _) in self._entries.items()
246 if coordinate != stored])
247
248 rival = min(rivals, key=score)
249 others = [item for stored, (item, _) in self._entries.items() if stored != rival]
250 if tiers[summary.tier] and self._score(summary, others) <= score(rival):
251 return
252 del self._entries[rival]
253 self._entries[key] = (summary, branch)
254 self._counts["branch_updates"] += 1
255
256 @torch.no_grad()
257 def _folded(self, branch):
258 # Fold hidden gates into the next weights before ordinary actor export.
259 plain = self._new_actor(0)
260 plain._set_parameters(branch.actor._parameters())
261 offset = 0
262 for layer, width in enumerate(self._widths):
263 bits = torch.tensor(branch.mask[offset:offset + width], dtype=torch.bool, device=plain.device)
264 plain._network[2 * (layer + 1)].weight.mul_(bits)
265 offset += width
266 return plain
267
268
269 def branch_policy(self, cell, tier):
270 """Return a standard ContinuousPolicy that supports portable NPZ export."""
271 return self._folded(self._entries[(tuple(cell), tier)][1])
272
273 def _report(self, episodes, branch, phase):
274 quality = float(np.mean([episode.return_ for episode in episodes]))
275 rows = [np.asarray(self._descriptor(episode), dtype=float) for episode in episodes]
276 self._offer(episodes, phase, descriptors=rows, quality=quality, parameters=self._folded(branch)._parameters())
277 descriptor = tuple(map(float, np.mean(rows, axis=0)))
278 if (not self.archive.in_bounds(descriptor, self.archive.features_domain)
279 or not self.archive.in_bounds((quality,), self.archive.fitness_domain)):
280 return
281 if self._anchors is None:
282 self._anchors = branch.actor._tensor(episodes[0].observations[:min(8, episodes[0].steps)])
283 with torch.no_grad():
284 actions = branch.actor._normalized(self._anchors)
285 values = torch.stack([_critic(net, self._anchors, actions) for net in branch.learner.critics])
286 profile = values.mean(dim=0).cpu().tolist()
287 if not np.isfinite(profile).all():
288 raise ValueError("SV-QD-RL critic profiles must be finite.")
289 sparsity = 1. - sum(branch.mask) / len(branch.mask)
290 tier = int(np.searchsorted(self._edges, sparsity, side="right"))
291 cell = self.archive.index_grid(descriptor)
292 self._admit(SVBranchSummary(cell, tier, quality, descriptor, branch.mask, sparsity, tuple(profile)), branch)
293
294 def _fit_proposals(self):
295 rows = sorted(self._entries.values(), key=lambda entry: entry[0].fitness, reverse=True)
296 if rows:
297 top = rows[:max(1, (len(rows) + 1) // 2)]
298 parameters = np.stack([branch.actor._parameters() for _, branch in top])
299 self._mean = .75 * self._mean + .25 * parameters.mean(axis=0, dtype=float)
300 self._std = np.maximum(.04, .75 * self._std + .25 * parameters.std(axis=0, dtype=float))
301 masks = [row.mask for row, _ in rows if row.sparsity > 0.]
302 if masks:
303 selected = masks[:max(1, (len(masks) + 1) // 2)]
304 self._frequency = .75 * self._frequency + .25 * np.mean(selected, axis=0)
305
306
307 def train(self, max_env_steps):
308 """Retain only fully evaluated candidates and account for partial rollouts."""
309 budget = _StepBudget(max_env_steps, self._counts)
310 with _open_environment(self._factory) as env:
311 _check_spaces(env, self._actor)
312 while budget.remaining:
313 turn = self._counts["candidate_attempts"] % 3
314 self._counts["candidate_attempts"] += 1
315 if turn == 1 and self._entries:
316 phase, branch = "continuations", self._continue()
317 else:
318 structural = self._masks and turn == 2
319 phase = "mask_proposals" if structural else "parameter_proposals"
320 branch = self._new_branch(structural)
321 self._counts[phase] += 1
322 self._collect(env, budget, branch)
323 cursor = _Cursor(env, branch.actor, self._horizon, self._evaluation_rng)
324 episodes = [_evaluate_episode(cursor, branch.actor, budget) for _ in range(self._episodes)]
325 if any(episode is None for episode in episodes):
326 break
327 self._counts["evaluated_policies"] += 1
328 self._report(episodes, branch, phase)
329 if turn == 2:
330 self._fit_proposals()
331 return self.stats
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
_offer(self, episodes, emitter, *, descriptors=None, quality=None, parameters=None, candidate_id=None)
Definition search.py:119
_new_actor(self, seed, device=None)
Definition search.py:112
A measured branch's behaviour, return, and structure–value metadata.
Definition sv_qd.py:40
Illuminate continuous behaviours with structure-conditioned TD3 branches.
Definition sv_qd.py:73
_score(self, summary, reference)
Definition sv_qd.py:223
_report(self, episodes, branch, phase)
Definition sv_qd.py:273
train(self, max_env_steps)
Spend a hard real-step budget across training and policy evaluation.
Definition sv_qd.py:307
_sample_mask(self, structural)
Definition sv_qd.py:154
_collect(self, env, budget, branch)
Definition sv_qd.py:198
branch_policy(self, cell, tier)
Copy the controller of a live learning branch, including its mask.
Definition sv_qd.py:269
_new_branch(self, structural)
Definition sv_qd.py:167
_behaviour(self, first, second)
Definition sv_qd.py:219
_folded(self, branch)
Definition sv_qd.py:257
_admit(self, summary, branch)
Definition sv_qd.py:232
Cumulative optimizer and interaction work and the size of the training pool.
Definition sv_qd.py:27
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