QDpy
Loading...
Searching...
No Matches
learned_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Learned QD inference and native ordered search."""
6
7import numpy as np
8from scipy.special import softmax
9
10from qdpy.base import registry
11from qdpy.containers import Container
12from qdpy.tools import iso_line_dd
13from .modern import _FixedGeneration, _positive_int, _variation_settings
14
15__all__ = ["LQDSelector", "LearnedQD"]
16
17
18def _standardize(values):
19 """Scale before computing moments to accommodate large finite coordinates."""
20 scale = np.max(np.abs(values), axis=0)
21 scaled = values / np.where(scale > 0, scale, 1.)
22 centered = scaled - scaled.mean(axis=0)
23 deviation = np.sqrt(np.mean(centered ** 2, axis=0))
24 return centered / np.where(deviation > 0, deviation, 1.)
25
26
27
29 """Produce one learned survival score per population member.
30
31 The model standardizes each input column across the population. Its
32 attention blocks have a residual feed-forward layer and no positional
33 encodings. The weights can be optimized by an external optimizer.
34
35 :param descriptor_size: Number of measured descriptor coordinates.
36 :param width: Embedding width, divisible by the number of heads.
37 :param heads: Number of attention heads.
38 :param layers: Number of attention blocks.
39 :param parameters: Optional one-dimensional vector of model weights.
40 :param seed: Local initialization seed when weights are unspecified.
41 """
42
43 def __init__(self, descriptor_size, *, width=16, heads=4, layers=4, parameters=None, seed=0):
44 self.descriptor_size = _positive_int(descriptor_size, "descriptor_size")
45 self.width = _positive_int(width, "width")
46 self.heads = _positive_int(heads, "heads")
47 self.layers = _positive_int(layers, "layers")
48 if self.width % self.heads:
49 raise ValueError("The embedding width must be divisible by the number of heads.")
50 width = self.width
51 count = (self.descriptor_size + 2) * width + self.layers * 8 * width ** 2
52 if parameters is None:
53 parameters = np.random.default_rng(seed).normal(scale=0.5 / np.sqrt(width), size=count)
54 self._parameters = np.array(parameters, dtype=float, copy=True)
55 if self._parameters.shape != (count,) or not np.isfinite(self._parameters).all():
56 raise ValueError(f"Provide {count} finite selector weights.")
57 end = (self.descriptor_size + 1) * width
58 self._project = self._parameters[:end].reshape(-1, width)
59 blocks = self._parameters[end:-width].reshape(self.layers, 8, width, width)
60 self._blocks = tuple((*block[:4], block[4:6].reshape(width, 2 * width),
61 block[6:].reshape(2 * width, width)) for block in blocks)
62 self._readout = self._parameters[-width:]
63
64 @property
65 def parameters(self):
66 """Return a copy of the flat model weights."""
67 return self._parameters.copy()
68
69
70 def score(self, quality, descriptors):
71 """Return finite scores in the input order. Larger scores survive."""
72 quality = np.asarray(quality, dtype=float)
73 descriptors = np.asarray(descriptors, dtype=float)
74 if (quality.ndim != 1 or not len(quality) or descriptors.shape != (len(quality), self.descriptor_size)
75 or not np.isfinite(quality).all() or not np.isfinite(descriptors).all()):
76 raise ValueError("Provide finite quality and descriptors for a nonempty population.")
77 hidden = _standardize(np.column_stack((quality, descriptors))) @ self._project
78 head_width = self.width // self.heads
79 for query, key, value, output, expand, reduce in self._blocks:
80 q, k, v = ((hidden @ weights).reshape(len(hidden), self.heads, head_width).transpose(1, 0, 2)
81 for weights in (query, key, value))
82 attention = softmax((q @ k.transpose(0, 2, 1)) / np.sqrt(head_width), axis=-1)
83 hidden = hidden + (attention @ v).transpose(1, 0, 2).reshape(len(hidden), self.width) @ output
84 hidden = hidden + np.maximum(hidden @ expand, 0.) @ reduce
85 scores = hidden @ self._readout
86 if not np.isfinite(scores).all():
87 raise FloatingPointError("The learned selector produced nonfinite scores.")
88 return scores
89
90
91 def save(self, path):
92 """Save the model geometry and weights."""
93 settings = np.array((1, self.descriptor_size, self.width, self.heads, self.layers), dtype=np.int64)
94 with open(path, "wb") as destination:
95 np.savez_compressed(destination, settings=settings, parameters=self._parameters)
96
97
98 @classmethod
99 def load(cls, path):
100 """Validate the format version and model geometry before constructing the selector."""
101 with np.load(path, allow_pickle=False) as data:
102 settings = data["settings"]
103 if settings.shape != (5,) or settings.dtype.kind not in "iu" or settings[0] != 1:
104 raise ValueError("Unsupported LQD selector format.")
105 _, size, width, heads, layers = settings
106 return cls(size, width=width, heads=heads, layers=layers, parameters=data["parameters"])
107
108
109
110@registry.register
112 """Evolve a population using Iso+LineDD and learned local competition.
113
114 The selector scores the concatenated parent and offspring population.
115 Keep the highest-scoring distinct genomes with stable ties. Raw fitness
116 and descriptors remain available for reporting and serialization.
117
118 :param selector: LQDSelector for the evaluator's descriptor width.
119 :param budget: Number of attempted evaluations.
120 :param dimension: Bounded real genome length.
121 :param population_size: Maximum retained population size.
122 :param batch_size: Number of offspring before survival selection.
123 :param ind_domain: Common clipping interval.
124 :param fitness_domain: Optional interval in raw objective units.
125 :param iso_sigma: Isotropic noise scale.
126 :param line_sigma: Directional noise scale.
127 :param seed: Local seed for parent draws and variation.
128 """
129
130 _requires_proposed_genome = True
131
132 def __init__(self, selector, budget, dimension, population_size, batch_size, *,
133 ind_domain=(0., 1.), fitness_domain=None, iso_sigma=.01, line_sigma=.2, seed=0, **kwargs):
134 if not isinstance(selector, LQDSelector):
135 raise TypeError("Supply an LQDSelector.")
136 self.selector, self.seed = selector, seed
137 self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
138 self.iso_sigma, self.line_sigma = iso_sigma, line_sigma
139 if fitness_domain is None:
140 fitness_domain = (-np.inf, np.inf)
141 if len(fitness_domain) != 2:
142 raise ValueError("Supply one fitness interval.")
143 archive = Container(fitness_domain=(fitness_domain,), capacity=_positive_int(population_size, "population_size"))
144 super().__init__(archive, _positive_int(budget, "budget"),
145 batch_size=_positive_int(batch_size, "batch_size"),
146 dimension=_positive_int(dimension, "dimension"), **kwargs)
147
148 def reinit(self):
149 """Reset the proposal stream and native counters."""
150 super().reinit()
151 self._rng = np.random.default_rng(self.seed)
152
153 def _internal_ask(self, base_ind):
154 archive = self.container
155 if len(archive) < archive.capacity:
156 base_ind[:] = self._rng.uniform(*self.ind_domain, size=self.dimension)
157 else:
158 first, second = self._rng.integers(len(archive), size=2)
159 base_ind[:] = iso_line_dd(archive[first], archive[second], bounds=self.ind_domain,
160 iso_sigma=self.iso_sigma, line_sigma=self.line_sigma, rng=self._rng)
161 return base_ind
162
163 def _check_candidate(self, individual):
164 super()._check_candidate(individual)
165 if len(individual.features) != self.selector.descriptor_size:
166 raise ValueError("The descriptor size must match the learned selector.")
167
168 def _commit_generation(self, evaluated):
169 archive = self.container
170 parents = list(archive)
171 combined = parents.copy()
172 slots = {}
173 seen = {tuple(parent) for parent in parents}
174 for slot, individual in enumerate(evaluated):
175 if individual is not None and tuple(individual) not in seen:
176 seen.add(tuple(individual))
177 slots[id(individual)] = slot
178 combined.append(individual)
179 if len(combined) > archive.capacity:
180 weight, = archive.fitness_weights
181 scores = self.selector.score([weight * individual.fitness.values[0] for individual in combined],
182 [tuple(individual.features) for individual in combined])
183 indices = np.argsort(-scores, kind="stable")[:archive.capacity]
184 combined = [combined[i] for i in indices]
185 selected = {id(individual) for individual in combined}
186 for parent in parents:
187 if id(parent) not in selected:
188 archive.discard(parent)
189 admitted = set()
190 for individual in combined:
191 if id(individual) in slots:
192 archive.add(individual)
193 admitted.add(slots[id(individual)])
194 return admitted
Permutation-equivariant attention over measured quality and descriptors.
Definition learned_qd.py:28
save(self, path)
Write versioned numeric weights to a local NPZ file.
Definition learned_qd.py:91
load(cls, path)
Read an LQD selector from a local numeric NPZ file.
Definition learned_qd.py:99
score(self, quality, descriptors)
Score a population using signed quality and measured descriptors.
Definition learned_qd.py:70
Use a learned competition rule in an ordered, bounded evolutionary search.