# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Construct diverse, validated context rewrites and measure answer disagreement.
# @see https://arxiv.org/abs/2610.40278
"""Targeted MAP-Elites for answer-preserving rewrites of one context."""
from collections import Counter
from dataclasses import dataclass
from itertools import product
from math import isfinite, log
from operator import index
import numpy as np
from .modern import _positive_int
__all__ = ["NeighborhoodElites", "NeighborhoodEntry", "NeighborhoodStats", "NeighborhoodProbe",
"answer_entropy"]
## @brief One assessed rewrite and its realized location.
[docs]
@dataclass(frozen=True)
class NeighborhoodEntry:
"""Store a context rewrite, its categorical cell and its quality."""
text: str
cell: tuple[str, str]
quality: float
## @brief Count construction and downstream answer requests separately.
[docs]
@dataclass(frozen=True)
class NeighborhoodStats:
"""Count attempted callbacks, rejected proposals and archive updates."""
edits: int = 0
assessments: int = 0
rejections: int = 0
admissions: int = 0
answer_calls: int = 0
## @brief Summary of a downstream disagreement measurement.
[docs]
@dataclass(frozen=True)
class NeighborhoodProbe:
"""Return raw answers and empirical semantic entropy in nats."""
answers: tuple[str, ...]
entropy: float | None
## @brief Measure empirical entropy over answer classes.
[docs]
def answer_entropy(answers, *, group=None):
"""Return entropy in nats, or None for an empty collection.
Pass a grouping callback that maps equivalent answers to the same
hashable key. Without it, compare exact answers.
"""
counts = Counter(map(group, answers) if group is not None else answers)
total = sum(counts.values())
if total == 0:
return None
return -sum((count / total) * log(count / total) for count in counts.values())
## @brief Grow and refine a categorical archive for one fixed question and context.
[docs]
class NeighborhoodElites:
"""Use a staged targeted scheduler with caller-defined rewrite strategies and checks.
:param context: Original context. Bind the question and answer specification
to the editor and validator callbacks.
:param edits: Ordered nonempty labels for the edit axis.
:param support: Ordered nonempty labels for the support axis. The first
label is the default bootstrap target.
:param inherit_support: Edit labels that require a parent in the target
support level. The default uses insertion and reordering labels.
:param bootstrap: Ordered cells to attempt from the original context.
:param target_attempts: Maximum attempts to fill each cell during coverage.
:param coverage_patience: End coverage after this many attempts with no new cell.
:param seed: Seed for ties in target selection.
"""
def __init__(self, context, *, edits=("distractor", "reorder", "style"),
support=("direct", "paraphrastic", "discourse", "multi-sentence"),
inherit_support=None, bootstrap=None, target_attempts=2, coverage_patience=5, seed=0):
if not isinstance(context, str) or not context.strip():
raise ValueError("Supply a nonempty original context.")
edits, support = tuple(edits), tuple(support)
for axis in (edits, support):
if not axis or any(not isinstance(label, str) or not label for label in axis) or len(set(axis)) != len(axis):
raise ValueError("Each axis needs distinct, nonempty labels.")
self.context = context.strip()
self.cells = tuple(product(edits, support))
self._bootstrap = (tuple((edit, support[0]) for edit in edits) if bootstrap is None
else tuple(map(tuple, bootstrap)))
self._inherit = (set(edits) & {"distractor", "reorder"} if inherit_support is None
else set(inherit_support))
if any(cell not in self.cells for cell in self._bootstrap) or not self._inherit <= set(edits):
raise ValueError("Bootstrap and inherited labels must belong to the configured axes.")
self._attempt_limit = _positive_int(target_attempts, "target_attempts")
self._patience = _positive_int(coverage_patience, "coverage_patience")
self._rng = np.random.default_rng(seed)
self._entries = {}
self._counts, self._targeted, self._refined = Counter(), Counter(), Counter()
self._next_seed = 0
@property
def entries(self):
"""Return one immutable elite per occupied cell in axis order."""
return tuple(self._entries[cell] for cell in self.cells if cell in self._entries)
@property
def stats(self):
"""Return cumulative construction and answer call counts."""
return NeighborhoodStats(**self._counts)
def _attempt(self, source, target, edit, assess):
self._counts["edits"] += 1
text = edit(source, target, self._rng)
if (not isinstance(text, str) or not text.strip()
or text.strip() in {self.context, source, *(entry.text for entry in self.entries)}):
self._counts["rejections"] += 1
return
text = text.strip()
self._counts["assessments"] += 1
measured = assess(source, text, target)
if measured is None:
self._counts["rejections"] += 1
return
cell, quality = measured
cell, quality = tuple(cell), float(quality)
if cell not in self.cells or cell[0] != target[0] or not isfinite(quality):
raise ValueError("Return a realized cell of the requested edit type and a finite quality.")
old = self._entries.get(cell)
if old is None or quality > old.quality:
self._entries[cell] = NeighborhoodEntry(text, cell, quality)
self._counts["admissions"] += 1
## @brief Bootstrap from the source, fill empty cells, then improve occupied cells.
[docs]
def run(self, edit, assess, *, budget, refinement_reserve=0):
"""Spend up to budget editor calls. Leave unused work if no action is possible.
:param edit: Callback (parent_context, target_cell, rng) returning text or None.
:param assess: Callback (parent_context, rewrite, target_cell) returning
(realized_cell, quality), or None when answer preservation or edit
verification fails. Use the same original answer specification throughout.
:param budget: Maximum additional editor calls, including rejected edits.
:param refinement_reserve: Portion of budget reserved for occupied cells.
"""
budget = _positive_int(budget, "budget")
reserve = index(refinement_reserve)
if not (0 <= reserve <= budget and callable(edit) and callable(assess)):
raise ValueError("Supply callable operators and a refinement reserve within the budget.")
stop = self.stats.edits + budget
while self.stats.edits < stop - reserve and self._next_seed < len(self._bootstrap):
target = self._bootstrap[self._next_seed]
self._next_seed += 1
self._attempt(self.context, target, edit, assess)
stalled = 0
while self.stats.edits < stop - reserve and stalled < self._patience:
parents = sorted(self.entries, key=lambda entry: -entry.quality)
options = {
cell: parent for cell in self.cells
if cell not in self._entries and self._targeted[cell] < self._attempt_limit
and (parent := next((row for row in parents if cell[0] not in self._inherit
or row.cell[1] == cell[1]), None)) is not None
}
if not options:
break
fewest = min(self._targeted[cell] for cell in options)
tied = [cell for cell in options if self._targeted[cell] == fewest]
target = tied[int(self._rng.integers(len(tied)))]
self._targeted[target] += 1
before = len(self._entries)
self._attempt(options[target].text, target, edit, assess)
stalled = 0 if len(self._entries) > before else stalled + 1
while self.stats.edits < stop and self._entries:
parent = min(self.entries, key=lambda row: (self._refined[row.cell], row.quality))
self._refined[parent.cell] += 1
self._attempt(parent.text, parent.cell, edit, assess)
return self.stats
## @brief Measure disagreement on retained rewrites without consulting the gold answer.
[docs]
def probe(self, predict, *, group=None, limit=None):
"""Call predict once per selected text and group answers by a hashable key.
The default groups exact answer strings. Pass a normalizer or a semantic
class callback for equivalent answers. When limited, query the
highest-quality elites first. Empty neighborhoods have undefined entropy.
"""
if not callable(predict) or group is not None and not callable(group):
raise ValueError("Supply prediction and optional grouping callbacks.")
rows = sorted(self.entries, key=lambda row: -row.quality)
if limit is not None:
rows = rows[:_positive_int(limit, "limit")]
answers = []
for row in rows:
self._counts["answer_calls"] += 1
answer = predict(row.text)
if not isinstance(answer, str):
raise ValueError("The predictor must return an answer string.")
answers.append(answer)
return NeighborhoodProbe(tuple(answers), answer_entropy(answers, group=group))