QDpy
Loading...
Searching...
No Matches
prior_offline.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Search categorical configurations under frozen predictions and a bounded prior."""
7
8from dataclasses import dataclass
9
10import numpy as np
11
12from qdpy.phenotype import Features, Fitness, Individual
13from .modern import _positive_int
14from .offline import OfflineMAPElites, OfflineSearchResult, _empty_geometry, _frozen_matern
15from .task_search import _validate_grid
16
17__all__ = ["PriorGuidedOfflineMAPElites", "PriorGuidedSearchResult"]
18
19
20
21@dataclass(frozen=True)
23 """Each elite's scores include its selection score, uncertainty, and prior weight."""
24
25 prior_queries: int
26
27
28
30 """Use a frozen Matérn GP and a caller-supplied categorical prior.
31
32 Mutation samples single-locus changes and optionally chooses among
33 them using prior scores. At admission, increasing model uncertainty
34 increases the contribution of the prior to a normalized quality score.
35 The returned archive stores raw predicted quality and descriptors.
36 Disagreement is an acquisition signal and carries no coverage guarantee.
37
38 :param archive: Empty parentless best-only Grid or CVTGrid with one signed objective.
39 :param genomes: Integer training designs, one row per measurement.
40 :param fitnesses: Measured scalar qualities for the training designs.
41 :param descriptors: Measured descriptors for the training designs.
42 :param nvec: Number of zero-based categories in each locus.
43 :param prior: Callable scoring a design on [0, 1], with higher being more plausible.
44 :param prior_weight: Maximum fraction of the acquisition score determined by the prior.
45 :param uncertainty_scale: Predicted deviation at which the prior receives half its maximum weight.
46 Defaults to one quarter of the logged quality span.
47 :param uncertainty_penalty: Fixed standard-deviation penalty in quality units.
48 :param mutation_choices: Number of prior-scored edits per mutation.
49 :param proposal_strength: Inverse temperature applied to prior scores on edits.
50 :param length_scale: Fixed Matérn length scale on one-hot genomes.
51 :param noise: Positive GP covariance regularization.
52 :param seed: Private seed for seed selection and mutations.
53 """
54
55 def __init__(self, archive, genomes, fitnesses, descriptors, *, nvec, prior=None,
56 prior_weight=1., uncertainty_scale=None, uncertainty_penalty=0., mutation_choices=4,
57 proposal_strength=3., length_scale=1.8, noise=1e-6, seed=0):
58 _validate_grid(archive)
59 weights = archive.fitness_weights
60 if weights is None or archive.fitness_score_names or archive.features_score_names:
61 raise ValueError("Use native scores and an explicit nonzero fitness weight.")
62 counts = tuple(_positive_int(count, "category count") for count in nvec)
63 if not counts:
64 raise ValueError("Supply at least one locus.")
65 rows = np.asarray(genomes)
66 scores = np.asarray(fitnesses, dtype=float)
67 descriptors = np.asarray(descriptors, dtype=float)
68 if (rows.ndim != 2 or len(rows) < 2 or rows.shape[1] != len(counts)
69 or rows.dtype.kind not in "iu" or (rows < 0).any() or (rows >= counts).any()
70 or scores.shape != (len(rows),) or not np.isfinite(scores).all()
71 or descriptors.shape != (len(rows), len(archive.features_domain))
72 or not np.isfinite(descriptors).all()):
73 raise ValueError("Supply aligned finite measurements for valid categorical genomes.")
74 if (prior is not None and not callable(prior) or not 0. <= prior_weight <= 1.
75 or not 0. <= uncertainty_penalty < np.inf or not 0. <= proposal_strength < np.inf
76 or not 0. < length_scale < np.inf or not 0. < noise < np.inf):
77 raise ValueError("Provide a callable prior and finite, valid acquisition and GP settings.")
78 self._weights = weights
79 self._direction = 1. if weights[0] > 0. else -1.
80 minimum = float((self._direction * scores).min())
81 span = float((self._direction * scores).max()) - minimum
82 self._span = span or max(1., abs(minimum))
83 self._uncertainty = max(self._span / 4., np.finfo(float).tiny) if uncertainty_scale is None else uncertainty_scale
84 if not 0. < self._span < np.inf or not 0. < self._uncertainty < np.inf:
85 raise ValueError("The logged quality span and uncertainty scale must be finite.")
86 self._minimum = minimum
87 self._groups = counts
88 self._offsets = np.cumsum((0, *counts[:-1]))
89 self._movable = tuple(i for i, count in enumerate(counts) if count > 1)
90 self._rows = rows.astype(np.int64, copy=True)
91 self._geometry = _empty_geometry(archive)
92 self._model = _frozen_matern(self._encode(self._rows), np.column_stack((scores, descriptors)),
93 length_scale, noise)
94 self._prior = prior if prior_weight else None
95 self._weight, self._penalty = prior_weight, uncertainty_penalty
96 self._choices = _positive_int(mutation_choices, "mutation_choices")
97 self._strength = proposal_strength
98 self.seed = seed
99
100 def _encode(self, rows):
101 features = np.zeros((len(rows), sum(self._groups)))
102 features[np.arange(len(rows))[:, None], rows + self._offsets] = 1.
103 return features
104
105 def _acquire(self, mean, deviation, prior):
106 weight = (self._weight * (deviation / np.hypot(self._uncertainty, deviation))**2
107 if self._prior is not None else 0.)
108 normalized = (self._direction * mean - self._minimum) / self._span
109 quality = (1. - weight) * normalized + weight * prior - self._penalty * (deviation / self._span)
110 return float(quality), float(weight)
111
112 def _edit(self, point, rng):
113 if not self._movable:
114 return point
115 locus = self._movable[int(rng.integers(len(self._movable)))]
116 draw = int(rng.integers(self._groups[locus] - 1))
117 return (*point[:locus], draw + (draw >= point[locus]), *point[locus + 1:])
118
119
123 def run(self, budget, *, initial_samples=16):
124 """Make a new predicted archive and count every prior call."""
125 budget = _positive_int(budget, "budget")
126 initial = min(_positive_int(initial_samples, "initial_samples"), budget, len(self._rows))
127 rng = np.random.default_rng(self.seed)
128 seeds = rng.permutation(len(self._rows))[:initial]
129 archive = _empty_geometry(self._geometry)
130 winners = {}
131 prior_calls = 0
132
133 def prior_score(point):
134 nonlocal prior_calls
135 if self._prior is None:
136 return 0.
137 prior_calls += 1
138 value = float(self._prior(point))
139 if not 0. <= value <= 1.:
140 raise ValueError("The prior must return a finite score in [0, 1].")
141 return value
142
143 for step in range(budget):
144 if step < initial:
145 point = tuple(map(int, self._rows[seeds[step]]))
146 prior = prior_score(point)
147 else:
148 if winners:
149 parent = tuple(winners.values())[int(rng.integers(len(winners)))]
150 else:
151 parent = self._rows[int(rng.integers(len(self._rows)))]
152 parent = tuple(map(int, parent))
153 if self._prior is None or not self._strength:
154 point = self._edit(parent, rng)
155 prior = prior_score(point)
156 else:
157 edits = tuple(dict.fromkeys(self._edit(parent, rng) for _ in range(self._choices)))
158 ranking = np.asarray([prior_score(point) for point in edits])
159 weights = np.exp(self._strength * (ranking - ranking.max()))
160 selected = int(rng.choice(len(edits), p=weights / weights.sum()))
161 point, prior = edits[selected], ranking[selected]
162 mean, std = self._model.predict(self._encode(np.asarray([point])), return_std=True)
163 quality, *features = mean[0]
164 deviation = float(std[0, 0])
165 value, weight = self._acquire(quality, deviation, prior)
166 if not np.isfinite((value, quality, deviation, *features)).all():
167 raise ValueError("The frozen surrogate produced a nonfinite prediction or acquisition.")
168 if not (archive.in_bounds((quality,), archive.fitness_domain)
169 and archive.in_bounds(features, archive.features_domain)):
170 continue
171 cell = archive.index_grid(features)
172 previous = winners.get(cell)
173 if previous is None and len(winners) >= archive.capacity:
174 continue
175 if previous is None or value > previous.scores["acquisition"]:
176 winners[cell] = Individual(point, fitness=Fitness((quality,), weights=self._weights),
177 features=Features(features), scores={
178 "acquisition": value, "prediction_std": deviation,
179 "predicted_fitness": float(quality), "prior": prior,
180 "prior_fraction": weight,
181 })
182 archive.update(winners.values())
183 return PriorGuidedSearchResult(archive, budget, prior_calls)
184
185 verify = staticmethod(OfflineMAPElites.verify)
Predicted elites and number of proposals assessed by the frozen model.
Definition offline.py:26
Adapt prior-guided offline design to products of finite categories.
run(self, budget, *, initial_samples=16)
Search with a hard cap on frozen-model predictions.
Predicted raw-quality archive and the number of prior and model queries.
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405