QDpy
Loading...
Searching...
No Matches
neighborhood_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Targeted MAP-Elites for answer-preserving rewrites of one context."""
7
8from collections import Counter
9from dataclasses import dataclass
10from itertools import product
11from math import isfinite, log
12from operator import index
13
14import numpy as np
15
16from .modern import _positive_int
17
18__all__ = ["NeighborhoodElites", "NeighborhoodEntry", "NeighborhoodStats", "NeighborhoodProbe",
19 "answer_entropy"]
20
21
22
23@dataclass(frozen=True)
25 """Store a context rewrite, its categorical cell and its quality."""
26
27 text: str
28 cell: tuple[str, str]
29 quality: float
30
31
32
33@dataclass(frozen=True)
35 """Count attempted callbacks, rejected proposals and archive updates."""
36
37 edits: int = 0
38 assessments: int = 0
39 rejections: int = 0
40 admissions: int = 0
41 answer_calls: int = 0
42
43
44
45@dataclass(frozen=True)
47 """Return raw answers and empirical semantic entropy in nats."""
48
49 answers: tuple[str, ...]
50 entropy: float | None
51
52
53
54def answer_entropy(answers, *, group=None):
55 """Return entropy in nats, or None for an empty collection.
56
57 Pass a grouping callback that maps equivalent answers to the same
58 hashable key. Without it, compare exact answers.
59 """
60 counts = Counter(map(group, answers) if group is not None else answers)
61 total = sum(counts.values())
62 if total == 0:
63 return None
64 return -sum((count / total) * log(count / total) for count in counts.values())
65
66
67
69 """Use a staged targeted scheduler with caller-defined rewrite strategies and checks.
70
71 :param context: Original context. Bind the question and answer specification
72 to the editor and validator callbacks.
73 :param edits: Ordered nonempty labels for the edit axis.
74 :param support: Ordered nonempty labels for the support axis. The first
75 label is the default bootstrap target.
76 :param inherit_support: Edit labels that require a parent in the target
77 support level. The default uses insertion and reordering labels.
78 :param bootstrap: Ordered cells to attempt from the original context.
79 :param target_attempts: Maximum attempts to fill each cell during coverage.
80 :param coverage_patience: End coverage after this many attempts with no new cell.
81 :param seed: Seed for ties in target selection.
82 """
83
84 def __init__(self, context, *, edits=("distractor", "reorder", "style"),
85 support=("direct", "paraphrastic", "discourse", "multi-sentence"),
86 inherit_support=None, bootstrap=None, target_attempts=2, coverage_patience=5, seed=0):
87 if not isinstance(context, str) or not context.strip():
88 raise ValueError("Supply a nonempty original context.")
89 edits, support = tuple(edits), tuple(support)
90 for axis in (edits, support):
91 if not axis or any(not isinstance(label, str) or not label for label in axis) or len(set(axis)) != len(axis):
92 raise ValueError("Each axis needs distinct, nonempty labels.")
93 self.context = context.strip()
94 self.cells = tuple(product(edits, support))
95 self._bootstrap = (tuple((edit, support[0]) for edit in edits) if bootstrap is None
96 else tuple(map(tuple, bootstrap)))
97 self._inherit = (set(edits) & {"distractor", "reorder"} if inherit_support is None
98 else set(inherit_support))
99 if any(cell not in self.cells for cell in self._bootstrap) or not self._inherit <= set(edits):
100 raise ValueError("Bootstrap and inherited labels must belong to the configured axes.")
101 self._attempt_limit = _positive_int(target_attempts, "target_attempts")
102 self._patience = _positive_int(coverage_patience, "coverage_patience")
103 self._rng = np.random.default_rng(seed)
104 self._entries = {}
105 self._counts, self._targeted, self._refined = Counter(), Counter(), Counter()
106 self._next_seed = 0
107
108 @property
109 def entries(self):
110 """Return one immutable elite per occupied cell in axis order."""
111 return tuple(self._entries[cell] for cell in self.cells if cell in self._entries)
112
113 @property
114 def stats(self):
115 """Return cumulative construction and answer call counts."""
116 return NeighborhoodStats(**self._counts)
117
118 def _attempt(self, source, target, edit, assess):
119 self._counts["edits"] += 1
120 text = edit(source, target, self._rng)
121 if (not isinstance(text, str) or not text.strip()
122 or text.strip() in {self.context, source, *(entry.text for entry in self.entries)}):
123 self._counts["rejections"] += 1
124 return
125 text = text.strip()
126 self._counts["assessments"] += 1
127 measured = assess(source, text, target)
128 if measured is None:
129 self._counts["rejections"] += 1
130 return
131 cell, quality = measured
132 cell, quality = tuple(cell), float(quality)
133 if cell not in self.cells or cell[0] != target[0] or not isfinite(quality):
134 raise ValueError("Return a realized cell of the requested edit type and a finite quality.")
135 old = self._entries.get(cell)
136 if old is None or quality > old.quality:
137 self._entries[cell] = NeighborhoodEntry(text, cell, quality)
138 self._counts["admissions"] += 1
139
140
141 def run(self, edit, assess, *, budget, refinement_reserve=0):
142 """Spend up to budget editor calls. Leave unused work if no action is possible.
143
144 :param edit: Callback (parent_context, target_cell, rng) returning text or None.
145 :param assess: Callback (parent_context, rewrite, target_cell) returning
146 (realized_cell, quality), or None when answer preservation or edit
147 verification fails. Use the same original answer specification throughout.
148 :param budget: Maximum additional editor calls, including rejected edits.
149 :param refinement_reserve: Portion of budget reserved for occupied cells.
150 """
151 budget = _positive_int(budget, "budget")
152 reserve = index(refinement_reserve)
153 if not (0 <= reserve <= budget and callable(edit) and callable(assess)):
154 raise ValueError("Supply callable operators and a refinement reserve within the budget.")
155 stop = self.stats.edits + budget
156 while self.stats.edits < stop - reserve and self._next_seed < len(self._bootstrap):
157 target = self._bootstrap[self._next_seed]
158 self._next_seed += 1
159 self._attempt(self.context, target, edit, assess)
160 stalled = 0
161 while self.stats.edits < stop - reserve and stalled < self._patience:
162 parents = sorted(self.entries, key=lambda entry: -entry.quality)
163 options = {
164 cell: parent for cell in self.cells
165 if cell not in self._entries and self._targeted[cell] < self._attempt_limit
166 and (parent := next((row for row in parents if cell[0] not in self._inherit
167 or row.cell[1] == cell[1]), None)) is not None
168 }
169 if not options:
170 break
171 fewest = min(self._targeted[cell] for cell in options)
172 tied = [cell for cell in options if self._targeted[cell] == fewest]
173 target = tied[int(self._rng.integers(len(tied)))]
174 self._targeted[target] += 1
175 before = len(self._entries)
176 self._attempt(options[target].text, target, edit, assess)
177 stalled = 0 if len(self._entries) > before else stalled + 1
178 while self.stats.edits < stop and self._entries:
179 parent = min(self.entries, key=lambda row: (self._refined[row.cell], row.quality))
180 self._refined[parent.cell] += 1
181 self._attempt(parent.text, parent.cell, edit, assess)
182 return self.stats
183
184
185 def probe(self, predict, *, group=None, limit=None):
186 """Call predict once per selected text and group answers by a hashable key.
187
188 The default groups exact answer strings. Pass a normalizer or a semantic
189 class callback for equivalent answers. When limited, query the
190 highest-quality elites first. Empty neighborhoods have undefined entropy.
191 """
192 if not callable(predict) or group is not None and not callable(group):
193 raise ValueError("Supply prediction and optional grouping callbacks.")
194 rows = sorted(self.entries, key=lambda row: -row.quality)
195 if limit is not None:
196 rows = rows[:_positive_int(limit, "limit")]
197 answers = []
198 for row in rows:
199 self._counts["answer_calls"] += 1
200 answer = predict(row.text)
201 if not isinstance(answer, str):
202 raise ValueError("The predictor must return an answer string.")
203 answers.append(answer)
204 return NeighborhoodProbe(tuple(answers), answer_entropy(answers, group=group))
Grow and refine a categorical archive for one fixed question and context.
run(self, edit, assess, *, budget, refinement_reserve=0)
Bootstrap from the source, fill empty cells, then improve occupied cells.
probe(self, predict, *, group=None, limit=None)
Measure disagreement on retained rewrites without consulting the gold answer.
One assessed rewrite and its realized location.
Summary of a downstream disagreement measurement.
Count construction and downstream answer requests separately.