29 """Produce one learned survival score per population member.
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.
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.
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")
49 raise ValueError(
"The embedding width must be divisible by the number of heads.")
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)
56 raise ValueError(f
"Provide {count} finite selector weights.")
60 self.
_blocks = tuple((*block[:4], block[4:6].reshape(width, 2 * width),
61 block[6:].reshape(2 * width, width))
for block
in blocks)
66 """Return a copy of the flat model weights."""
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
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
86 if not np.isfinite(scores).all():
87 raise FloatingPointError(
"The learned selector produced nonfinite scores.")
92 """Save the model geometry and weights."""
94 with open(path,
"wb")
as destination:
95 np.savez_compressed(destination, settings=settings, parameters=self.
_parameters)
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"])
112 """Evolve a population using Iso+LineDD and learned local competition.
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.
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.
130 _requires_proposed_genome =
True
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.")
137 self.
ind_domain = _variation_settings(ind_domain, 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)
149 """Reset the proposal stream and native counters."""
151 self.
_rng = np.random.default_rng(self.
seed)
155 if len(archive) < archive.capacity:
158 first, second = self.
_rng.integers(len(archive), size=2)
159 base_ind[:] = iso_line_dd(archive[first], archive[second], bounds=self.
ind_domain,
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.")
170 parents = list(archive)
171 combined = parents.copy()
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)
190 for individual
in combined:
191 if id(individual)
in slots:
192 archive.add(individual)
193 admitted.add(slots[id(individual)])