69 """Run the QD-Rec search loop using caller-supplied scoring and generation.
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.
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.
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):
94 self.
_contexts = _unit_rows(item_embeddings)
96 raise ValueError(
"Supply one embedding per distinct item.")
97 self.
_neighbors = _positive_int(neighbors,
"neighbors")
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.")
107 self.
_precision = np.eye(width) * prior_precision
110 np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
117 """Return an immutable snapshot of the recommendation entries."""
122 """Return cumulative callback and archive counters."""
127 """Return the highest pointwise score still in the archive."""
128 return max(self.
_archive, key=
lambda entry: entry.quality, default=
None)
134 sample = solve_triangular(lower.T, self.
_choose_rng.normal(size=len(lower)), lower=
False)
135 sample += cho_solve((lower,
True), self.
_response)
138 indices = list(dict.fromkeys(self.
_indices[row.recommendation.item]
for row
in self.
_archive))
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())
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.")
151 def _evaluate(self, pair, score, embed, novel, compare, *, seed_entry):
153 if pair
in self.
_seen:
154 self.
_counts[
"duplicates"] += 1
156 self.
_counts[
"embeddings"] += 1
157 embedding = np.asarray(embed(pair), dtype=float)
159 raise ValueError(
"Return a vector in a fixed pair embedding space.")
160 embedding, = _unit_rows(embedding[
None])
162 quality = float(score(pair))
163 if not 0. <= quality <= 1.:
164 raise ValueError(
"Return quality in [0, 1] for contextual bandit feedback.")
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.")
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])
188 if not (np.isfinite(precision).all()
and np.isfinite(response).all()):
189 raise FloatingPointError(
"The contextual posterior overflowed. Increase noise_variance.")
191 self.
_counts[
"bandit_updates"] += 1
195 entry =
QDRecEntry(pair, quality, tuple(map(float, embedding)))
200 self.
_counts[
"replacements"] += 1
201 self.
_counts[
"admissions"] += 1
204 def run(self, propose, score, embed, novel, compare, *, budget, initial=()):
205 """Return cumulative statistics after a fixed number of proposals.
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.
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)
221 raise ValueError(
"Use a nonnegative proposal budget.")
223 self.
_evaluate(pair, score, embed, novel, compare, seed_entry=
True)
224 for _
in range(budget):
228 parents = tuple(self.
_archive[i].recommendation
for i
in chosen)
231 self.
_evaluate(pair, score, embed, novel, compare, seed_entry=
False)
An evaluated archive entry with an independent pair embedding.
run(self, propose, score, embed, novel, compare, *, budget, initial=())
Warm-start from supplied recommendations and spend additional proposal calls.