QDpy
Loading...
Searching...
No Matches
neuro_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Evolve classifiers across a learned space of per-example errors."""
7
8from dataclasses import dataclass
9
10import numpy as np
11from scipy.special import ndtr
12
13from qdpy.containers import Grid
14from ._population import _attempt_budget
15from .modern import _positive_int
16from .task_search import _measurement, _offer, _validate_grid
17
18__all__ = ["NMEEnsemble", "NMEResult", "neuro_map_elites", "nme_ensemble"]
19
20
21def _labels(values, size=None):
22 labels = np.asarray(values)
23 if (labels.ndim != 1 or not len(labels) or (size is not None and len(labels) != size)
24 or labels.dtype.kind not in "biufUS"
25 or (labels.dtype.kind == "f" and not np.isfinite(labels).all())):
26 raise ValueError("Provide a fixed nonempty vector of finite numeric or string labels.")
27 return labels
28
29
30def _balanced(correct, groups, counts):
31 correct_by_class = np.bincount(groups, weights=correct, minlength=len(counts))
32 return float(np.mean(correct_by_class / counts))
33
34
35def _vote(votes, classes, predictions):
36 indices = np.searchsorted(classes, predictions)
37 if np.any(indices >= len(classes)) or not np.array_equal(classes[indices], predictions):
38 raise ValueError("A classifier predicted a class outside the training labels.")
39 votes[np.arange(len(indices)), indices] += 1
40
41
42
43@dataclass(frozen=True)
45 """Preserve vote order and break vote ties by the order of classes."""
46
47 genomes: tuple[tuple, ...]
48 classes: tuple
49 validation_accuracy: float
50 validation_evaluations: int
51
52
53 def predict(self, predict):
54 """Call predict(genome) once per member and return the majority labels."""
55 classes = np.asarray(self.classes)
56 votes = None
57 for genome in self.genomes:
58 row = _labels(predict(genome), None if votes is None else len(votes))
59 if votes is None:
60 votes = np.zeros((len(row), len(classes)), dtype=int)
61 _vote(votes, classes, row)
62 return classes[votes.argmax(axis=1)]
63
64
65
66@dataclass(frozen=True)
68 """The encoder maps binary error masks to descriptors in the unit cube."""
69
70 archive: Grid
71 mining_archive: Grid
72 encoder: object
73 evaluations: int
74 mining_evaluations: int
75 encoder_updates: int
76 training_masks: int
77
78
80 def __init__(self, torch, masks, width, hidden, beta, steps, batch, rng):
81 nn = torch.nn
82 layout = dict(device="cpu", dtype=torch.float32)
83 with torch.random.fork_rng(devices=[]):
84 torch.random.default_generator.manual_seed(int(rng.integers(2**32)))
85 self._encoder = nn.Sequential(nn.Linear(masks.shape[1], hidden, **layout), nn.ReLU(),
86 nn.Linear(hidden, 2 * width, **layout))
87 decoder = nn.Sequential(nn.Linear(width, hidden, **layout), nn.ReLU(),
88 nn.Linear(hidden, masks.shape[1], **layout))
89 self._torch, self._size, self._width = torch, masks.shape[1], width
90 noise = torch.Generator(device="cpu").manual_seed(int(rng.integers(2**32)))
91 optimizer = torch.optim.Adam((*self._encoder.parameters(), *decoder.parameters()), lr=.003)
92 data = torch.as_tensor(masks, device="cpu", dtype=torch.float32)
93 for _ in range(steps):
94 rows = rng.choice(len(data), min(batch, len(data)), replace=False)
95 target = data[rows]
96 mean, log_variance = self._encoder(target).chunk(2, dim=1)
97 log_variance = log_variance.clamp(-10., 6.)
98 jitter = torch.randn(mean.shape, device="cpu", dtype=mean.dtype, generator=noise)
99 sampled = mean + (.5 * log_variance).exp() * jitter
100 penalty = .5 * (mean.square() + log_variance.exp() - log_variance - 1.).sum(dim=1).mean()
101 loss = nn.functional.binary_cross_entropy_with_logits(decoder(sampled), target, reduction="sum")
102 loss = loss / len(rows) + beta * penalty
103 if not torch.isfinite(loss):
104 raise FloatingPointError("The error-mask encoder produced a nonfinite loss.")
105 optimizer.zero_grad(set_to_none=True)
106 loss.backward()
107 optimizer.step()
108 self._encoder.requires_grad_(False)
109
110 def transform(self, masks):
111 """Return normal quantiles of the latent means for binary error masks."""
112 masks = np.asarray(masks, dtype=np.float32)
113 if masks.ndim not in (1, 2) or masks.shape[-1] != self._size or not np.isin(masks, (0, 1)).all():
114 raise ValueError("Supply binary masks in the original training example order.")
115 with self._torch.no_grad():
116 means = self._encoder(self._torch.from_numpy(masks.copy()))[..., :self._width].numpy()
117 if not np.isfinite(means).all():
118 raise FloatingPointError("The error-mask encoder produced nonfinite descriptors.")
119 return ndtr(means.astype(float))
120
121
122
140def neuro_map_elites(targets, predict, *, sample, mutate, structural, mining_archive,
141 budget, mining_budget, initial_samples=16, shape=(8, 8), min_mining_accuracy=.5,
142 fit_steps=128, hidden=32, fit_batch=32, beta=.3, seed=0):
143 """Run structural and learned-descriptor searches over the same training panel.
144
145 Use balanced accuracy in both phases. Retain the error masks of qualifying
146 mining elites and fit a beta-VAE to the binary masks. Seed the learned
147 archive from cached mining measurements. Normal quantiles partition each
148 learned axis into bins of equal mass under the latent prior.
149 """
150 if not all(map(callable, (predict, sample, mutate, structural))):
151 raise TypeError("Supply callable prediction, variation and mining descriptors.")
152 _validate_grid(mining_archive)
153 if type(mining_archive) is not Grid or (mining_archive.fitness_weights or (1.,))[0] <= 0:
154 raise ValueError("Use a rectangular mining archive which maximizes quality.")
155 target = _labels(targets)
156 classes, groups, counts = np.unique(target, return_inverse=True, return_counts=True)
157 groups = groups.reshape(-1)
158 budget, first = _attempt_budget(budget), _positive_int(mining_budget, "mining_budget")
159 initial_samples = _attempt_budget(initial_samples)
160 shape = tuple(_positive_int(n, "shape") for n in shape)
161 if (len(classes) < 2 or not shape or budget <= first or not 0 <= min_mining_accuracy <= 1
162 or not 0 < beta < np.inf):
163 raise ValueError("Use two or more classes, a mining budget below budget, and valid encoder settings.")
164 steps = _positive_int(fit_steps, "fit_steps")
165 hidden = _positive_int(hidden, "hidden")
166 batch = _positive_int(fit_batch, "fit_batch")
167 try:
168 import torch
169 except ImportError as error:
170 raise ImportError("Neuro-MAP-Elites requires PyTorch. Install qdpy[rl] or torch.") from error
171 if mining_archive.fitness_weights is None:
172 mining_archive._set_fitness_weights((1.,))
173 rng, fit_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
174
175 def propose(grid):
176 return tuple(mutate(tuple(grid[int(rng.integers(len(grid)))]), rng) if grid else sample(rng))
177
178 def score(genome):
179 predictions = _labels(predict(genome), len(target))
180 if not np.isin(predictions, classes).all():
181 raise ValueError("Predicted labels must belong to the training classes.")
182 mask = predictions != target
183 return _balanced(~mask, groups, counts), tuple(map(bool, mask))
184
185 def admit(grid, genome, quality, mask, descriptor):
186 candidate = _measurement(grid, ((quality,), descriptor), genome)
187 candidate[0].scores["nme_error_mask"] = mask
188 _offer(grid, candidate)
189
190 for step in range(first):
191 genome = tuple(sample(rng)) if step < initial_samples else propose(mining_archive)
192 quality, mask = score(genome)
193 admit(mining_archive, genome, quality, mask, structural(genome))
194 masks = [row.scores["nme_error_mask"] for row in mining_archive
195 if row.fitness.values[0] >= min_mining_accuracy]
196 if not masks:
197 raise ValueError("The mining archive has no qualifying classifiers for the VAE.")
198 encoder = _MaskEncoder(torch, np.array(masks), len(shape), hidden, beta, steps, batch, fit_rng)
199 archive = Grid(shape=shape, features_domain=((0., 1.),) * len(shape),
200 fitness_domain=((0., 1.),), fitness_weights=(1.,))
201 for row in mining_archive:
202 mask = row.scores["nme_error_mask"]
203 admit(archive, tuple(row), row.fitness.values[0], mask, encoder.transform(mask))
204 for _ in range(budget - first):
205 genome = propose(archive)
206 quality, mask = score(genome)
207 admit(archive, genome, quality, mask, encoder.transform(mask))
208 return NMEResult(archive, mining_archive, encoder, budget, first, steps, len(masks))
209
210
211
219def nme_ensemble(archive, predict, targets, *, classes=None, max_members=None, size=None):
220 """Try quality-ranked vote prefixes and keep the smallest best-scoring one."""
221 target = _labels(targets)
222 observed, groups, counts = np.unique(target, return_inverse=True, return_counts=True)
223 groups = groups.reshape(-1)
224 classes = observed if classes is None else np.unique(_labels(classes))
225 if not np.isin(observed, classes).all():
226 raise ValueError("The validation targets include an unknown class.")
227 ranked = sorted(archive, key=lambda row: row.fitness.values[0] * row.fitness.weights[0], reverse=True)
228 if max_members is not None:
229 ranked = ranked[:_positive_int(max_members, "max_members")]
230 if size is not None:
231 size = _positive_int(size, "size")
232 if size > len(ranked):
233 raise ValueError("The archive cannot fill the requested ensemble size.")
234 ranked = ranked[:size]
235 if not ranked or not callable(predict):
236 raise ValueError("Supply a nonempty archive and callable validation prediction.")
237 genomes = tuple(tuple(row) for row in ranked)
238 votes = np.zeros((len(target), len(classes)), dtype=int)
239 best, best_size = -1., 0
240 for length, genome in enumerate(genomes, 1):
241 _vote(votes, classes, _labels(predict(genome), len(target)))
242 value = _balanced(classes[votes.argmax(axis=1)] == target, groups, counts)
243 if length == size or (size is None and value > best):
244 best, best_size = value, length
245 return NMEEnsemble(genomes[:best_size], tuple(classes.tolist()), best, len(genomes))
Classifiers selected by validation accuracy and combined with majority voting.
predict(self, predict)
Predict labels on a shared panel using the selected genomes.
Report the final learned repertoire, initial mining archive, and model-call counts.