QDpy
Loading...
Searching...
No Matches
loki.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Train shared controllers while periodically refreshing their design pools."""
7
8from collections import Counter
9from dataclasses import dataclass
10from itertools import cycle
11from math import fsum, isfinite, prod
12from typing import Hashable
13
14from gymnasium import Env, spaces
15from gymnasium.vector import VectorEnv
16import numpy as np
17from sklearn.cluster import KMeans
18from threadpoolctl import threadpool_limits
19
20from qdpy.algorithms._population import _finite_vector
21from .policy import _action_layout, _flatten_observation, _integer, _make_policy, _observation_shape
22from .ppo import PPOConfig, _Learner
23from .rollout import TrainingStats, _Cursor, _StepBudget, _evaluate_episode, _open_environment, _seed
24
25__all__ = ["LOKI", "LOKIStats", "LOKIMeasurement", "LOKIEvaluation"]
26
27
28
29@dataclass(frozen=True)
31 """Count complete rounds, new designs tested, and live-pool replacements."""
32
33 rounds: int = 0
34 design_proposals: int = 0
35 replacements: int = 0
36 rounds_by_cluster: tuple[int, ...] = ()
37
38
39
40@dataclass(frozen=True)
42 """Keep the mean undiscounted return over the common seed panel."""
43
44 cluster: int
45 design: Hashable
46 return_: float
47
48
49
50@dataclass(frozen=True)
52 """Report complete audit rows and only the environment steps used in the audit."""
53
54 measurements: tuple[LOKIMeasurement, ...]
55 steps: int
56
57
59 """Use one underlying environment at a time with a design-conditioned observation."""
60
61 def __init__(self, factory, next_design, obs_shape, obs_space, action_space, action_layout):
62 self._factory, self._next = factory, next_design
63 self._shape, self._action_layout = obs_shape, action_layout
64 self.observation_space, self.action_space = obs_space, action_space
65 self._env = self._active = None
66
67 def _observation(self, observation):
68 return np.concatenate((_flatten_observation(observation, self._shape), self._features))
69
70 def reset(self, *, seed=None, options=None):
71 super().reset(seed=seed)
72 design, self._features = self._next()
73 if self._env is None or design != self._active:
74 self.close()
75 env = self._factory(design)
76 try:
77 if (isinstance(env, VectorEnv) or _observation_shape(env.observation_space) != self._shape
78 or _action_layout(env.action_space) != self._action_layout):
79 raise ValueError("All design environments must have the declared observation shape and action space.")
80 except Exception:
81 env.close()
82 raise
83 self._env, self._active = env, design
84 observation, info = self._env.reset(seed=seed, options=options)
85 return self._observation(observation), info
86
87 def step(self, action):
88 observation, reward, terminated, truncated, info = self._env.step(action)
89 if (terminated or truncated) and "final_observation" in info:
90 info = {**info, "final_observation": self._observation(info["final_observation"])}
91 return self._observation(observation), reward, terminated, truncated, info
92
93 def close(self):
94 if self._env is not None:
95 env, self._env = self._env, None
96 env.close()
97
98
99
100class LOKI:
101 """Train one controller and value model per cluster of design embeddings.
102
103 A round visits one cluster and takes one on-policy PPO update across
104 the current design pool. At configured intervals, evaluate uniformly
105 sampled non-pool designs and incumbents on the current actor using
106 common seeds. Replace the worst incumbents with the best sampled
107 designs before training. Each episode sees its design embedding as
108 part of the observation.
109
110 :param designs: Finite ordered catalog of distinct immutable design identifiers.
111 :param env_factory: Callable (design) returning a fresh single Gymnasium environment.
112 :param descriptor: Callable (design) returning a real vector for clustering and policy conditioning.
113 :param clusters: Number of k-means clusters.
114 :param pool_size: Maximum live designs per cluster.
115 :param search_period: Rounds per cluster between replacements, or None for static pools.
116 :param proposals: Maximum new designs measured in a search round.
117 :param replace_count: Maximum number of incumbents replaced in a search round.
118 :param evaluation_episodes: Common-seed episodes per design during competition.
119 :param max_episode_steps: Shared episode horizon.
120 :param ppo: PPOConfig for the shared actor and critic.
121 :param policy: PolicyConfig for hidden layers.
122 :param seed: Private seed for clustering, proposal draws, training, and evaluation.
123 :param device: PyTorch device.
124 """
125
126 def __init__(self, designs, *, env_factory, descriptor, clusters=2, pool_size=4, search_period=2,
127 proposals=8, replace_count=1, evaluation_episodes=2, max_episode_steps=100,
128 ppo=None, policy=None, seed=0, device="cpu"):
129 self._designs = tuple(designs)
130 if not self._designs or len(set(self._designs)) != len(self._designs):
131 raise ValueError("Supply a nonempty catalog of distinct immutable design identifiers.")
132 if not callable(env_factory) or not callable(descriptor):
133 raise TypeError("Supply callable env_factory and descriptor functions.")
134 self._lookup = {design: i for i, design in enumerate(self._designs)}
135 self._factory, self._descriptor = env_factory, descriptor
136 self._config = PPOConfig() if ppo is None else ppo
137 if not isinstance(self._config, PPOConfig):
138 raise TypeError("ppo must be a PPOConfig.")
139 size, clusters = _integer(pool_size, "pool_size"), _integer(clusters, "clusters")
140 self._period = None if search_period is None else _integer(search_period, "search_period")
141 self._proposals = _integer(proposals, "proposals")
142 self._replace = _integer(replace_count, "replace_count")
143 self._episodes = _integer(evaluation_episodes, "evaluation_episodes")
144 self._horizon = _integer(max_episode_steps, "max_episode_steps")
145 seeds = np.random.SeedSequence(_integer(seed, "seed", 0)).spawn(5)
146 initial, features, self._search_rng, self._train_rng, self._eval_rng = map(np.random.default_rng, seeds)
147 first = _finite_vector(descriptor(self._designs[0]), "Design embedding")
148 self._width = len(first)
149 raw = np.asarray([first, *(_finite_vector(descriptor(design), "Design embedding", self._width)
150 for design in self._designs[1:])])
151 self._scale = np.maximum(1., np.max(abs(raw), axis=0))
152 normalized = raw / self._scale
153 embeddings = self._embeddings = normalized.astype(np.float32)
154 if clusters > len(np.unique(normalized, axis=0)):
155 raise ValueError("clusters cannot exceed the number of distinct design embeddings.")
156 with threadpool_limits(limits=1):
157 model = KMeans(clusters, n_init=5, random_state=_seed(features)).fit(normalized)
158 self._centroids = model.cluster_centers_
159 self._assignments = model.labels_
160 self._groups = tuple(tuple(map(int, np.flatnonzero(model.labels_ == i))) for i in range(clusters))
161 if any(not group for group in self._groups):
162 raise ValueError("Clustering yielded an empty cluster. Rescale the embeddings or use fewer clusters.")
163 self._pools = [list(map(int, initial.choice(group, size=min(size, len(group)), replace=False)))
164 for group in self._groups]
165 with _open_environment(lambda: env_factory(self._designs[0])) as env:
166 self._shape = _observation_shape(env.observation_space)
167 self._action_space = env.action_space
168 self._layout = _action_layout(self._action_space)
169 self._obs_space = spaces.Box(-np.inf, np.inf, shape=(prod(self._shape) + self._width,), dtype=np.float32)
170 with self._environment(lambda: (self._designs[0], embeddings[0])) as proxy:
171 self._learners = [_Learner(_make_policy(proxy, policy, _seed(initial), device, stochastic=True),
172 self._config, _seed(initial)) for _ in self._groups]
173 self._rounds = [0] * clusters
174 self._counts = Counter()
175
176 def _environment(self, next_design):
177 return _open_environment(lambda: _DesignEnvironment(self._factory, next_design, self._shape,
178 self._obs_space, self._action_space, self._layout))
179
180 def _embedding(self, design):
181 if design in self._lookup:
182 return self._embeddings[self._lookup[design]]
183 values = np.asarray(_finite_vector(self._descriptor(design), "Design embedding", self._width)) / self._scale
184 if np.any(np.abs(values) > np.finfo(np.float32).max):
185 raise ValueError("Design embedding lies outside the representable policy input range.")
186 return values
187
188 @property
189 def pools(self):
190 """Return live designs grouped by shared controller index."""
191 return tuple(tuple(self._designs[i] for i in pool) for pool in self._pools)
192
193 @property
195 """Return the coordinate divisors to preserve with exported actors."""
196 return tuple(map(float, self._scale))
197
198 @property
200 """Return cluster centers in normalized embedding coordinates."""
201 return tuple(tuple(map(float, row)) for row in self._centroids)
202
203 @property
204 def stats(self):
205 """Return cumulative training, design search, and replacement costs."""
206 return LOKIStats(**self._counts, rounds_by_cluster=tuple(self._rounds))
207
208
212 def observation(self, design, observation):
213 """Append the normalized design embedding to the raw observation."""
214 return np.concatenate((_flatten_observation(observation, self._shape), self._embedding(design).astype(np.float32)))
215
216
219 def cluster(self, design):
220 """Return the nearest training cluster in normalized embedding space."""
221 if design in self._lookup:
222 return int(self._assignments[self._lookup[design]])
223 return self._nearest(self._embedding(design))
224
225 def _nearest(self, embedding):
226 return int(np.argmin(np.linalg.norm(self._centroids - embedding, axis=1)))
227
228 def _measure(self, learner, design, embedding, budget, seed, episodes):
229 with self._environment(lambda: (design, embedding)) as env:
230 cursor = _Cursor(env, learner.actor, self._horizon, np.random.default_rng(seed))
231 measured = [_evaluate_episode(cursor, learner.actor, budget) for _ in range(episodes)]
232 value = fsum(row.return_ / episodes for row in measured)
233 if not isfinite(value):
234 raise ValueError("Mean return lies outside the representable range.")
235 return value
236
237 def _refresh(self, cluster, outside, count, budget):
238 pool, learner = self._pools[cluster], self._learners[cluster]
239 sampled = list(map(int, self._search_rng.choice(outside, size=count, replace=False)))
240 seed = _seed(self._eval_rng)
241 results = {}
242 for idx in (*pool, *sampled):
243 self._counts["candidate_attempts"] += 1
244 results[idx] = self._measure(learner, self._designs[idx], self._embeddings[idx], budget, seed, self._episodes)
245 self._counts["evaluated_policies"] += 1
246 replace = min(len(pool), count, self._replace)
247 low = sorted(range(len(pool)), key=lambda slot: results[pool[slot]])[:replace]
248 high = sorted(sampled, key=results.__getitem__, reverse=True)[:replace]
249 for slot, candidate in zip(low, high):
250 pool[slot] = candidate
251 self._counts["design_proposals"] += count
252 self._counts["replacements"] += replace
253 self._counts["archive_updates"] += replace
254
255
258 def train(self, max_env_steps):
259 """Reserve the full comparison panel and PPO rollout before starting each round."""
260 limit = _integer(max_env_steps, "max_env_steps", 0)
261 if not limit:
262 return self.stats
263 budget = _StepBudget(limit, self._counts)
264 while budget.remaining:
265 cluster = self._counts["rounds"] % len(self._groups)
266 pool, learner = self._pools[cluster], self._learners[cluster]
267 scheduled = self._period is not None and (self._rounds[cluster] + 1) % self._period == 0
268 active = set(pool)
269 outside = tuple(i for i in self._groups[cluster] if i not in active) if scheduled else ()
270 count = min(self._proposals, len(outside))
271 reserve = (len(pool) + count) * self._episodes * self._horizon if count else 0
272 if budget.remaining < self._config.rollout_steps + reserve:
273 break
274 if count:
275 self._refresh(cluster, outside, count, budget)
276 designs = cycle(self._train_rng.permutation(pool))
277
278 def next_design():
279 idx = int(next(designs))
280 return self._designs[idx], self._embeddings[idx]
281
282 with self._environment(next_design) as env:
283 cursor = _Cursor(env, learner.actor, self._horizon, self._train_rng)
284 learner.update(cursor, budget, self._config.rollout_steps)
285 self._rounds[cluster] += 1
286 self._counts["rounds"] += 1
287 return self.stats
288
289
294 def policy(self, cluster, *, seed=0, device=None):
295 """Copy the actor's measured weights without its critic or optimizer."""
296 actor = self._learners[_integer(cluster, "cluster", 0)].actor
297 clone = actor._new(_integer(seed, "seed", 0), device)
298 clone._set_parameters(actor._parameters())
299 return clone
300
301
306 def evaluate(self, designs=None, *, episodes_per_design=8, seed=1337):
307 """Audit held-out designs by assigning them to the closest training cluster."""
308 episodes = _integer(episodes_per_design, "episodes_per_design")
309 if designs is None:
310 panel = [(cluster, self._designs[idx], self._embeddings[idx])
311 for cluster, pool in enumerate(self._pools) for idx in pool]
312 else:
313 panel = []
314 for design in designs:
315 embedding = self._embedding(design)
316 idx = self._lookup.get(design)
317 cluster = self._nearest(embedding) if idx is None else int(self._assignments[idx])
318 panel.append((cluster, design, embedding.astype(np.float32)))
319 if not panel:
320 return LOKIEvaluation((), 0)
321 counts = Counter()
322 budget = _StepBudget(len(panel) * episodes * self._horizon, counts)
323 rows = tuple(LOKIMeasurement(cluster, design, self._measure(self._learners[cluster], design,
324 embedding, budget, seed, episodes)) for cluster, design, embedding in panel)
325 return LOKIEvaluation(rows, counts["evaluation_steps"])
A separate audit of retained or previously unseen designs.
Definition loki.py:51
An independently measured design with its assigned controller.
Definition loki.py:41
Cumulative PPO and dynamic design search costs.
Definition loki.py:30
Co-design over a finite catalog with local competition and shared PPO policies.
Definition loki.py:100
cluster_centers(self)
Definition loki.py:199
embedding_scale(self)
Definition loki.py:194
_nearest(self, embedding)
Definition loki.py:225
train(self, max_env_steps)
Spend an additional budget in complete round-robin design and PPO updates.
Definition loki.py:258
_environment(self, next_design)
Definition loki.py:176
evaluate(self, designs=None, *, episodes_per_design=8, seed=1337)
Audit designs with fresh episodes and their assigned cluster policies.
Definition loki.py:306
_embedding(self, design)
Definition loki.py:180
_measure(self, learner, design, embedding, budget, seed, episodes)
Definition loki.py:228
cluster(self, design)
Assign an unseen design to the nearest learned cluster center.
Definition loki.py:219
_refresh(self, cluster, outside, count, budget)
Definition loki.py:237
observation(self, design, observation)
Condition a policy input on a design embedding.
Definition loki.py:212
policy(self, cluster, *, seed=0, device=None)
Return an independent serializable actor for a cluster.
Definition loki.py:294
_observation(self, observation)
Definition loki.py:67
Sampling and minibatch settings for the clipped PPO update.
Definition ppo.py:21
Cumulative search costs and evaluated-candidate counts.
Definition rollout.py:51