49 """Implement EDO-CS over numeric policy vectors and a seeded evaluator.
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.
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.
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")
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.")
95 self.
_bounds =
None if ind_domain
is None else _bounds(ind_domain)
98 np.random.default_rng, np.random.SeedSequence(seed).spawn(4))
107 """Return measured policies from oldest to newest."""
112 """Return cumulative attempts and counts of observed arm rewards."""
118 """Return evaluator calls required by the next round, or zero if empty."""
119 distinct = len({row.descriptor
for row
in self.
_archive})
123 def _initial_genome(self):
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.")
131 def _measure(self, evaluate, genome, *, probe=False):
134 result = evaluate(tuple(map(float, genome)), int(self.
_evaluation.integers(2**32)))
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.")
143 return EDOCSPolicy(tuple(map(float, genome)), float(reward), descriptor)
145 def _representatives(self):
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)
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)
161 def _arm(self, scheduled):
162 unmeasured = np.flatnonzero(scheduled == 0)
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))
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.")
175 def _offspring(self, evaluate, parent, weight, reference):
176 center = np.asarray(parent.genome)
177 for _
in range(self.
_steps):
179 candidates = center + self.
_sigma * noise
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):
187 utilities = np.array([row.reward
for row
in rows])
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"):
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)
199 def _offer(self, row):
201 distances = [dist(row.descriptor, old.descriptor)
for old
in self.
_archive]
202 nearest = int(np.argmin(distances))
204 if row.reward > self.
_archive[nearest].reward:
216 def run(self, evaluate, budget):
217 """Reserve each whole round before updating archive or bandit state."""
218 remaining = _attempt_budget(budget)
231 arm = self.
_arm(scheduled)
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: