QDpy
Loading...
Searching...
No Matches
edo_cs.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Black-box EDO-CS with a bounded behavior archive and UCB-controlled ES."""
7
8from dataclasses import dataclass
9from math import dist, fsum, isfinite
10
11import numpy as np
12from sklearn.cluster import KMeans
13
14from ._population import _attempt_budget, _finite_vector
15from .modern import _bounds, _positive_int
16
17__all__ = ["EDOCS", "EDOCSPolicy", "EDOCSStats"]
18
19
20
21@dataclass(frozen=True)
23 """Archive only measurements from initialization and evaluated ES centers."""
24
25 genome: tuple[float, ...]
26 reward: float
27 descriptor: tuple[float, ...]
28
29
30
31@dataclass(frozen=True)
33 """Report attempts, failed slots, completed outer rounds, and UCB feedback counts."""
34
35 policy_evaluations: int
36 perturbation_evaluations: int
37 failures: int
38 rounds: int
39 arm_counts: tuple[int, ...]
40
41 @property
42 def evaluations(self):
43 """Return total evaluator calls."""
44 return self.policy_evaluations + self.perturbation_evaluations
45
46
47
48class EDOCS:
49 """Implement EDO-CS over numeric policy vectors and a seeded evaluator.
50
51 Cluster the current archive with k-means at each round. Always breed
52 the best archived policy, then sample uniformly among the top policies
53 of each other cluster. Estimate raw ES gradients from Gaussian probes
54 against a frozen archive. Use UCB1 on each diversity weight's measured
55 improvement in return. Each accepted offspring is the newest archive
56 entry for FIFO capacity enforcement.
57
58 :param dimension: Number of parameters in each policy vector.
59 :param archive_size: Number of random initialization attempts and maximum live policies.
60 :param clusters: Maximum number of behavioral clusters.
61 :param top_per_cluster: Number of high-reward policies eligible in each other cluster.
62 :param sample: Optional callable (rng) returning initial parameters.
63 The default is uniform within ind_domain or [-1, 1] if unbounded.
64 :param ind_domain: Optional shared finite bounds for clipped ES.
65 :param novelty_neighbors: Number of nearest archived policies in the ES novelty term.
66 :param novelty_threshold: Descriptor radius within which reward decides replacement.
67 :param probes: Independent Gaussian probes per ES update.
68 :param es_steps: ES updates per selected policy before evaluating its final center.
69 :param sigma: Standard deviation of Gaussian perturbations.
70 :param learning_rate: Step size of the raw ES gradient estimator.
71 :param weights: Diversity weights made available as UCB arms.
72 Pass a single value for a fixed-weight ablation.
73 :param ucb_scale: Nonnegative scale of the confidence bonus.
74 :param seed: Seed for initialization, selection, perturbations, and rollouts.
75 """
76
77 def __init__(self, dimension, *, archive_size=32, clusters=5, top_per_cluster=2, sample=None,
78 ind_domain=None, novelty_neighbors=10, novelty_threshold=.05, probes=16,
79 es_steps=5, sigma=.05, learning_rate=.02, weights=(0., .5), ucb_scale=1., seed=0):
80 self._dimension = _positive_int(dimension, "dimension")
81 self._capacity = _positive_int(archive_size, "archive_size")
82 self._clusters = _positive_int(clusters, "clusters")
83 self._top = _positive_int(top_per_cluster, "top_per_cluster")
84 self._neighbors = _positive_int(novelty_neighbors, "novelty_neighbors")
85 self._probes = _positive_int(probes, "probes")
86 self._steps = _positive_int(es_steps, "es_steps")
87 self._weights = _finite_vector(weights, "Diversity weights")
88 if (len(set(self._weights)) != len(self._weights) or any(not 0 <= w <= 1 for w in self._weights)
89 or self._clusters > self._capacity or not 0 <= novelty_threshold < np.inf
90 or not 0 < sigma < np.inf or not 0 < learning_rate < np.inf or not 0 <= ucb_scale < np.inf):
91 raise ValueError("Use valid archive settings, distinct weights in [0, 1], and finite ES scales.")
92 if sample is not None and not callable(sample):
93 raise TypeError("sample must be callable.")
94 self._sample = sample
95 self._bounds = None if ind_domain is None else _bounds(ind_domain)
96 self._threshold, self._sigma, self._rate, self._ucb = novelty_threshold, sigma, learning_rate, ucb_scale
97 self._initial, self._selection, self._variation, self._evaluation = map(
98 np.random.default_rng, np.random.SeedSequence(seed).spawn(4))
99 self._archive = []
100 self._arm_counts = np.zeros(len(self._weights), dtype=int)
101 self._arm_means = np.zeros(len(self._weights))
102 self._initialized = self._policy_calls = self._probe_calls = self._failures = self._rounds = 0
103 self._descriptor_size = None
104
105 @property
106 def archive(self):
107 """Return measured policies from oldest to newest."""
108 return tuple(self._archive)
109
110 @property
111 def stats(self):
112 """Return cumulative attempts and counts of observed arm rewards."""
113 return EDOCSStats(self._policy_calls, self._probe_calls, self._failures,
114 self._rounds, tuple(map(int, self._arm_counts)))
115
116 @property
118 """Return evaluator calls required by the next round, or zero if empty."""
119 distinct = len({row.descriptor for row in self._archive})
120 representatives = min(self._clusters, distinct) or min(1, len(self._archive))
121 return representatives * (self._steps * self._probes + 1)
122
123 def _initial_genome(self):
124 genome = (self._initial.uniform(*(self._bounds or (-1., 1.)), size=self._dimension) if self._sample is None
125 else self._sample(self._initial))
126 vector = _finite_vector(genome, "Policy parameters", self._dimension)
127 if self._bounds is not None and any(not self._bounds[0] <= value <= self._bounds[1] for value in vector):
128 raise ValueError("Initial policy parameters lie outside ind_domain.")
129 return vector
130
131 def _measure(self, evaluate, genome, *, probe=False):
132 self._probe_calls += int(probe)
133 self._policy_calls += int(not probe)
134 result = evaluate(tuple(map(float, genome)), int(self._evaluation.integers(2**32)))
135 if result is None:
136 self._failures += 1
137 return None
138 reward, descriptor = result
139 descriptor = _finite_vector(descriptor, "Behavior descriptor", self._descriptor_size)
140 if not isfinite(reward):
141 raise ValueError("Policy reward must be finite.")
142 self._descriptor_size = len(descriptor)
143 return EDOCSPolicy(tuple(map(float, genome)), float(reward), descriptor)
144
145 def _representatives(self):
146 rows = self._archive
147 positions = np.asarray([row.descriptor for row in rows])
148 groups = min(self._clusters, len({row.descriptor for row in rows}))
149 best = max(range(len(rows)), key=lambda i: rows[i].reward)
150 if groups == 1:
151 return (rows[best],)
152 positions /= np.max(np.abs(positions)) or 1.
153 labels = KMeans(n_clusters=groups, n_init=1, random_state=int(self._selection.integers(2**32))).fit_predict(positions)
154 choices = [rows[best]]
155 for label in np.unique(labels):
156 if label != labels[best]:
157 eligible = sorted(np.flatnonzero(labels == label), key=lambda i: -rows[i].reward)[:self._top]
158 choices.append(rows[int(self._selection.choice(eligible))])
159 return tuple(choices)
160
161 def _arm(self, scheduled):
162 unmeasured = np.flatnonzero(scheduled == 0)
163 if len(unmeasured):
164 return int(unmeasured[0])
165 bonus = self._ucb * np.sqrt(np.log(max(1, scheduled.sum())) / scheduled)
166 return int(np.argmax(self._arm_means + bonus))
167
168 def _novelty(self, row, reference):
169 distances = sorted(dist(row.descriptor, old.descriptor) for old in reference)[:self._neighbors]
170 novelty = fsum(value / len(distances) for value in distances)
171 if not isfinite(novelty):
172 raise ValueError("Novelty is outside the representable range. Rescale descriptors.")
173 return novelty
174
175 def _offspring(self, evaluate, parent, weight, reference):
176 center = np.asarray(parent.genome)
177 for _ in range(self._steps):
178 noise = self._variation.standard_normal((self._probes, self._dimension))
179 candidates = center + self._sigma * noise
180 if self._bounds is not None:
181 candidates = np.clip(candidates, *self._bounds)
182 if not np.isfinite(candidates).all():
183 raise ValueError("An ES probe overflowed. Rescale policy parameters or sigma.")
184 rows = [self._measure(evaluate, candidate, probe=True) for candidate in candidates]
185 if any(row is None for row in rows):
186 continue
187 utilities = np.array([row.reward for row in rows])
188 if weight:
189 utilities = (1. - weight) * utilities + weight * np.array([
190 self._novelty(row, reference) for row in rows])
191 with np.errstate(over="ignore", invalid="ignore"):
192 update = self._rate / self._sigma * ((utilities / self._probes) @ noise)
193 improved = center + update
194 if not np.isfinite(improved).all():
195 raise ValueError("The ES update overflowed. Rescale reward, descriptors, or ES settings.")
196 center = improved if self._bounds is None else np.clip(improved, *self._bounds)
197 return self._measure(evaluate, center)
198
199 def _offer(self, row):
200 if self._archive:
201 distances = [dist(row.descriptor, old.descriptor) for old in self._archive]
202 nearest = int(np.argmin(distances))
203 if distances[nearest] <= self._threshold:
204 if row.reward > self._archive[nearest].reward:
205 del self._archive[nearest]
206 else:
207 return
208 self._archive.append(row)
209 if len(self._archive) > self._capacity:
210 del self._archive[0]
211
212
216 def run(self, evaluate, budget):
217 """Reserve each whole round before updating archive or bandit state."""
218 remaining = _attempt_budget(budget)
219 while remaining and (self._initialized < self._capacity or not self._archive):
220 row = self._measure(evaluate, self._initial_genome())
221 if row is not None:
222 self._archive.append(row)
223 self._initialized += 1
224 remaining -= 1
225 while (cost := self.next_round_cost) and remaining >= cost:
226 before = self._policy_calls + self._probe_calls
227 reference = self.archive
228 scheduled = self._arm_counts.copy()
229 evaluated = []
230 for parent in self._representatives():
231 arm = self._arm(scheduled)
232 scheduled[arm] += 1
233 child = self._offspring(evaluate, parent, self._weights[arm], reference)
234 if child is not None:
235 gain = child.reward - parent.reward
236 if not isfinite(gain):
237 raise ValueError("Policy reward improvement is outside the representable range.")
238 evaluated.append((arm, child, gain))
239 for arm, child, gain in evaluated:
240 self._offer(child)
241 self._arm_counts[arm] += 1
242 count = self._arm_counts[arm]
243 self._arm_means[arm] = self._arm_means[arm] * ((count - 1) / count) + gain / count
244 remaining -= self._policy_calls + self._probe_calls - before
245 self._rounds += 1
246 return self.stats
The measured parameters, return, and descriptor of an archived policy.
Definition edo_cs.py:22
Track policy and perturbation evaluation costs separately.
Definition edo_cs.py:32
Cluster live descriptors and independently update each representative with ES.
Definition edo_cs.py:48
run(self, evaluate, budget)
Measure initialization and as many complete outer rounds as the budget permits.
Definition edo_cs.py:216
_arm(self, scheduled)
Definition edo_cs.py:161
_measure(self, evaluate, genome, *, probe=False)
Definition edo_cs.py:131
_novelty(self, row, reference)
Definition edo_cs.py:168
_offspring(self, evaluate, parent, weight, reference)
Definition edo_cs.py:175