Source code for qdpy.algorithms.qd_rec

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Discover diverse explanations for items from a fixed catalog.
# @see https://arxiv.org/abs/2610.23470

"""Provider-independent QD-Rec with a contextual linear bandit."""

from collections import Counter
from dataclasses import dataclass
from operator import index
from typing import Hashable

import numpy as np
from scipy.linalg import cho_solve, solve_triangular

from .modern import _positive_int

__all__ = ["QDRec", "QDRecEntry", "QDRecStats", "Recommendation"]


## @brief One catalog item and a proposed reason for choosing it.
[docs] @dataclass(frozen=True) class Recommendation: """Hold an immutable item identifier and a nonempty explanation.""" item: Hashable hypothesis: str
## @brief An evaluated archive entry with an independent pair embedding.
[docs] @dataclass(frozen=True) class QDRecEntry: """Store raw pointwise quality and a normalized cosine-search vector.""" recommendation: Recommendation quality: float embedding: tuple[float, ...]
## @brief Count the different callbacks involved in proposal and local competition.
[docs] @dataclass(frozen=True) class QDRecStats: """Count attempts, including callbacks that raise, and committed bandit updates.""" proposals: int = 0 embeddings: int = 0 scores: int = 0 novelty_checks: int = 0 comparisons: int = 0 duplicates: int = 0 admissions: int = 0 replacements: int = 0 bandit_updates: int = 0
def _unit_rows(values): matrix = np.asarray(values, dtype=float) if (matrix.ndim != 2 or not all(matrix.shape) or not np.isfinite(matrix).all()): raise ValueError("Supply a nonempty finite matrix of embeddings.") scale = np.max(np.abs(matrix), axis=1, keepdims=True) if np.any(scale == 0.): raise ValueError("Cosine embeddings must be nonzero.") scaled = matrix / scale return scaled / np.linalg.norm(scaled, axis=1, keepdims=True) ## @brief Evolve explanations with Thompson item selection and blind local competition.
[docs] class QDRec: """Run the QD-Rec search loop using caller-supplied scoring and generation. Item embeddings guide the contextual bandit. Separate embeddings of item-hypothesis pairs determine the archive neighborhood. A novel recommendation enters the archive directly. Otherwise, a blind comparison with its nearest neighbor determines replacement. The bandit observes every scored and fully processed proposal, including rejected ones. :param items: Nonempty sequence of distinct hashable item identifiers. :param item_embeddings: Aligned item embeddings, L2 normalized at construction. :param neighbors: Number of recommendations passed to the novelty judge. :param exemplars: Number of archive recommendations passed to the proposer. :param diversity_weight: Weight of cosine novelty in the item acquisition. :param prior_precision: Positive isotropic precision of the linear model's prior. :param noise_variance: Positive observation variance of normalized rewards. :param selection: "thompson" or "uniform". With zero exemplars, uniform selection gives the independent proposal control. :param seed: Private random seed for item selection, exemplars, and comparisons. """ def __init__(self, items, item_embeddings, *, neighbors=3, exemplars=3, diversity_weight=1., prior_precision=1., noise_variance=.1, selection="thompson", seed=0): self._items = tuple(items) self._indices = {item: i for i, item in enumerate(self._items)} self._contexts = _unit_rows(item_embeddings) if len(self._contexts) != len(self._items) or len(self._indices) != len(self._items): raise ValueError("Supply one embedding per distinct item.") self._neighbors = _positive_int(neighbors, "neighbors") self._exemplars = index(exemplars) if (self._exemplars < 0 or not 0 <= diversity_weight < np.inf or not 0 < prior_precision < np.inf or not np.finfo(float).tiny <= noise_variance < np.inf or selection not in ("thompson", "uniform")): raise ValueError("Use valid bandit scales, exemplar count, and selection strategy.") self._diversity = diversity_weight self._noise_precision = 1. / noise_variance self._selection = selection width = self._contexts.shape[1] self._precision = np.eye(width) * prior_precision self._response = np.zeros(width) self._choose_rng, self._propose_rng, self._duel_rng = map( np.random.default_rng, np.random.SeedSequence(seed).spawn(3)) self._archive, self._seen = [], set() self._embedding_size = None self._counts = Counter() @property def archive(self): """Return an immutable snapshot of the recommendation entries.""" return tuple(self._archive) @property def stats(self): """Return cumulative callback and archive counters.""" return QDRecStats(**self._counts) @property def best(self): """Return the highest pointwise score still in the archive.""" return max(self._archive, key=lambda entry: entry.quality, default=None) def _choose(self): if self._selection == "uniform": return int(self._choose_rng.integers(len(self._items))) lower = np.linalg.cholesky(self._precision) sample = solve_triangular(lower.T, self._choose_rng.normal(size=len(lower)), lower=False) sample += cho_solve((lower, True), self._response) values = self._contexts @ sample if self._archive and self._diversity: indices = list(dict.fromkeys(self._indices[row.recommendation.item] for row in self._archive)) cosine = (self._contexts @ self._contexts[indices].T).max(axis=1) values += self._diversity * (1. - np.clip(cosine, -1., 1.)) if not np.isfinite(values).all(): raise FloatingPointError("The contextual acquisition overflowed.") return int(values.argmax()) def _recommendation(self, pair): if (not isinstance(pair, Recommendation) or pair.item not in self._indices or not isinstance(pair.hypothesis, str) or not pair.hypothesis.strip()): raise ValueError("Supply a catalog item and a nonempty hypothesis.") return pair def _evaluate(self, pair, score, embed, novel, compare, *, seed_entry): pair = self._recommendation(pair) if pair in self._seen: self._counts["duplicates"] += 1 return self._counts["embeddings"] += 1 embedding = np.asarray(embed(pair), dtype=float) if embedding.ndim != 1 or (self._embedding_size is not None and embedding.size != self._embedding_size): raise ValueError("Return a vector in a fixed pair embedding space.") embedding, = _unit_rows(embedding[None]) self._counts["scores"] += 1 quality = float(score(pair)) if not 0. <= quality <= 1.: raise ValueError("Return quality in [0, 1] for contextual bandit feedback.") admitted, replace = True, None if self._archive and not seed_entry: embeddings = np.asarray([row.embedding for row in self._archive]) nearest = np.argsort(-(embeddings @ embedding), kind="stable")[:self._neighbors] neighbors = tuple(self._archive[i].recommendation for i in nearest) self._counts["novelty_checks"] += 1 admitted = novel(pair, neighbors) if not isinstance(admitted, (bool, np.bool_)): raise ValueError("Novelty must return a Boolean.") if not admitted: slot = int(self._duel_rng.integers(2)) duel = (pair, neighbors[0]) if slot == 0 else (neighbors[0], pair) self._counts["comparisons"] += 1 winner = index(compare(*duel)) if winner not in (0, 1): raise ValueError("The comparison must return the winning index, 0 or 1.") admitted = winner == slot replace = int(nearest[0]) context = self._contexts[self._indices[pair.item]] precision = self._precision + self._noise_precision * np.outer(context, context) response = self._response + (quality * self._noise_precision) * context if not (np.isfinite(precision).all() and np.isfinite(response).all()): raise FloatingPointError("The contextual posterior overflowed. Increase noise_variance.") self._precision, self._response = precision, response self._counts["bandit_updates"] += 1 self._seen.add(pair) self._embedding_size = embedding.size if admitted: entry = QDRecEntry(pair, quality, tuple(map(float, embedding))) if replace is None: self._archive.append(entry) else: self._archive[replace] = entry self._counts["replacements"] += 1 self._counts["admissions"] += 1 ## @brief Warm-start from supplied recommendations and spend additional proposal calls.
[docs] def run(self, propose, score, embed, novel, compare, *, budget, initial=()): """Return cumulative statistics after a fixed number of proposals. :param propose: (item, exemplars, rng) -> hypothesis string. :param score: Recommendation -> quality in [0, 1]. :param embed: Recommendation -> nonzero vector for cosine matching. :param novel: (candidate, nearest_recommendations) -> Boolean. :param compare: (first, second) -> index of the preferred recommendation. The order is randomized and scores are withheld. :param budget: Number of proposer calls. Duplicates still consume calls. :param initial: Optional Recommendation seeds, scored separately and admitted without local competition. """ if not all(map(callable, (propose, score, embed, novel, compare))): raise TypeError("Provide five callable generation and evaluation functions.") budget = index(budget) if budget < 0: raise ValueError("Use a nonnegative proposal budget.") for pair in tuple(map(self._recommendation, initial)): self._evaluate(pair, score, embed, novel, compare, seed_entry=True) for _ in range(budget): item = self._items[self._choose()] count = min(self._exemplars, len(self._archive)) chosen = self._propose_rng.choice(len(self._archive), size=count, replace=False) parents = tuple(self._archive[i].recommendation for i in chosen) self._counts["proposals"] += 1 pair = Recommendation(item, propose(item, parents, self._propose_rng)) self._evaluate(pair, score, embed, novel, compare, seed_entry=False) return self.stats