QDpy
Loading...
Searching...
No Matches
dvd_es.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Diversity via Determinants for antithetic evolution strategies."""
7
8from dataclasses import dataclass
9
10import numpy as np
11from scipy.spatial.distance import cdist
12
13from .me_es import _rank_gradient
14from .modern import _bounds, _positive_int
15
16__all__ = ["DvDES", "DvDESMember", "DvDESStats", "behavior_logdet"]
17
18
19def _kernel_settings(bandwidth, ridge):
20 if not (0 < bandwidth < np.inf and np.finfo(float).eps <= ridge < np.inf):
21 raise ValueError("Use a positive finite bandwidth and a finite ridge of at least machine epsilon.")
22
23
24def _logdet(embeddings, bandwidth, ridge):
25 with np.errstate(over="ignore"):
26 scaled = embeddings / bandwidth
27 distances = (cdist(scaled, scaled, "sqeuclidean") if np.isfinite(scaled).all()
28 else np.square(cdist(embeddings, embeddings) / bandwidth))
29 kernel = np.exp(-.5 * distances)
30 kernel.flat[::len(kernel) + 1] = 1. + ridge
31 sign, logdet = np.linalg.slogdet(kernel)
32 if sign != 1 or not np.isfinite(logdet):
33 raise ValueError("The kernel could not be factored. Rescale the embeddings or increase ridge.")
34 return float(logdet)
35
36
37
42def behavior_logdet(embeddings, *, bandwidth=1., ridge=1e-6):
43 """Compute log(det(K + ridge I)) for an RBF kernel."""
44 _kernel_settings(bandwidth, ridge)
45 embeddings = np.asarray(embeddings, dtype=float)
46 if embeddings.ndim != 2 or min(embeddings.shape) == 0 or not np.isfinite(embeddings).all():
47 raise ValueError("Supply a nonempty matrix of finite embeddings.")
48 return _logdet(embeddings, bandwidth, ridge)
49
50
51
52@dataclass(frozen=True)
54 """Store the center parameters, reward, and behaviour from a fresh evaluation."""
55
56 genome: tuple[float, ...]
57 reward: float
58 embedding: tuple[float, ...]
59
60
61
62@dataclass(frozen=True)
64 """Count evaluator attempts even when a returned failure invalidates a round."""
65
66 center_evaluations: int
67 perturbation_evaluations: int
68 failed_evaluations: int
69 updates: int
70 reward_only_updates: int
71 mixed_updates: int
72
73 @property
74 def evaluations(self):
75 """Return total calls to the evaluator."""
76 return self.center_evaluations + self.perturbation_evaluations
77
78
79
80class DvDES:
81 """Compute one determinant for each simultaneous population perturbation.
82
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.
90
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.
100 """
101
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.")
115 self._centers, self._population = population, ()
116 self._embedding_size = None
117 self._pairs = _positive_int(pairs, "pairs")
118 self._sigma, self._rate = sigma, learning_rate
119 self._bandwidth, self._ridge = bandwidth, ridge
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))
122 self._posterior = np.ones((2, 2))
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)
126
127 @property
128 def population(self):
129 """Return the last successfully measured centers in member order."""
130 return self._population
131
132 @property
133 def stats(self):
134 """Return cumulative costs and update counts."""
135 return DvDESStats(**self._counts)
136
137 @property
139 """Return the number of calls needed to measure the initial centers."""
140 return len(self._centers)
141
142 @property
143 def round_cost(self):
144 """Return the call reservation for one complete generation."""
145 return self.initialization_cost * (2 * self._pairs + 1)
146
147 def _bounded(self, points):
148 return points if self._bounds is None else np.clip(points, *self._bounds)
149
150 def _measure(self, evaluate, points, *, center):
151 rows = []
152 phase = "center_evaluations" if center else "perturbation_evaluations"
153 for point in points:
154 genome = tuple(map(float, point))
155 self._counts[phase] += 1
156 measurement = evaluate(genome, int(self._rollouts.integers(2**32)))
157 if measurement is None:
158 self._counts["failed_evaluations"] += 1
159 rows.append(None)
160 continue
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.")
167 if self._embedding_size is None:
168 self._embedding_size = len(embedding)
169 elif len(embedding) != self._embedding_size:
170 raise ValueError("Embedding dimensions must remain fixed throughout the run.")
171 rows.append(DvDESMember(genome, reward, tuple(map(float, embedding))))
172 return rows
173
174 def _round(self, evaluate):
175 arm = None if self._weight is not None else int(np.argmax(self._bandit.beta(*self._posterior.T)))
176 weight = self._weight if arm is None else .5 * arm
177 noise = self._rng.normal(size=(self._pairs, *self._centers.shape))
178 perturbations = np.concatenate((noise, -noise))
179 points = self._bounded(self._centers + self._sigma * perturbations)
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):
182 return
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)
185 for i in range(self.initialization_cost)])
186 if weight:
187 diversity = [_logdet(np.asarray([row.embedding for row in batch]), self._bandwidth, self._ridge)
188 for batch in rows]
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)
196 proposed = self._bounded(self._centers + move)
197 measured = self._measure(evaluate, proposed, center=True)
198 if any(row is None for row in measured):
199 return
200 if arm is not None:
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
203 self._centers, self._population = proposed, tuple(measured)
204 self._mean, self._variance = mean, variance
205 self._counts["updates"] = step
206 self._counts["mixed_updates" if weight else "reward_only_updates"] += 1
207
208
212 def run(self, evaluate, budget):
213 """Continue the search, starting only rounds whose complete cost fits."""
214 remaining = _positive_int(budget, "budget")
215 while not self._population and remaining >= self.initialization_cost:
216 measured = self._measure(evaluate, self._centers, center=True)
217 remaining -= self.initialization_cost
218 if all(row is not None for row in measured):
219 self._population = tuple(measured)
220 while self._population and remaining >= self.round_cost:
221 previous = self.stats.evaluations
222 self._round(evaluate)
223 remaining -= self.stats.evaluations - previous
224 return self.stats
A policy center with its own measured reward and embedding.
Definition dvd_es.py:53
Cumulative calls, successful updates, and weighting choices.
Definition dvd_es.py:63
Optimize multiple centers with local rewards and shared population volumes.
Definition dvd_es.py:80
_measure(self, evaluate, points, *, center)
Definition dvd_es.py:150
run(self, evaluate, budget)
Spend at most an additional evaluator-call budget.
Definition dvd_es.py:212
_round(self, evaluate)
Definition dvd_es.py:174