81 """Compute one determinant for each simultaneous population perturbation.
83 For each perturbation index, measure all members and compute one
84 shared diversity score. Mix separate centered ranks of reward and
85 diversity in the antithetic ES gradients. Each member uses its own
86 Adam moments. Reevaluate all proposed centers before committing a
87 round. A fixed diversity_weight of zero runs independent ES updates.
88 Set diversity_weight to None to use Beta-Bernoulli Thompson sampling
89 with weights 0 and 0.5 and an increase in best center reward as feedback.
91 :param initial_population: At least two finite initial parameter vectors of equal length.
92 :param pairs: Antithetic perturbation pairs per round and member.
93 :param sigma: Standard deviation of each Gaussian perturbation.
94 :param learning_rate: Adam update size.
95 :param diversity_weight: Proportion of the diversity gradient in [0, 1] or None for adaptation.
96 :param bandwidth: RBF length scale in embedding coordinates.
97 :param ridge: Diagonal stabilization added to the Gram matrix.
98 :param ind_domain: Optional common inclusive parameter bounds.
99 :param seed: Private seed for Gaussian probes, weighting, and evaluations.
102 def __init__(self, initial_population, *, pairs=8, sigma=.05, learning_rate=.03, diversity_weight=None,
103 bandwidth=1., ridge=1e-6, ind_domain=None, seed=0):
104 population = np.asarray(initial_population, dtype=float).copy()
105 if (population.ndim != 2
or len(population) < 2
or not population.shape[1]
106 or not np.isfinite(population).all()):
107 raise ValueError(
"Supply at least two finite initial vectors of equal positive length.")
108 if not (0 < sigma < np.inf
and 0 < learning_rate < np.inf
109 and (diversity_weight
is None or 0 <= diversity_weight <= 1)):
110 raise ValueError(
"Use positive finite ES scales and a diversity weight in [0, 1] or None.")
111 _kernel_settings(bandwidth, ridge)
112 self.
_bounds =
None if ind_domain
is None else _bounds(ind_domain)
113 if not np.array_equal(self.
_bounded(population), population):
114 raise ValueError(
"The initial population lies outside ind_domain.")
117 self.
_pairs = _positive_int(pairs,
"pairs")
120 self.
_weight = diversity_weight
121 self.
_rng, self.
_rollouts, self.
_bandit = (np.random.default_rng(s)
for s
in np.random.SeedSequence(seed).spawn(3))
123 self.
_mean, self.
_variance = np.zeros_like(population), np.zeros_like(population)
124 self.
_counts = dict(center_evaluations=0, perturbation_evaluations=0, failed_evaluations=0,
125 updates=0, reward_only_updates=0, mixed_updates=0)
129 """Return the last successfully measured centers in member order."""
134 """Return cumulative costs and update counts."""
139 """Return the number of calls needed to measure the initial centers."""
144 """Return the call reservation for one complete generation."""
147 def _bounded(self, points):
148 return points
if self.
_bounds is None else np.clip(points, *self.
_bounds)
150 def _measure(self, evaluate, points, *, center):
152 phase =
"center_evaluations" if center
else "perturbation_evaluations"
154 genome = tuple(map(float, point))
156 measurement = evaluate(genome, int(self.
_rollouts.integers(2**32)))
157 if measurement
is None:
158 self.
_counts[
"failed_evaluations"] += 1
161 reward, embedding = measurement
162 reward = float(reward)
163 embedding = np.asarray(embedding, dtype=float)
164 if (embedding.ndim != 1
or not len(embedding)
or not np.isfinite(embedding).all()
165 or not np.isfinite(reward)):
166 raise ValueError(
"Return a finite scalar reward and a nonempty finite embedding, or None.")
170 raise ValueError(
"Embedding dimensions must remain fixed throughout the run.")
171 rows.append(
DvDESMember(genome, reward, tuple(map(float, embedding))))
174 def _round(self, evaluate):
176 weight = self.
_weight if arm
is None else .5 * arm
178 perturbations = np.concatenate((noise, -noise))
180 rows = [self.
_measure(evaluate, batch, center=
False)
for batch
in points]
181 if any(row
is None for batch
in rows
for row
in batch):
183 rewards = np.asarray([[row.reward
for row
in batch]
for batch
in rows])
184 gradients = np.asarray([_rank_gradient(noise[:, i], rewards[:, i], self.
_sigma)
187 diversity = [_logdet(np.asarray([row.embedding
for row
in batch]), self.
_bandwidth, self.
_ridge)
189 joint = np.asarray([_rank_gradient(tangent, diversity, self.
_sigma)
190 for tangent
in noise.transpose(1, 0, 2)])
191 gradients = (1. - weight) * gradients + weight * joint
192 step = self.
_counts[
"updates"] + 1
193 mean = .9 * self.
_mean + .1 * gradients
194 variance = .999 * self.
_variance + .001 * np.square(gradients)
195 move = self.
_rate * (mean / (1. - .9**step)) / (np.sqrt(variance / (1. - .999**step)) + 1e-8)
197 measured = self.
_measure(evaluate, proposed, center=
True)
198 if any(row
is None for row
in measured):
201 improved = max(row.reward
for row
in measured) > max(row.reward
for row
in self.
_population)
202 self.
_posterior[arm, 0
if improved
else 1] += 1
206 self.
_counts[
"mixed_updates" if weight
else "reward_only_updates"] += 1
212 def run(self, evaluate, budget):
213 """Continue the search, starting only rounds whose complete cost fits."""
214 remaining = _positive_int(budget,
"budget")
218 if all(row
is not None for row
in measured):
221 previous = self.
stats.evaluations
223 remaining -= self.
stats.evaluations - previous