Source code for qdpy.algorithms.divhf

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Learn behavior descriptors from ranked pairs in each annotated triplet.
# @see https://doi.org/10.1007/s11704-025-41167-w

"""Use human judgments about the most and least similar pair of three behaviors."""

from copy import copy
from dataclasses import dataclass
from functools import partial
from operator import index
import warnings

import numpy as np
from scipy.special import expit

from .qdhf import QDHFResult, TripletProjector, _feedback_search

__all__ = ["DivHFJudgment", "DivHFProjector", "DivHFResult", "divhf_search"]

_TRIPLET_PAIRS = ((0, 1), (0, 2), (1, 2))


## @brief Fit a linear descriptor with Bradley-Terry preference likelihoods.
[docs] class DivHFProjector(TripletProjector): """Train on anchor, near, far index triples using log likelihood. Two distinct pairs in a triplet share one anchor. Similarity is negative squared Euclidean distance in the projected coordinates. A small weight penalty regularizes otherwise separable comparisons. :param raw_feature_size: Input width. :param descriptor_size: Learned coordinate width. :param temperature: Positive divisor for the difference in similarities. :param regularization: Nonnegative squared-weight penalty. :param seed: Initial projection seed. """ def __init__(self, raw_feature_size, descriptor_size, *, temperature=.1, regularization=1e-3, seed=0): super().__init__(raw_feature_size, descriptor_size, seed=seed) if not 0 < temperature < np.inf or not 0 <= regularization < np.inf: raise ValueError("Specify finite, positive temperature and nonnegative regularization.") self.temperature, self.regularization = temperature, regularization
[docs] def fit(self, raw_features, triplets, *, steps=128, batch_size=32, learning_rate=.01, seed=0): """Fit probabilities for anchor, closer, farther labels by minimizing cross-entropy.""" return super().fit(raw_features, triplets, steps=steps, batch_size=batch_size, learning_rate=learning_rate, seed=seed)
def _loss_gradient(self, dp, dn, zp, zn, weights): diff = (np.sum(zp ** 2, axis=1) - np.sum(zn ** 2, axis=1)) / self.temperature weight = expit(diff)[:, None] likelihood = 2. / len(dp) * (dp.T @ (weight * zp) - dn.T @ (weight * zn)) / self.temperature return likelihood + 2. * self.regularization * weights
## @brief Ordered query IDs and the indices of the closest and farthest pairs.
[docs] @dataclass(frozen=True) class DivHFJudgment: """Use pair indices 0 for (0,1), 1 for (0,2), and 2 for (1,2).""" attempts: tuple[int, int, int] pairs: tuple[int, int] | None
## @brief Learned archive, projection, evaluator costs, and query log.
[docs] @dataclass(frozen=True) class DivHFResult(QDHFResult): """Each query stores the original pair ranking or an abstention.""" projector: DivHFProjector feedback: tuple[DivHFJudgment, ...]
def _anchored(rows, pairs): first, second = map(_TRIPLET_PAIRS.__getitem__, pairs) anchor = next(slot for slot in first if slot in second) return rows[anchor], rows[sum(first) - anchor], rows[sum(second) - anchor] def _refit_pairs(projector, trials, feedback, log, requests, rng, fit_steps): if len(trials) < 3 or requests == 0: return projector labels = [] for _ in range(requests): rows = tuple(map(int, rng.choice(len(trials), size=3, replace=False))) pairs = feedback(*(trials[i] for i in rows)) if pairs is not None: pairs = tuple(map(index, pairs)) if len(pairs) != 2 or len(set(pairs)) != 2 or any(pair not in range(3) for pair in pairs): raise ValueError("Return distinct closest and farthest pair indices in [0, 2], or None.") labels.append(_anchored(rows, pairs)) log.append(DivHFJudgment(tuple(trials[i].attempt for i in rows), pairs)) if not labels: return projector try: return copy(projector).fit([row.raw_features for row in trials], labels, steps=fit_steps, seed=int(rng.integers(2**32))) except FloatingPointError as error: warnings.warn(f"Skipped DivHF projection update: {error}", stacklevel=3) return projector ## @brief Illuminate descriptors trained from closest and farthest pairs. # @param evaluate Callable (genome) returning finite scalar fitness and raw features. # @param archive Empty rectangular grid for learned descriptor coordinates. # @param feedback Callable of three trials returning two pair indices or None. # @param budget Total candidate evaluations. # @param feedback_budget Hard query budget including abstentions. # @param dimension Real genome width. # @param raw_feature_size Raw descriptor width. # @param ind_domain Common finite genome bounds. # @param warmup Number of uniform trials to collect before the first fit. # @param refit_every Attempts between online fits, or None for a single offline fit. # @param feedback_batch Maximum queries at an online refit. # @param fit_steps Adam steps per fit. # @param temperature Positive preference temperature. # @param regularization Nonnegative squared-weight penalty. # @param seed Private root seed. # @return DivHFResult with attempted evaluations and a replayable query log.