QDpy
Loading...
Searching...
No Matches
divhf.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Use human judgments about the most and least similar pair of three behaviors."""
7
8from copy import copy
9from dataclasses import dataclass
10from functools import partial
11from operator import index
12import warnings
13
14import numpy as np
15from scipy.special import expit
16
17from .qdhf import QDHFResult, TripletProjector, _feedback_search
18
19__all__ = ["DivHFJudgment", "DivHFProjector", "DivHFResult", "divhf_search"]
20
21_TRIPLET_PAIRS = ((0, 1), (0, 2), (1, 2))
22
23
24
26 """Train on anchor, near, far index triples using log likelihood.
27
28 Two distinct pairs in a triplet share one anchor. Similarity is
29 negative squared Euclidean distance in the projected coordinates.
30 A small weight penalty regularizes otherwise separable comparisons.
31
32 :param raw_feature_size: Input width.
33 :param descriptor_size: Learned coordinate width.
34 :param temperature: Positive divisor for the difference in similarities.
35 :param regularization: Nonnegative squared-weight penalty.
36 :param seed: Initial projection seed.
37 """
38
39 def __init__(self, raw_feature_size, descriptor_size, *, temperature=.1, regularization=1e-3, seed=0):
40 super().__init__(raw_feature_size, descriptor_size, seed=seed)
41 if not 0 < temperature < np.inf or not 0 <= regularization < np.inf:
42 raise ValueError("Specify finite, positive temperature and nonnegative regularization.")
43 self.temperature, self.regularization = temperature, regularization
44
45 def fit(self, raw_features, triplets, *, steps=128, batch_size=32, learning_rate=.01, seed=0):
46 """Fit probabilities for anchor, closer, farther labels by minimizing cross-entropy."""
47 return super().fit(raw_features, triplets, steps=steps, batch_size=batch_size,
48 learning_rate=learning_rate, seed=seed)
49
50 def _loss_gradient(self, dp, dn, zp, zn, weights):
51 diff = (np.sum(zp ** 2, axis=1) - np.sum(zn ** 2, axis=1)) / self.temperature
52 weight = expit(diff)[:, None]
53 likelihood = 2. / len(dp) * (dp.T @ (weight * zp) - dn.T @ (weight * zn)) / self.temperature
54 return likelihood + 2. * self.regularization * weights
55
56
57
58@dataclass(frozen=True)
60 """Use pair indices 0 for (0,1), 1 for (0,2), and 2 for (1,2)."""
61
62 attempts: tuple[int, int, int]
63 pairs: tuple[int, int] | None
64
65
66
67@dataclass(frozen=True)
69 """Each query stores the original pair ranking or an abstention."""
70
71 projector: DivHFProjector
72 feedback: tuple[DivHFJudgment, ...]
73
74
75def _anchored(rows, pairs):
76 first, second = map(_TRIPLET_PAIRS.__getitem__, pairs)
77 anchor = next(slot for slot in first if slot in second)
78 return rows[anchor], rows[sum(first) - anchor], rows[sum(second) - anchor]
79
80
81def _refit_pairs(projector, trials, feedback, log, requests, rng, fit_steps):
82 if len(trials) < 3 or requests == 0:
83 return projector
84 labels = []
85 for _ in range(requests):
86 rows = tuple(map(int, rng.choice(len(trials), size=3, replace=False)))
87 pairs = feedback(*(trials[i] for i in rows))
88 if pairs is not None:
89 pairs = tuple(map(index, pairs))
90 if len(pairs) != 2 or len(set(pairs)) != 2 or any(pair not in range(3) for pair in pairs):
91 raise ValueError("Return distinct closest and farthest pair indices in [0, 2], or None.")
92 labels.append(_anchored(rows, pairs))
93 log.append(DivHFJudgment(tuple(trials[i].attempt for i in rows), pairs))
94 if not labels:
95 return projector
96 try:
97 return copy(projector).fit([row.raw_features for row in trials], labels,
98 steps=fit_steps, seed=int(rng.integers(2**32)))
99 except FloatingPointError as error:
100 warnings.warn(f"Skipped DivHF projection update: {error}", stacklevel=3)
101 return projector
102
103
104
121def divhf_search(evaluate, archive, *, feedback, budget, feedback_budget, dimension,
122 raw_feature_size, ind_domain=(0., 1.), warmup=64, refit_every=None,
123 feedback_batch=24, fit_steps=128, temperature=.1, regularization=1e-3, seed=0):
124 """Compare the two labeled extremes and fit a probabilistic projection.
125
126 For example, (1, 0) says records 0 and 2 are closest and records 0
127 and 1 are farthest apart. A skipped query still consumes one
128 annotation. Reuse QDHF's cached archive rebuild when refitting.
129 """
130 projector = partial(DivHFProjector, temperature=temperature, regularization=regularization)
131 return _feedback_search(evaluate, archive, feedback=feedback, budget=budget, feedback_budget=feedback_budget,
132 dimension=dimension, raw_feature_size=raw_feature_size, ind_domain=ind_domain,
133 warmup=warmup, refit_every=refit_every, feedback_batch=feedback_batch,
134 fit_steps=fit_steps, seed=seed, make_projector=projector, refit=_refit_pairs,
135 result_type=DivHFResult)
Ordered query IDs and the indices of the closest and farthest pairs.
Definition divhf.py:59
Fit a linear descriptor with Bradley-Terry preference likelihoods.
Definition divhf.py:25
fit(self, raw_features, triplets, *, steps=128, batch_size=32, learning_rate=.01, seed=0)
Definition divhf.py:45
Learned archive, projection, evaluator costs, and query log.
Definition divhf.py:68
Final QDHF search state and independent evaluation and annotation counts.
Definition qdhf.py:129
Learn a linear map using a squared-Euclidean triplet margin.
Definition qdhf.py:24