Source code for qdpy.algorithms.soft_prompt

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Budgeted QD search over frozen-model input embeddings.
# @see https://doi.org/10.1145/3795095.3805183

"""Evolve a soft prompt by decoding its embedding and measuring its output."""

from dataclasses import dataclass

import numpy as np

from qdpy.containers import CVTGrid

from .modern import _positive_int
from .task_search import _measurement, _offer, _validate_grid

__all__ = ["SoftPromptMAPElites", "SoftPromptStats"]


## @brief Count generations sent to the decoder and scores produced by the evaluator.
[docs] @dataclass(frozen=True) class SoftPromptStats: """Probe calls are a subset of generations and share the generation budget.""" generations: int = 0 measurements: int = 0 probes: int = 0 admissions: int = 0
## @brief Evolve soft prompts using Gaussian, crossover, and descriptor-guided mutations.
[docs] class SoftPromptMAPElites: """Run the fixed-archive, callback-based variant of QD-LLM. :param archive: Empty parentless best-only Grid or CVTGrid. :param initial_embedding: Finite 2D array with one vector per soft token. :param sigma: Gaussian exploration scale per embedding coordinate. :param probe_step: Length of updates along random unit probe directions. :param probe_directions: Maximum number of paired probes per targeted update. :param targeted_probability: Probability of selecting targeted variation. :param crossover_probability: Probability of interpolating two prompts. :param seed: Private seed for embedding search and decoder calls. """ def __init__(self, archive, initial_embedding, *, sigma=.1, probe_step=.1, probe_directions=4, targeted_probability=.35, crossover_probability=.3, seed=0): _validate_grid(archive) initial = np.array(initial_embedding, dtype=np.float64, order="C", copy=True) if initial.ndim != 2 or not initial.size or not np.isfinite(initial).all(): raise ValueError("Supply a finite nonempty token-by-embedding array.") if (not np.isfinite(sigma) or sigma <= 0. or not np.isfinite(probe_step) or probe_step <= 0. or min(targeted_probability, crossover_probability) < 0. or not 0. <= targeted_probability + crossover_probability <= 1.): raise ValueError("Use positive finite steps and variation probabilities totalling at most one.") lower, upper = np.asarray(archive.features_domain, dtype=float).T spans = upper - lower if not np.all(np.isfinite(spans) & (spans > 0.)): raise ValueError("Soft-prompt search needs finite increasing descriptor domains.") self._directions = _positive_int(probe_directions, "probe_directions") if archive.fitness_weights is None: archive._set_fitness_weights((1.,)) self.archive = archive self._initial = initial self._sigma, self._probe_step = sigma, probe_step self._targeted, self._crossover = targeted_probability, crossover_probability self._span, self._lower = spans, lower search_seed, decode_seed = np.random.SeedSequence(seed).spawn(2) self._rng, self._decode = np.random.default_rng(search_seed), np.random.default_rng(decode_seed) self._generations = self._measurements = self._probes = self._admissions = 0 @property def stats(self): """Return cumulative decoding and archive work.""" return SoftPromptStats(self._generations, self._measurements, self._probes, self._admissions) ## @brief Recover the numeric prompt saved with an elite.
[docs] def embedding(self, elite): """Return a fresh array for an elite from this search. Its text is elite[0].""" return np.frombuffer(elite[1], dtype=np.float64).reshape(self._initial.shape).copy()
def _seed(self): return int(self._decode.integers(2**63, dtype=np.uint64)) def _evaluate(self, prompt, generate, evaluate, *, seed, probe=False): prompt = np.ascontiguousarray(prompt, dtype=np.float64) if not np.isfinite(prompt).all(): raise ValueError("Variation produced a nonfinite prompt. Reduce the step sizes.") self._generations += 1 self._probes += probe text = generate(prompt.copy(), seed) if text is None: return None if not isinstance(text, str): raise TypeError("The generator must return text or None.") self._measurements += 1 result = evaluate(text) if result is None: return None fitness, descriptor = result genome = (text, prompt.tobytes()) measurement = _measurement(self.archive, ((fitness,), descriptor), genome) previous = self.archive.nb_added _offer(self.archive, measurement) self._admissions += self.archive.nb_added - previous candidate, cell = measurement return np.asarray(candidate.features.values) if cell is not None else None def _target(self): choices = tuple(cell for cell, occupants in self.archive.solutions.items() if not occupants) if not choices: choices = tuple(self.archive.solutions) cell = choices[int(self._rng.integers(len(choices)))] if isinstance(self.archive, CVTGrid): return self.archive.cluster_centers[cell[0]] return self._lower + (np.asarray(cell) + .5) / self.archive.shape * self._span def _guided(self, parent, directions, generate, evaluate): target = self._target() gradient = np.zeros_like(parent) for _ in range(directions): direction = self._rng.normal(size=parent.shape) direction /= np.linalg.norm(direction) seed = self._seed() plus = self._evaluate(parent + self._probe_step * direction, generate, evaluate, seed=seed, probe=True) minus = self._evaluate(parent - self._probe_step * direction, generate, evaluate, seed=seed, probe=True) if plus is not None and minus is not None: toward = (target - minus) / self._span away = (target - plus) / self._span gradient += (np.dot(toward, toward) - np.dot(away, away)) * direction length = np.linalg.norm(gradient) if length > 0.: return parent + self._sigma * np.sqrt(parent.size) * gradient / length return self._gaussian(parent) def _gaussian(self, parent): return parent + self._rng.normal(scale=self._sigma, size=parent.shape) def _offspring(self, mode, remaining, generate, evaluate): if mode == "fixed" or not self._generations: return self._initial if not self.archive: return self._gaussian(self._initial) slot = int(self._rng.integers(len(self.archive))) parent = self.embedding(self.archive[slot]) if mode == "targeted": choice = self._rng.random() if choice < self._crossover and len(self.archive) >= 2: other_slot = int(self._rng.integers(len(self.archive) - 1)) other = self.embedding(self.archive[other_slot + (other_slot >= slot)]) weight = self._rng.uniform(.3, .7) return weight * parent + (1 - weight) * other directions = min(self._directions, (remaining - 1) // 2) if self._crossover <= choice < self._crossover + self._targeted and directions: return self._guided(parent, directions, generate, evaluate) return self._gaussian(parent) ## @brief Spend an additional total generation budget including every probe.
[docs] def run(self, generate, evaluate, *, budget, mode="targeted"): """Fill the archive using frozen decoding and independent output assessment. generate(embedding, seed) returns text or None. evaluate(text) returns (scalar fitness, descriptor vector) or None. Paired probes receive the same seed and can enter the archive. Choose "gaussian" for a mutation control or "fixed" to decode repeatedly from the initial embedding. """ if not callable(generate) or not callable(evaluate): raise TypeError("Supply generation and evaluation callbacks.") if mode not in ("targeted", "gaussian", "fixed"): raise ValueError("mode must be targeted, gaussian or fixed.") stop = self._generations + _positive_int(budget, "budget") while self._generations < stop: prompt = self._offspring(mode, stop - self._generations, generate, evaluate) self._evaluate(prompt, generate, evaluate, seed=self._seed()) return self.archive