53 """Use Conti et al.'s shared novelty memory and three search objectives.
55 Each step selects one member with probability proportional to its
56 novelty. Separately rank the probe rewards and novelty scores, then
57 combine their gradient estimates. NS-ES uses only novelty. NSR-ES
58 averages both signals. NSRA-ES starts with reward and lowers its
59 weight as best measured center reward stagnates.
61 :param initial_population: Nonempty matrix of finite parameter vectors.
62 :param mode: ``ns-es``, ``nsr-es``, or ``nsra-es``.
63 :param archive: Optional parentless best-only reporting Grid or CVTGrid.
64 It uses reward maximization and does not affect selection.
65 :param pairs: Number of antithetic Gaussian perturbation pairs per step.
66 :param sigma: Gaussian standard deviation.
67 :param learning_rate: Step size of the per-member Adam update.
68 :param l2: Nonnegative weight decay in the parameter gradient.
69 :param neighbors: Number of nearest measured center descriptors.
70 :param distance: Symmetric nonnegative descriptor distance, default Euclidean.
71 :param history_capacity: Optional maximum number of recent center descriptors.
72 :param patience: Stagnant steps before reducing NSRA-ES reward weight.
73 :param weight_step: Amount to change that weight on a plateau or new best.
74 :param ind_domain: Optional common parameter interval for clipped ES.
75 :param seed: Private seed for selection, perturbations, and evaluations.
78 def __init__(self, initial_population, *, mode="nsra-es", archive=None, pairs=16, sigma=.05,
79 learning_rate=.02, l2=.005, neighbors=10, distance=dist, history_capacity=None,
80 patience=10, weight_step=.05, ind_domain=None, seed=0):
81 points = np.asarray(initial_population, dtype=float)
82 if points.ndim != 2
or not all(points.shape)
or not np.isfinite(points).all():
83 raise ValueError(
"Supply a nonempty matrix of finite parameter vectors.")
84 weights = {
"ns-es": 0.,
"nsr-es": .5,
"nsra-es": 1.}
85 if mode
not in weights:
86 raise ValueError(
"Choose ns-es, nsr-es, or nsra-es.")
87 if not callable(distance)
or not (0 < sigma < np.inf
and 0 < learning_rate < np.inf
88 and 0 <= l2 < np.inf
and 0 < weight_step <= 1):
89 raise ValueError(
"Use a distance callable and finite scales.")
90 if archive
is not None and (
91 not isinstance(archive, Grid)
or archive.parents
or archive.max_items_per_bin != 1
92 or archive.discard_random_on_bin_overload
or len(archive.fitness_domain
or ()) != 1
93 or len(archive.fitness_weights
or ()) != 1
or not 0 < archive.fitness_weights[0] < np.inf
94 or archive.features_score_names
or archive.fitness_score_names):
95 raise ValueError(
"Use a parentless best-only grid with a positive scalar fitness weight and native scores.")
97 self.
_bounds =
None if ind_domain
is None else _bounds(ind_domain)
98 if not np.array_equal(self.
_bounded(points), points):
99 raise ValueError(
"Initial genomes lie outside ind_domain.")
100 self.
_initial = tuple(map(tuple, points))
101 self.
_pairs = _positive_int(pairs,
"pairs")
102 self.
_neighbors, self.
_patience = _positive_int(neighbors,
"neighbors"), _positive_int(patience,
"patience")
105 capacity =
None if history_capacity
is None else _positive_int(history_capacity,
"history_capacity")
106 self.
_history = deque(maxlen=capacity)
109 self.
_steps = np.zeros(len(points), dtype=int)
112 np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
115 self.
_descriptor_size = len(archive.features_domain)
if archive
is not None else None
119 """Return measured centers in population order."""
120 return tuple(row
for row
in self.
_population if row
is not None)
124 """Return the historically best measured center, or None before a successful call."""
129 """Return shared descriptors from committed center measurements."""
134 """Return a snapshot of cumulative costs and current reward weight."""
140 """Return evaluator calls reserved for a probe batch and its center."""
141 return 2 * self.
_pairs + 1
143 def _bounded(self, points):
144 return points
if self.
_bounds is None else np.clip(points, *self.
_bounds)
146 def _observe(self, result, genome):
150 reward, descriptor = result
151 if not isfinite(reward):
152 raise ValueError(
"A policy must return a finite reward.")
153 values = _finite_vector(descriptor,
"Behavior descriptor", self.
_descriptor_size)
157 def _measure(self, evaluate, points, executor, *, center=False):
160 genome = _finite_vector(point,
"Policy parameters")
166 result = evaluate(genome, seed)
if executor
is None else executor.submit(evaluate, genome, seed)
167 results.append((genome, result))
168 return [self.
_observe(result
if executor
is None else result.result(), genome)
for genome, result
in results]
170 def _record(self, slot, row, *, adapt):
173 self.
_history.append(row.descriptor)
176 if archive.in_bounds((row.reward,), archive.fitness_domain)
and archive.in_bounds(
177 row.descriptor, archive.features_domain):
178 archive.add(
Individual(row.genome, fitness=
Fitness((row.reward,), weights=archive.fitness_weights),
180 improved = row
is not None and (self.
_best is None or row.reward > self.
_best.reward)
183 if adapt
and self.
mode ==
"nsra-es":
191 def _novelty(self, descriptor):
193 if any(
not isfinite(value)
or value < 0.
for value
in gaps):
194 raise ValueError(
"Descriptor distances must be finite and nonnegative.")
196 return fsum(value / len(nearest)
for value
in nearest)
198 def _step(self, evaluate, executor):
199 available = [i
for i, row
in enumerate(self.
_population)
if row
is not None]
201 scaled = novelty / (novelty.max()
or 1.)
202 probability = scaled / scaled.sum()
if scaled.any()
else None
203 slot = int(self.
_selection.choice(available, p=probability))
207 probes = self.
_bounded(center + self.
_sigma * np.concatenate((noise, -noise)))
208 rows = self.
_measure(evaluate, probes, executor)
209 if any(row
is None for row
in rows):
210 self.
_record(slot,
None, adapt=
True)
212 gradient = -self.
_l2 * center
214 gradient += self.
_weight * _rank_gradient(noise, [row.reward
for row
in rows], self.
_sigma)
216 values = [self.
_novelty(row.descriptor)
for row
in rows]
217 gradient += (1. - self.
_weight) * _rank_gradient(noise, values, self.
_sigma)
218 mean = .9 * self.
_means[slot] + .1 * gradient
219 variance = .999 * self.
_variances[slot] + .001 * np.square(gradient)
220 step = int(self.
_steps[slot]) + 1
221 proposal = center + self.
_rate * (mean / (1. - .9 ** step)) / (np.sqrt(variance / (1. - .999 ** step)) + 1e-8)
222 if not np.isfinite(proposal).all()
or not np.isfinite(variance).all():
223 raise ValueError(
"The ES step overflowed. Rescale parameters or ES settings.")
224 row, = self.
_measure(evaluate, (self.
_bounded(proposal),), executor, center=
True)
227 self.
_record(slot, row, adapt=
True)
234 def run(self, evaluate, budget, *, executor=None):
235 """Retry initialization if all centers fail and reserve full ES steps."""
236 remaining = _attempt_budget(budget)
246 self.
_step(evaluate, executor)