QDpy
Loading...
Searching...
No Matches
qd_rec.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Provider-independent QD-Rec with a contextual linear bandit."""
7
8from collections import Counter
9from dataclasses import dataclass
10from operator import index
11from typing import Hashable
12
13import numpy as np
14from scipy.linalg import cho_solve, solve_triangular
15
16from .modern import _positive_int
17
18__all__ = ["QDRec", "QDRecEntry", "QDRecStats", "Recommendation"]
19
20
21
22@dataclass(frozen=True)
24 """Hold an immutable item identifier and a nonempty explanation."""
25
26 item: Hashable
27 hypothesis: str
28
29
30
31@dataclass(frozen=True)
33 """Store raw pointwise quality and a normalized cosine-search vector."""
34
35 recommendation: Recommendation
36 quality: float
37 embedding: tuple[float, ...]
38
39
40
41@dataclass(frozen=True)
43 """Count attempts, including callbacks that raise, and committed bandit updates."""
44
45 proposals: int = 0
46 embeddings: int = 0
47 scores: int = 0
48 novelty_checks: int = 0
49 comparisons: int = 0
50 duplicates: int = 0
51 admissions: int = 0
52 replacements: int = 0
53 bandit_updates: int = 0
54
55
56def _unit_rows(values):
57 matrix = np.asarray(values, dtype=float)
58 if (matrix.ndim != 2 or not all(matrix.shape) or not np.isfinite(matrix).all()):
59 raise ValueError("Supply a nonempty finite matrix of embeddings.")
60 scale = np.max(np.abs(matrix), axis=1, keepdims=True)
61 if np.any(scale == 0.):
62 raise ValueError("Cosine embeddings must be nonzero.")
63 scaled = matrix / scale
64 return scaled / np.linalg.norm(scaled, axis=1, keepdims=True)
65
66
67
68class QDRec:
69 """Run the QD-Rec search loop using caller-supplied scoring and generation.
70
71 Item embeddings guide the contextual bandit. Separate embeddings of
72 item-hypothesis pairs determine the archive neighborhood. A novel
73 recommendation enters the archive directly. Otherwise, a blind
74 comparison with its nearest neighbor determines replacement.
75 The bandit observes every scored and fully processed proposal,
76 including rejected ones.
77
78 :param items: Nonempty sequence of distinct hashable item identifiers.
79 :param item_embeddings: Aligned item embeddings, L2 normalized at construction.
80 :param neighbors: Number of recommendations passed to the novelty judge.
81 :param exemplars: Number of archive recommendations passed to the proposer.
82 :param diversity_weight: Weight of cosine novelty in the item acquisition.
83 :param prior_precision: Positive isotropic precision of the linear model's prior.
84 :param noise_variance: Positive observation variance of normalized rewards.
85 :param selection: "thompson" or "uniform". With zero exemplars, uniform
86 selection gives the independent proposal control.
87 :param seed: Private random seed for item selection, exemplars, and comparisons.
88 """
89
90 def __init__(self, items, item_embeddings, *, neighbors=3, exemplars=3, diversity_weight=1.,
91 prior_precision=1., noise_variance=.1, selection="thompson", seed=0):
92 self._items = tuple(items)
93 self._indices = {item: i for i, item in enumerate(self._items)}
94 self._contexts = _unit_rows(item_embeddings)
95 if len(self._contexts) != len(self._items) or len(self._indices) != len(self._items):
96 raise ValueError("Supply one embedding per distinct item.")
97 self._neighbors = _positive_int(neighbors, "neighbors")
98 self._exemplars = index(exemplars)
99 if (self._exemplars < 0 or not 0 <= diversity_weight < np.inf or not 0 < prior_precision < np.inf
100 or not np.finfo(float).tiny <= noise_variance < np.inf
101 or selection not in ("thompson", "uniform")):
102 raise ValueError("Use valid bandit scales, exemplar count, and selection strategy.")
103 self._diversity = diversity_weight
104 self._noise_precision = 1. / noise_variance
105 self._selection = selection
106 width = self._contexts.shape[1]
107 self._precision = np.eye(width) * prior_precision
108 self._response = np.zeros(width)
109 self._choose_rng, self._propose_rng, self._duel_rng = map(
110 np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
111 self._archive, self._seen = [], set()
112 self._embedding_size = None
113 self._counts = Counter()
114
115 @property
116 def archive(self):
117 """Return an immutable snapshot of the recommendation entries."""
118 return tuple(self._archive)
119
120 @property
121 def stats(self):
122 """Return cumulative callback and archive counters."""
123 return QDRecStats(**self._counts)
124
125 @property
126 def best(self):
127 """Return the highest pointwise score still in the archive."""
128 return max(self._archive, key=lambda entry: entry.quality, default=None)
129
130 def _choose(self):
131 if self._selection == "uniform":
132 return int(self._choose_rng.integers(len(self._items)))
133 lower = np.linalg.cholesky(self._precision)
134 sample = solve_triangular(lower.T, self._choose_rng.normal(size=len(lower)), lower=False)
135 sample += cho_solve((lower, True), self._response)
136 values = self._contexts @ sample
137 if self._archive and self._diversity:
138 indices = list(dict.fromkeys(self._indices[row.recommendation.item] for row in self._archive))
139 cosine = (self._contexts @ self._contexts[indices].T).max(axis=1)
140 values += self._diversity * (1. - np.clip(cosine, -1., 1.))
141 if not np.isfinite(values).all():
142 raise FloatingPointError("The contextual acquisition overflowed.")
143 return int(values.argmax())
144
145 def _recommendation(self, pair):
146 if (not isinstance(pair, Recommendation) or pair.item not in self._indices
147 or not isinstance(pair.hypothesis, str) or not pair.hypothesis.strip()):
148 raise ValueError("Supply a catalog item and a nonempty hypothesis.")
149 return pair
150
151 def _evaluate(self, pair, score, embed, novel, compare, *, seed_entry):
152 pair = self._recommendation(pair)
153 if pair in self._seen:
154 self._counts["duplicates"] += 1
155 return
156 self._counts["embeddings"] += 1
157 embedding = np.asarray(embed(pair), dtype=float)
158 if embedding.ndim != 1 or (self._embedding_size is not None and embedding.size != self._embedding_size):
159 raise ValueError("Return a vector in a fixed pair embedding space.")
160 embedding, = _unit_rows(embedding[None])
161 self._counts["scores"] += 1
162 quality = float(score(pair))
163 if not 0. <= quality <= 1.:
164 raise ValueError("Return quality in [0, 1] for contextual bandit feedback.")
165
166 admitted, replace = True, None
167 if self._archive and not seed_entry:
168 embeddings = np.asarray([row.embedding for row in self._archive])
169 nearest = np.argsort(-(embeddings @ embedding), kind="stable")[:self._neighbors]
170 neighbors = tuple(self._archive[i].recommendation for i in nearest)
171 self._counts["novelty_checks"] += 1
172 admitted = novel(pair, neighbors)
173 if not isinstance(admitted, (bool, np.bool_)):
174 raise ValueError("Novelty must return a Boolean.")
175 if not admitted:
176 slot = int(self._duel_rng.integers(2))
177 duel = (pair, neighbors[0]) if slot == 0 else (neighbors[0], pair)
178 self._counts["comparisons"] += 1
179 winner = index(compare(*duel))
180 if winner not in (0, 1):
181 raise ValueError("The comparison must return the winning index, 0 or 1.")
182 admitted = winner == slot
183 replace = int(nearest[0])
184
185 context = self._contexts[self._indices[pair.item]]
186 precision = self._precision + self._noise_precision * np.outer(context, context)
187 response = self._response + (quality * self._noise_precision) * context
188 if not (np.isfinite(precision).all() and np.isfinite(response).all()):
189 raise FloatingPointError("The contextual posterior overflowed. Increase noise_variance.")
190 self._precision, self._response = precision, response
191 self._counts["bandit_updates"] += 1
192 self._seen.add(pair)
193 self._embedding_size = embedding.size
194 if admitted:
195 entry = QDRecEntry(pair, quality, tuple(map(float, embedding)))
196 if replace is None:
197 self._archive.append(entry)
198 else:
199 self._archive[replace] = entry
200 self._counts["replacements"] += 1
201 self._counts["admissions"] += 1
202
203
204 def run(self, propose, score, embed, novel, compare, *, budget, initial=()):
205 """Return cumulative statistics after a fixed number of proposals.
206
207 :param propose: (item, exemplars, rng) -> hypothesis string.
208 :param score: Recommendation -> quality in [0, 1].
209 :param embed: Recommendation -> nonzero vector for cosine matching.
210 :param novel: (candidate, nearest_recommendations) -> Boolean.
211 :param compare: (first, second) -> index of the preferred recommendation.
212 The order is randomized and scores are withheld.
213 :param budget: Number of proposer calls. Duplicates still consume calls.
214 :param initial: Optional Recommendation seeds, scored separately
215 and admitted without local competition.
216 """
217 if not all(map(callable, (propose, score, embed, novel, compare))):
218 raise TypeError("Provide five callable generation and evaluation functions.")
219 budget = index(budget)
220 if budget < 0:
221 raise ValueError("Use a nonnegative proposal budget.")
222 for pair in tuple(map(self._recommendation, initial)):
223 self._evaluate(pair, score, embed, novel, compare, seed_entry=True)
224 for _ in range(budget):
225 item = self._items[self._choose()]
226 count = min(self._exemplars, len(self._archive))
227 chosen = self._propose_rng.choice(len(self._archive), size=count, replace=False)
228 parents = tuple(self._archive[i].recommendation for i in chosen)
229 self._counts["proposals"] += 1
230 pair = Recommendation(item, propose(item, parents, self._propose_rng))
231 self._evaluate(pair, score, embed, novel, compare, seed_entry=False)
232 return self.stats
An evaluated archive entry with an independent pair embedding.
Definition qd_rec.py:32
Count the different callbacks involved in proposal and local competition.
Definition qd_rec.py:42
Evolve explanations with Thompson item selection and blind local competition.
Definition qd_rec.py:68
_evaluate(self, pair, score, embed, novel, compare, *, seed_entry)
Definition qd_rec.py:151
run(self, propose, score, embed, novel, compare, *, budget, initial=())
Warm-start from supplied recommendations and spend additional proposal calls.
Definition qd_rec.py:204
One catalog item and a proposed reason for choosing it.
Definition qd_rec.py:23