QDpy
Loading...
Searching...
No Matches
vq_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""VQ-Elites with a bounded latent space and a moving codebook."""
7
8from collections import deque
9from copy import deepcopy
10from dataclasses import dataclass
11from math import isfinite
12
13import numpy as np
14from sklearn.cluster import KMeans
15from threadpoolctl import threadpool_limits
16
17from qdpy.containers import Grid
18from qdpy.phenotype import Features, Fitness, Individual
19from qdpy.tools import iso_line_dd
20from .modern import _positive_int, _variation_settings
21
22__all__ = ["VQElites", "VQElitesStats"]
23
24
25
26@dataclass(frozen=True)
28 """Cumulative cost across supplied observations and evaluated proposals."""
29
30 evaluations: int
31 refits: int
32 optimizer_steps: int
33 archive_updates: int
34
35
36
38 """Store one measured elite per learned code.
39
40 The encoder maps raw observations to bounded latents. Each latent
41 selects its nearest learnable code. Periodic updates train from a
42 bounded observation depot, then re-encode already measured elites.
43 At the first refit the depot supplies initial codebook clusters
44 and archive seeds. Colliding elites compete using their stored
45 fitnesses, so remaps never call the expensive evaluator.
46
47 :param dimension: Length of a numeric decision vector.
48 :param observation_size: Number of numeric values in each raw observation.
49 :param cells: Number of learned archive codes.
50 :param latent_size: Width of the latent space.
51 :param hidden_size: Hidden width of the encoder and decoder.
52 :param ind_domain: Shared finite genome bounds.
53 :param fitness_domain: Closed interval of raw objective values.
54 :param fitness_weight: Finite nonzero signed objective weight.
55 :param training_period: Measurements between codebook updates.
56 :param training_capacity: Most recent measurements retained for training.
57 :param epochs: Optimizer passes per refit.
58 :param batch_size: Optimizer minibatch width.
59 :param learning_rate: Positive Adam learning rate.
60 :param commitment: Nonnegative encoder commitment weight.
61 :param iso_sigma: Independent Gaussian mutation scale.
62 :param line_sigma: Shared Iso+LineDD direction scale.
63 :param seed: Private random seed for trajectories, codebook and optimization.
64 :param device: Torch CPU or CUDA device.
65 """
66
67 _observation_key = "vq_observation"
68
69 def __init__(self, dimension, observation_size, *, cells=32, latent_size=2, hidden_size=32,
70 ind_domain=(0., 1.), fitness_domain=(-np.inf, np.inf), fitness_weight=1.,
71 training_period=64, training_capacity=2048, epochs=5, batch_size=32,
72 learning_rate=1e-3, commitment=.25, iso_sigma=.04, line_sigma=.2,
73 seed=0, device="cpu"):
74 try:
75 import torch
76 except ImportError as error:
77 raise ImportError("VQ-Elites requires PyTorch. Install torch or qdpy[rl].") from error
78 self.dimension = _positive_int(dimension, "dimension")
79 self.observation_size = _positive_int(observation_size, "observation_size")
80 self.cells = _positive_int(cells, "cells")
81 self.latent_size = _positive_int(latent_size, "latent_size")
82 hidden = _positive_int(hidden_size, "hidden_size")
83 self.training_period = _positive_int(training_period, "training_period")
84 capacity = _positive_int(training_capacity, "training_capacity")
85 self.epochs = _positive_int(epochs, "epochs")
86 self.batch_size = _positive_int(batch_size, "batch_size")
87 self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
88 if (not 0 < learning_rate < np.inf or not 0 <= commitment < np.inf
89 or not isfinite(fitness_weight) or not fitness_weight
90 or not isfinite(self.ind_domain[1] - self.ind_domain[0])):
91 raise ValueError("Use finite genome bounds and loss weights and a positive learning rate.")
92 self._weight, self.commitment = fitness_weight, commitment
93 self._fitness_domain = tuple(fitness_domain)
94 self.archive = self._new_archive()
95 self._records = deque(maxlen=capacity)
96 self._iso_sigma, self._line_sigma = iso_sigma, line_sigma
97 streams = np.random.SeedSequence(seed).spawn(2)
98 self._proposal_rng, self._training_rng = (np.random.default_rng(stream) for stream in streams)
99 self.device = torch.device(device)
100 module_seed = int(self._training_rng.integers(2**32))
101 nn = torch.nn
102 with torch.random.fork_rng(devices=[]):
103 torch.random.default_generator.manual_seed(module_seed)
104 self._model = nn.ModuleDict({
105 "encoder": nn.Sequential(nn.Linear(self.observation_size, hidden), nn.ReLU(),
106 nn.Linear(hidden, self.latent_size), nn.Tanh()),
107 "decoder": nn.Sequential(nn.Linear(self.latent_size, hidden), nn.ReLU(),
108 nn.Linear(hidden, self.observation_size)),
109 "codes": nn.Embedding(self.cells, self.latent_size),
110 })
111 self._model.to(self.device)
112 with torch.no_grad():
113 values = self._training_rng.uniform(-1., 1., size=(self.cells, self.latent_size))
114 self._model["codes"].weight.copy_(torch.as_tensor(values, dtype=torch.float32, device=self.device))
115 self._optimizer = torch.optim.Adam(self._model.parameters(), lr=learning_rate)
116 self._evaluations = self._refits = self._steps = self._archive_updates = 0
117
118 def _new_archive(self):
119 return Grid(shape=(self.cells,), features_domain=((-.5, self.cells - .5),),
120 fitness_domain=(self._fitness_domain,), fitness_weights=(self._weight,))
121
122 @property
123 def stats(self):
124 """Return cumulative work, including measurements supplied with observe()."""
125 return VQElitesStats(self._evaluations, self._refits, self._steps, self._archive_updates)
126
127 @property
128 def codebook(self):
129 """Return a detached copy of the current latent centroids."""
130 return self._model["codes"].weight.detach().cpu().numpy().copy()
131
132 def _tensor(self, rows):
133 import torch
134
135 return torch.as_tensor(np.asarray(rows, dtype=np.float32), device=self.device)
136
137 @staticmethod
138 def _codes(model, latent):
139 import torch
140
141 distances = torch.cdist(latent, model["codes"].weight, compute_mode="donot_use_mm_for_euclid_dist")
142 return distances.argmin(dim=1)
143
144 def _classify(self, model, rows):
145 import torch
146
147 with torch.no_grad():
148 latent = model["encoder"](self._tensor(rows))
149 if not torch.isfinite(latent).all():
150 raise ValueError("The encoder produced a nonfinite code.")
151 return self._codes(model, latent).cpu().numpy()
152
153 def _record(self, archive, row, index):
154 genome, fitness, observation = row
155 if archive.in_bounds((fitness,), archive.fitness_domain):
156 candidate = Individual(list(genome), fitness=Fitness((fitness,), weights=(self._weight,)),
157 features=Features((int(index),)),
158 scores={self._observation_key: observation})
159 return archive.add(candidate) is not None
160 return False
161
162 def _refit(self):
163 import torch
164 from torch.nn import functional as F
165
166 model, optimizer = deepcopy((self._model, self._optimizer))
167 data = self._tensor([row[2] for row in self._records])
168 if not self._refits and len(data) >= self.cells:
169 with torch.no_grad():
170 latent = model["encoder"](data).cpu().numpy()
171 if len(np.unique(latent, axis=0)) >= self.cells:
172 seed = int(self._training_rng.integers(2**32))
173 with threadpool_limits(limits=1):
174 centers = KMeans(self.cells, n_init=1, random_state=seed).fit(latent).cluster_centers_
175 model["codes"].weight.copy_(self._tensor(centers))
176 steps = 0
177 for _ in range(self.epochs):
178 order = self._training_rng.permutation(len(data))
179 for start in range(0, len(data), self.batch_size):
180 index = torch.as_tensor(order[start:start + self.batch_size], device=self.device)
181 observed = data[index]
182 latent = model["encoder"](observed)
183 quantized = model["codes"](self._codes(model, latent))
184 reconstructed = model["decoder"](latent + (quantized - latent).detach())
185 loss = (F.mse_loss(reconstructed, observed) + F.mse_loss(quantized, latent.detach())
186 + self.commitment * F.mse_loss(latent, quantized.detach()))
187 if not torch.isfinite(loss):
188 raise ValueError("The VQ-VAE produced a nonfinite loss.")
189 optimizer.zero_grad(set_to_none=True)
190 loss.backward()
191 torch.nn.utils.clip_grad_norm_(model.parameters(), float("inf"), error_if_nonfinite=True)
192 optimizer.step()
193 with torch.no_grad():
194 model["codes"].weight.clamp_(-1., 1.)
195 steps += 1
196 rows = ([(tuple(ind), ind.fitness.values[0], ind.scores[self._observation_key])
197 for ind in self.archive] if self._refits else list(self._records))
198 rebuilt = self._new_archive()
199 if rows:
200 codes = self._classify(model, [row[2] for row in rows])
201 for row, index in zip(rows, codes):
202 self._record(rebuilt, row, index)
203 self._model, self._optimizer, self.archive = model, optimizer, rebuilt
204 self._refits += 1
205 self._steps += steps
206
207
208 def observe(self, genome, fitness, observation):
209 """Accept a scalar objective and a finite observation with observation_size values."""
210 point = np.asarray(genome, dtype=float)
211 data = np.asarray(observation, dtype=np.float32).ravel()
212 fitness = float(fitness)
213 if (point.shape != (self.dimension,) or not np.isfinite(point).all()
214 or np.any(point < self.ind_domain[0]) or np.any(point > self.ind_domain[1])
215 or data.shape != (self.observation_size,) or not np.isfinite(data).all() or not isfinite(fitness)):
216 raise ValueError("Supply a finite in-bounds genome, a scalar fitness, and a fixed finite observation.")
217 row = (tuple(point), fitness, tuple(map(float, data)))
218 index, = self._classify(self._model, [row[2]])
219 self._records.append(row)
220 self._evaluations += 1
221 self._archive_updates += self._record(self.archive, row, index)
222 if self._evaluations % self.training_period == 0:
223 self._refit()
224
225
226 def run(self, evaluate, budget):
227 """Call evaluate(genome) for a pair (scalar fitness, raw observation)."""
228 budget = _positive_int(budget, "budget")
229 if not callable(evaluate):
230 raise TypeError("evaluate must be callable.")
231 rng = self._proposal_rng
232 for _ in range(budget):
233 if not len(self.archive) or not self._refits:
234 point = rng.uniform(*self.ind_domain, size=self.dimension)
235 else:
236 a, b = rng.integers(len(self.archive), size=2)
237 point = iso_line_dd(self.archive[a], self.archive[b], bounds=self.ind_domain,
238 iso_sigma=self._iso_sigma, line_sigma=self._line_sigma, rng=rng)
239 fitness, observation = evaluate(tuple(point))
240 self.observe(point, fitness, observation)
241 return self.stats
Count exact measurements, codebook refits, and optimizer steps.
Definition vq_elites.py:27
Learn archive niches using a vector-quantized autoencoder.
Definition vq_elites.py:37
observe(self, genome, fitness, observation)
Offer a previously measured candidate and trigger a refit when due.
Definition vq_elites.py:208
run(self, evaluate, budget)
Collect additional real measurements using bounded Iso+LineDD variation.
Definition vq_elites.py:226
_record(self, archive, row, index)
Definition vq_elites.py:153
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405