23 """Learn a diagonal Gaussian latent space in normalized genome coordinates."""
25 def __init__(self, dimension, hidden, latent, rate, beta, seed, device):
28 except ImportError
as error:
29 raise ImportError(
"DDEElites requires PyTorch. Install qdpy[rl] or torch.")
from error
32 self.
device = torch.device(device)
33 self.
rng = torch.Generator(device=self.
device).manual_seed(seed)
35 with torch.random.fork_rng(devices=[]):
36 torch.random.default_generator.manual_seed(seed)
37 self.
encoder = nn.Sequential(nn.Linear(dimension, hidden), nn.ReLU(), nn.Linear(hidden, 2 * latent))
38 self.
decoder = nn.Sequential(nn.Linear(latent, hidden), nn.ReLU(), nn.Linear(hidden, dimension),
44 def fit(self, genomes, epochs, batch_size):
47 data = torch.as_tensor(genomes, dtype=torch.float32, device=self.
device)
48 for _
in range(epochs):
49 order = torch.randperm(len(data), generator=self.
rng, device=self.
device)
50 for rows
in order.split(batch_size):
52 means, log_variance = self.
encoder(batch).chunk(2, dim=1)
53 log_variance = log_variance.clamp(-12., 8.)
54 noise = torch.randn(means.shape, device=self.
device, generator=self.
rng)
55 reconstructions = self.
decoder(means + noise * (0.5 * log_variance).exp())
56 reconstruction_loss = (batch - reconstructions).square().mean()
57 kl = 0.5 * (means.square() + log_variance.exp() - log_variance - 1).mean()
58 loss = reconstruction_loss + self.
beta * kl
59 if not torch.isfinite(loss):
60 raise ValueError(
"The genome VAE produced a nonfinite loss.")
61 self.
optimizer.zero_grad(set_to_none=
True)
65 def encode(self, genomes):
69 return self.
_means(genomes).cpu().numpy()
71 def _means(self, genomes):
74 data = torch.as_tensor(genomes, dtype=torch.float32, device=self.
device)
75 means, _ = self.
encoder(data).chunk(2, dim=1)
76 if not torch.isfinite(means).all():
77 raise ValueError(
"The genome VAE produced a nonfinite latent code.")
80 def reconstruct(self, genomes):
86 def decode(self, codes):
90 data = torch.as_tensor(codes, dtype=torch.float32, device=self.
device)
91 return self.
decoder(data).cpu().numpy()
97 """DDE-Elites for bounded real genomes and a fixed, best-only archive.
99 A variational autoencoder learns from the current elites. Reconstructive
100 crossover averages a parent with its decoded latent mean. A sliding
101 window UCB1 bandit chooses a mixture of this operator, Iso+LineDD, and
102 isotropic mutation once per generation. Successful offspring are those
103 still present after the whole generation has been committed.
105 :param container: Fixed, one-elite Grid or CVTGrid.
106 :param budget: Candidate evaluations.
107 :param dimension: Length of the real genome.
108 :param ind_domain: Shared finite lower and upper genome bounds.
109 :param batch_size: Candidate proposals per generation.
110 :param mixtures: Rows of probabilities in reconstruction, line, isotropic order.
111 Include a mixture without reconstruction for warm-up. The default
112 tries the three pure operators and two mixed arms.
113 :param window_size: Number of recent arm rewards kept by UCB1.
114 :param min_elites: Elites required before training a model.
115 :param fit_interval: Generations between fits, starting at the first eligible batch.
116 :param fit_epochs: Passes over the archive per fit.
117 :param fit_batch_size: Genome minibatch size.
118 :param hidden_size: Width of the encoder and decoder hidden layers.
119 :param latent_size: Width of the Gaussian latent representation.
120 :param learning_rate: VAE Adam learning rate.
121 :param beta: KL term weight.
122 :param iso_sigma: Isotropic mutation scale in genome units.
123 :param line_sigma: Relative Iso+LineDD direction scale.
124 :param seed: Private search and model seed.
125 :param device: PyTorch training device.
126 :param kwargs: Native QDAlgorithm options.
129 _requires_proposed_genome =
True
131 def __init__(self, container, budget, dimension, ind_domain=(0., 1.), *, batch_size=32,
132 mixtures=((1., 0., 0.), (0., 1., 0.), (0., 0., 1.), (.5, .5, 0.), (.5, 0., .5)),
133 window_size=50, min_elites=4, fit_interval=1, fit_epochs=5, fit_batch_size=64,
134 hidden_size=64, latent_size=8, learning_rate=1e-3, beta=0.01,
135 iso_sigma=.01, line_sigma=.2, seed=0, device=
"cpu", **kwargs):
136 if (type(container)
not in (Grid, CVTGrid)
or container.max_items_per_bin != 1
137 or container.discard_random_on_bin_overload
or container.fitness_domain
is None
138 or len(container.fitness_domain) != 1):
139 raise ValueError(
"DDEElites requires a fixed, best-only Grid or CVTGrid with one objective.")
140 self.
ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
142 self.
mixtures = np.array(mixtures, dtype=float, copy=
True)
145 or not np.allclose(self.
mixtures.sum(axis=1), 1)
146 or not np.any(self.
mixtures[:, 0] == 0)):
147 raise ValueError(
"Provide probability triples including a mixture without reconstruction.")
149 self.
window_size = _positive_int(window_size,
"window_size")
150 self.
min_elites = _positive_int(min_elites,
"min_elites")
151 self.
fit_interval = _positive_int(fit_interval,
"fit_interval")
152 self.
fit_epochs = _positive_int(fit_epochs,
"fit_epochs")
153 self.
fit_batch_size = _positive_int(fit_batch_size,
"fit_batch_size")
154 if not (0 < learning_rate < np.inf
and 0 <= beta < np.inf):
155 raise ValueError(
"learning_rate must be positive and beta must be finite and nonnegative.")
157 raise ValueError(
"The genome range must be finite.")
158 self.
_model_args = (_positive_int(hidden_size,
"hidden_size"),
159 _positive_int(latent_size,
"latent_size"), learning_rate, beta, seed, device)
160 super().__init__(container, _positive_int(budget,
"budget"),
161 dimension=_positive_int(dimension,
"dimension"),
162 batch_size=_positive_int(batch_size,
"batch_size"), **kwargs)
165 """Reset the model and bandit while retaining the reporting archive."""
176 """Return cumulative proposals by variation operator, including random starts."""
181 """Return the number of completed archive VAE fits."""
184 def _encoding_input(self, vectors, dimension):
186 raise RuntimeError(
"The archive VAE has not been fitted yet.")
187 values = np.asarray(vectors, dtype=float)
188 if values.ndim != 2
or values.shape[1] != dimension
or not np.isfinite(values).all():
189 raise ValueError(f
"Expected a matrix of finite vectors of length {dimension}.")
194 """Map rows of bounded genomes to the means of their latent distributions."""
197 if np.any((data < lower) | (data > upper)):
198 raise ValueError(
"Genomes must respect ind_domain.")
199 return self.
_model.
encode((data - lower) / (upper - lower))
203 """Return one bounded reconstructed genome per row of latent coordinates."""
205 if np.any(np.abs(data) > np.finfo(np.float32).max):
206 raise ValueError(
"Latent coordinates must be representable in float32.")
209 def _scale_reconstructions(self, genomes):
211 if not np.isfinite(genomes).all():
212 raise ValueError(
"The genome VAE produced a nonfinite reconstruction.")
213 return lower + (upper - lower) * genomes.astype(float)
215 def _choose_arm(self):
216 eligible = np.flatnonzero(np.ones(len(self.
mixtures), dtype=bool)
218 counts = np.bincount([arm
for arm, _
in self.
_history], minlength=len(self.
mixtures))
219 untried = eligible[counts[eligible] == 0]
221 return self.
_rng.choice(untried)
222 totals = np.bincount([arm
for arm, _
in self.
_history],
223 weights=[reward
for _, reward
in self.
_history], minlength=len(self.
mixtures))
224 scores = totals[eligible] / counts[eligible] + np.sqrt(2 * np.log(len(self.
_history)) / counts[eligible])
225 return self.
_rng.choice(eligible[scores == scores.max()])
231 self.
_tags = [
"random"] * size
234 parents = np.asarray([tuple(individual)
for individual
in self.
container], dtype=float)
236 if (parents.shape != (len(self.
container), self.
dimension)
or not np.isfinite(parents).all()
237 or np.any((parents < lower) | (parents > upper))):
238 raise ValueError(
"DDEElites needs finite archive genomes inside ind_domain.")
246 self.
_tags = [_OPERATORS[kind]
for kind
in kinds]
247 vectors = parents[self.
_rng.integers(len(parents), size=size)]
248 reconstruct = kinds == 0
249 if np.any(reconstruct):
250 selected = vectors[reconstruct]
251 decoded = self.
_model.reconstruct((selected - lower) / (upper - lower))
253 for row
in np.flatnonzero(kinds == 1):
254 vectors[row] = iso_line_dd(vectors[row], parents[self.
_rng.integers(len(parents))],
256 isotropic = kinds == 2
258 self.
_vectors = np.clip(vectors, lower, upper)
264 def _check_candidate(self, individual):
265 super()._check_candidate(individual)
268 def _generation_feedback(self, position):
269 return {
"variation_operator": self.
_tags[position]}
273 for position, individual
in enumerate(evaluated):
274 if individual
is not None:
275 cell = self.
container.index_grid(individual)
277 admitted[cell] = position
279 if self.
_arm is not None:
280 self.
_history.append((self.
_arm, len(admitted) / len(evaluated)))
281 return set(admitted.values())