QDpy
Loading...
Searching...
No Matches
qdhf.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Offline and iterative Quality Diversity through Human Feedback."""
6
7from copy import copy
8from dataclasses import dataclass
9from math import isfinite
10from operator import index
11import warnings
12
13import numpy as np
14
15from qdpy.containers import Grid
16from qdpy.tools import iso_line_dd
17from .modern import _positive_int
18from .task_search import _measure, _offer, _search_bounds, _validate_grid
19
20__all__ = ["TripletProjector", "QDHFTrial", "TripletJudgment", "QDHFResult", "qdhf_search"]
21
22
23
25 """Project fixed-width raw features into a lower-dimensional space.
26
27 For each labelled triplet, fit a linear map so the anchor is closer
28 to the preferred point than to the other point by at least the margin.
29 Distances in the training loss are squared Euclidean distances.
30
31 :param raw_feature_size: Number of input coordinates after feature extraction.
32 :param descriptor_size: Number of learned descriptor coordinates.
33 :param margin: Positive target gap between squared distances.
34 :param seed: Seed for the initial projection.
35 """
36
37 def __init__(self, raw_feature_size, descriptor_size, *, margin=0.05, seed=0):
38 self.raw_feature_size = _positive_int(raw_feature_size, "raw_feature_size")
39 self.descriptor_size = _positive_int(descriptor_size, "descriptor_size")
40 if self.descriptor_size > self.raw_feature_size or not isfinite(margin) or margin <= 0:
41 raise ValueError("Provide a positive margin and at most one descriptor axis per input coordinate.")
42 self.margin = margin
43 self._weights = np.random.default_rng(seed).normal(
44 scale=0.1 / np.sqrt(raw_feature_size), size=(raw_feature_size, descriptor_size))
45
46 def _features(self, values):
47 values = np.asarray(values, dtype=float)
48 if (values.ndim not in (1, 2) or values.shape[-1] != self.raw_feature_size
49 or not np.isfinite(values).all()):
50 raise ValueError("Raw features must be finite vectors of the configured length.")
51 return values
52
53
54 def fit(self, raw_features, triplets, *, steps=128, batch_size=32, learning_rate=0.01, seed=0):
55 """Use Adam on the triplet hinge loss and return the fitted projector.
56
57 Each row of ``triplets`` gives three distinct row indices into
58 ``raw_features``: anchor, preferred neighbor, other candidate.
59 Training starts with the current projection and independent Adam
60 moments. Commit the updated weights only after a finite fit.
61 """
62 features = self._features(raw_features)
63 triplets = np.asarray(triplets)
64 if (features.ndim != 2 or triplets.ndim != 2 or triplets.shape[1] != 3 or not len(triplets)
65 or not np.issubdtype(triplets.dtype, np.integer)
66 or np.any(triplets < 0) or np.any(triplets >= len(features))
67 or np.any(np.diff(np.sort(triplets, axis=1), axis=1) == 0)):
68 raise ValueError("Supply a nonempty array of distinct, in-range triplet indices.")
69 if not isfinite(learning_rate) or learning_rate <= 0:
70 raise ValueError("Provide a finite positive learning rate.")
71 steps = _positive_int(steps, "steps")
72 batch_size = min(len(triplets), _positive_int(batch_size, "batch_size"))
73 generator = np.random.default_rng(seed)
74 anchors, near, far = features[triplets].transpose(1, 0, 2)
75 positive, negative = anchors - near, anchors - far
76 weights = self._weights.copy()
77 first = np.zeros_like(weights)
78 second = np.zeros_like(weights)
79 with np.errstate(over="raise", invalid="raise"):
80 for step in range(1, steps + 1):
81 rows = generator.choice(len(triplets), size=batch_size, replace=False)
82 dp, dn = positive[rows], negative[rows]
83 zp, zn = dp @ weights, dn @ weights
84 grad = self._loss_gradient(dp, dn, zp, zn, weights)
85 first = 0.9 * first + 0.1 * grad
86 second = 0.999 * second + 0.001 * grad ** 2
87 weights -= learning_rate * (first / (1 - 0.9 ** step)) / (
88 np.sqrt(second / (1 - 0.999 ** step)) + 1e-8)
89 if not np.isfinite(weights).all():
90 raise FloatingPointError("The triplet update produced nonfinite weights.")
91 self._weights = weights
92 return self
93
94 def _loss_gradient(self, dp, dn, zp, zn, weights):
95 active = self.margin + np.sum(zp ** 2, axis=1) - np.sum(zn ** 2, axis=1) > 0
96 return 2. / len(dp) * (dp[active].T @ zp[active] - dn[active].T @ zn[active])
97
98
99 def transform(self, raw_features):
100 """Return descriptor coordinates in the units of the trained projection."""
101 projected = self._features(raw_features) @ self._weights
102 if not np.isfinite(projected).all():
103 raise ValueError("The projection produced nonfinite descriptors.")
104 return projected
105
106
107
108@dataclass(frozen=True)
110 """One evaluated genome with a one-based attempt ID, fitness, and raw features."""
111
112 attempt: int
113 genome: tuple[float, ...]
114 fitness: float
115 raw_features: tuple[float, ...]
116
117
118
119@dataclass(frozen=True)
121 """IDs are in anchor, first alternative, second alternative order."""
122
123 attempts: tuple[int, int, int]
124 choice: int | None
125
126
127
128@dataclass(frozen=True)
130 """Feedback includes abstentions. Fits count successful projection updates."""
131
132 archive: Grid
133 projector: TripletProjector
134 attempts: int
135 failures: int
136 feedback: tuple[TripletJudgment, ...]
137 fits: int
138
139
140def _place(grid, records, projector, trial):
141 measurement = _measure(grid, lambda: ((trial.fitness,), projector.transform(trial.raw_features)),
142 (), trial.genome)
143 if measurement is None or measurement[1] is None:
144 return
145 candidate, cell = measurement
146 front = grid.solutions[cell]
147 previous = int(front[0].name) if front else None
148 candidate.name = str(trial.attempt)
149 added = grid.nb_added
150 _offer(grid, measurement)
151 if grid.nb_added != added:
152 records.pop(previous, None)
153 records[trial.attempt] = trial
154
155
156def _rebin(template, projector, trials):
157 grid = Grid(shape=template.shape, features_domain=template.features_domain,
158 fitness_domain=template.fitness_domain, fitness_weights=template.fitness_weights,
159 fitness_score_names=template.fitness_score_names,
160 features_score_names=template.features_score_names, name=template.name,
161 storage_type=type(template.items), capacity=template.capacity)
162 records = {}
163 for trial in trials:
164 _place(grid, records, projector, trial)
165 return grid, records
166
167
168def _refit(projector, trials, feedback, log, requests, rng, fit_steps):
169 if len(trials) < 3 or requests == 0:
170 return projector
171 labels = []
172 for _ in range(requests):
173 a, b, c = map(int, rng.choice(len(trials), size=3, replace=False))
174 choice = feedback(trials[a], trials[b], trials[c])
175 if choice not in (None, 0, 1):
176 raise ValueError("A feedback callback must return 0, 1, or None.")
177 if choice is not None:
178 choice = int(choice)
179 log.append(TripletJudgment((trials[a].attempt, trials[b].attempt, trials[c].attempt), choice))
180 if choice is not None:
181 labels.append((a, b, c) if choice == 0 else (a, c, b))
182 if not labels:
183 return projector
184 try:
185 return copy(projector).fit([trial.raw_features for trial in trials], labels,
186 steps=fit_steps, seed=int(rng.integers(2**32)))
187 except FloatingPointError as error:
188 warnings.warn(f"Skipped QDHF projection update: {error}", stacklevel=3)
189 return projector
190
191
192
193def qdhf_search(evaluate, archive, *, feedback, budget, feedback_budget, dimension,
194 raw_feature_size, ind_domain=(0., 1.), warmup=64, refit_every=112,
195 feedback_batch=24, fit_steps=128, seed=0):
196 """Learn a descriptor on random trials and optionally on the evolving archive.
197
198 :param evaluate: Function of a genome tuple returning scalar fitness and a
199 raw feature vector in fixed units.
200 :param archive: Empty, parentless, one-elite rectangular Grid used as
201 a template. Learned coordinates use its existing descriptor bounds.
202 :param feedback: Function of three QDHFTrial records. Return 0 for the
203 second record, 1 for the third, or None to abstain.
204 :param budget: Hard budget of attempted evaluator calls, including warm-up.
205 :param feedback_budget: Hard budget of feedback calls, including abstentions.
206 :param dimension: Number of bounded real genome coordinates.
207 :param raw_feature_size: Length of the evaluator's raw feature vector.
208 :param ind_domain: Shared lower and upper genome bounds.
209 :param warmup: Number of uniform candidate attempts before the first fit.
210 :param refit_every: Attempts between online feedback rounds. None requests
211 the entire annotation budget at warm-up and freezes the projection.
212 :param feedback_batch: Maximum number of requests per online feedback round.
213 :param fit_steps: Adam update steps per fit.
214 :param seed: Root seed for independent variation and feedback streams.
215 :returns: Final archive, projector, attempted evaluations, failures, and labels.
216 """
217 return _feedback_search(evaluate, archive, feedback=feedback, budget=budget, feedback_budget=feedback_budget,
218 dimension=dimension, raw_feature_size=raw_feature_size, ind_domain=ind_domain,
219 warmup=warmup, refit_every=refit_every, feedback_batch=feedback_batch,
220 fit_steps=fit_steps, seed=seed, make_projector=TripletProjector, refit=_refit)
221
222
223def _feedback_search(evaluate, archive, *, feedback, budget, feedback_budget, dimension, raw_feature_size,
224 ind_domain, warmup, refit_every, feedback_batch, fit_steps, seed, make_projector, refit,
225 result_type=QDHFResult):
226 _validate_grid(archive)
227 if type(archive) is not Grid or any(not isfinite(v) or low >= high
228 for low, high in archive.features_domain for v in (low, high)):
229 raise ValueError("Supply a rectangular grid with finite increasing descriptor bounds.")
230 if not callable(evaluate) or not callable(feedback):
231 raise TypeError("Supply evaluator and feedback callables.")
232 budget = _positive_int(budget, "budget")
233 dimension = _positive_int(dimension, "dimension")
234 warmup = min(budget, _positive_int(warmup, "warmup"))
235 feedback_budget = index(feedback_budget)
236 if feedback_budget < 0:
237 raise ValueError("The feedback budget cannot be negative.")
238 feedback_batch = _positive_int(feedback_batch, "feedback_batch")
239 fit_steps = _positive_int(fit_steps, "fit_steps")
240 if refit_every is not None:
241 refit_every = _positive_int(refit_every, "refit_every")
242 bounds = _search_bounds(ind_domain)
243 variation_seed, label_seed, projection_seed = np.random.SeedSequence(seed).spawn(3)
244 variation = np.random.default_rng(variation_seed)
245 labels = np.random.default_rng(label_seed)
246 projector = make_projector(raw_feature_size, len(archive.shape), seed=projection_seed)
247 grid, records = _rebin(archive, projector, ())
248 if grid.fitness_weights is None:
249 grid._set_fitness_weights((1.,))
250 initial, log = [], []
251 failures = fits = 0
252
253 for attempt in range(1, budget + 1):
254 if attempt <= warmup or not grid:
255 genome = tuple(variation.uniform(*bounds, size=dimension))
256 else:
257 i, j = variation.integers(len(grid), size=2)
258 genome = tuple(iso_line_dd(grid[i], grid[j], rng=variation, bounds=bounds,
259 iso_sigma=0.01 * (bounds[1] - bounds[0])))
260 try:
261 fitness, raw = evaluate(genome)
262 raw = projector._features(raw)
263 if raw.ndim != 1 or not isfinite(fitness):
264 raise ValueError("Expected scalar finite fitness and one raw feature vector.")
265 trial = QDHFTrial(attempt, genome, float(fitness), tuple(raw))
266 except Exception as error:
267 failures += 1
268 warnings.warn(f"QDHF evaluation failed: {error}", stacklevel=2)
269 else:
270 if attempt <= warmup:
271 initial.append(trial)
272 else:
273 _place(grid, records, projector, trial)
274
275 remaining = feedback_budget - len(log)
276 if attempt == warmup:
277 requests = remaining if refit_every is None else min(remaining, feedback_batch)
278 updated = refit(projector, initial, feedback, log, requests, labels, fit_steps)
279 grid, records = _rebin(grid, updated, initial)
280 initial.clear()
281 elif attempt > warmup and refit_every is not None and remaining and (attempt - warmup) % refit_every == 0:
282 trials = list(records.values())
283 updated = refit(projector, trials, feedback, log, min(remaining, feedback_batch), labels, fit_steps)
284 if updated is not projector:
285 grid, records = _rebin(grid, updated, trials)
286 else:
287 continue
288
289 fits += updated is not projector
290 projector = updated
291
292 return result_type(grid, projector, budget, failures, tuple(log), fits)
Final QDHF search state and independent evaluation and annotation counts.
Definition qdhf.py:129
An immutable behavior record shown to a feedback provider.
Definition qdhf.py:109
The requested triplet's attempt IDs and the provider's response.
Definition qdhf.py:120
Learn a linear map using a squared-Euclidean triplet margin.
Definition qdhf.py:24
fit(self, raw_features, triplets, *, steps=128, batch_size=32, learning_rate=0.01, seed=0)
Fit or fine-tune the map using an array of labelled indices.
Definition qdhf.py:54
_loss_gradient(self, dp, dn, zp, zn, weights)
Definition qdhf.py:94
transform(self, raw_features)
Apply the same projection to one vector or a matrix of row vectors.
Definition qdhf.py:99