38 """Store one measured elite per learned code.
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.
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.
67 _observation_key =
"vq_observation"
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"):
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")
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
91 raise ValueError(
"Use finite genome bounds and loss weights and a positive learning rate.")
95 self.
_records = deque(maxlen=capacity)
97 streams = np.random.SeedSequence(seed).spawn(2)
99 self.
device = torch.device(device)
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(),
107 "decoder": nn.Sequential(nn.Linear(self.
latent_size, hidden), nn.ReLU(),
112 with torch.no_grad():
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)
118 def _new_archive(self):
119 return Grid(shape=(self.
cells,), features_domain=((-.5, self.
cells - .5),),
124 """Return cumulative work, including measurements supplied with observe()."""
129 """Return a detached copy of the current latent centroids."""
130 return self.
_model[
"codes"].weight.detach().cpu().numpy().copy()
132 def _tensor(self, rows):
135 return torch.as_tensor(np.asarray(rows, dtype=np.float32), device=self.
device)
138 def _codes(model, latent):
141 distances = torch.cdist(latent, model[
"codes"].weight, compute_mode=
"donot_use_mm_for_euclid_dist")
142 return distances.argmin(dim=1)
144 def _classify(self, model, rows):
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()
153 def _record(self, archive, row, index):
154 genome, fitness, observation = row
155 if archive.in_bounds((fitness,), archive.fitness_domain):
159 return archive.add(candidate)
is not None
164 from torch.nn import functional
as F
169 with torch.no_grad():
170 latent = model[
"encoder"](data).cpu().numpy()
171 if len(np.unique(latent, axis=0)) >= self.
cells:
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))
177 for _
in range(self.
epochs):
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)
191 torch.nn.utils.clip_grad_norm_(model.parameters(), float(
"inf"), error_if_nonfinite=
True)
193 with torch.no_grad():
194 model[
"codes"].weight.clamp_(-1., 1.)
196 rows = ([(tuple(ind), ind.fitness.values[0], ind.scores[self.
_observation_key])
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)
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()
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)))
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.")
232 for _
in range(budget):
236 a, b = rng.integers(len(self.
archive), size=2)
239 fitness, observation = evaluate(tuple(point))
240 self.
observe(point, fitness, observation)