QDpy
Loading...
Searching...
No Matches
elite_replay.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Verified strategy search and balanced replay for external trainers."""
7
8import json
9from collections import Counter
10from collections.abc import Mapping
11from dataclasses import asdict, dataclass
12from pathlib import Path
13
14import numpy as np
15
16from qdpy.base import _atomic_output_path
17
18from .modern import _positive_int
19
20__all__ = ["EliteReplay", "EliteReplayDataset", "EliteReplayEntry", "EliteReplayStats"]
21
22
23def _descriptor(labels):
24 labels = (labels,) if isinstance(labels, str) else tuple(labels)
25 if not labels or any(not isinstance(label, str) or not label for label in labels):
26 raise ValueError("A strategy descriptor needs one or more nonempty string labels.")
27 return labels
28
29
30def _text(value):
31 if not isinstance(value, str) or not value.strip():
32 raise ValueError("Problem IDs and solutions must be nonempty strings.")
33 return value
34
35
36
37@dataclass(frozen=True)
39 """Store the raw text and its caller-defined positive length."""
40
41 problem: str
42 descriptor: tuple[str, ...]
43 solution: str
44 length: int
45
46 def __post_init__(self):
47 _text(self.problem)
48 _text(self.solution)
49 object.__setattr__(self, "descriptor", _descriptor(self.descriptor))
50 object.__setattr__(self, "length", _positive_int(self.length, "length"))
51
52
53
55 """Replay verified solution text independently of the search or trainer.
56
57 :param entries: EliteReplayEntry records with unique problem/descriptor pairs.
58 """
59
60 def __init__(self, entries):
61 self._entries = tuple(entries)
62 groups = {}
63 seen = set()
64 for entry in self._entries:
65 if not isinstance(entry, EliteReplayEntry):
66 raise TypeError("Supply EliteReplayEntry records.")
67 key = (entry.problem, entry.descriptor)
68 if key in seen:
69 raise ValueError("Replay data must have only one entry per problem and descriptor.")
70 seen.add(key)
71 groups.setdefault(entry.problem, []).append(entry)
72 self._groups = tuple(tuple(group) for group in groups.values())
73
74 @property
75 def entries(self):
76 """Return the immutable replay records in archive order."""
77 return self._entries
78
79 def __len__(self):
80 return len(self._entries)
81
82
83 def sample(self, size, *, rng):
84 """Return a tuple of entries sampled with replacement using a NumPy generator."""
85 if not self._groups:
86 raise ValueError("At least one problem must have a verified solution.")
87 samples = []
88 for problem in rng.integers(len(self._groups), size=_positive_int(size, "size")):
89 group = self._groups[problem]
90 samples.append(group[int(rng.integers(len(group)))])
91 return tuple(samples)
92
93
94 def save(self, path):
95 """Export problem, descriptor, solution and length fields."""
96 with _atomic_output_path(path) as temporary, temporary.open("w", encoding="utf-8") as stream:
97 for entry in self._entries:
98 stream.write(json.dumps(asdict(entry), ensure_ascii=False) + "\n")
99
100
101 @classmethod
102 def load(cls, path):
103 """Read UTF-8 JSONL and validate entries and cell uniqueness."""
104 with Path(path).open(encoding="utf-8") as stream:
105 return cls(EliteReplayEntry(**json.loads(line)) for line in stream if line.strip())
106
107
108
109@dataclass(frozen=True)
111 """Cumulative counts for search and directly offered seed solutions."""
112
113 proposals: int = 0
114 verifications: int = 0
115 verified: int = 0
116 admissions: int = 0
117
118
119
121 """Build EliteReplay's pre-training solution data with generic callbacks.
122
123 :param targets: Mapping from problem IDs to ordered distinct strategy
124 descriptors. Each descriptor is a string or tuple of string labels.
125 :param length: Callback (solution) returning its positive token count
126 or another integer cost. The default counts characters.
127 :param seed: Seed for proposal randomness and cross-cell parent selection.
128 """
129
130 def __init__(self, targets, *, length=len, seed=0):
131 if not isinstance(targets, Mapping) or not targets or not callable(length):
132 raise ValueError("Supply a nonempty problem mapping and a callable length function.")
133 self._targets = {_text(problem): tuple(map(_descriptor, cells))
134 for problem, cells in targets.items()}
135 if any(not cells or len(cells) != len(set(cells)) for cells in self._targets.values()):
136 raise ValueError("Each problem needs at least one target and distinct descriptors.")
137 self._target_set = {problem: frozenset(cells) for problem, cells in self._targets.items()}
138 self._elites = {problem: {} for problem in self._targets}
139 self._problem_attempts = Counter()
140 self._target_attempts = Counter()
141 self._counts = Counter()
142 self._length = length
143 self._rng = np.random.default_rng(seed)
144
145 @property
146 def stats(self):
147 """Return cumulative proposal, verifier call, success, and admission counts."""
148 return EliteReplayStats(**self._counts)
149
150
151 def dataset(self):
152 """Return an independent replay snapshot in declared problem order."""
153 return EliteReplayDataset(entry for group in self._elites.values() for entry in group.values())
154
155
156 def offer(self, problem, solution, verify):
157 """Return whether the verified solution filled a cell or shortened its elite.
158
159 verify(problem, solution) independently checks correctness and
160 returns a declared achieved descriptor or None on failure.
161 """
162 if problem not in self._elites or not callable(verify):
163 raise ValueError("Use a declared problem ID and a callable verifier.")
164 _text(solution)
165 self._counts["verifications"] += 1
166 achieved = verify(problem, solution)
167 if achieved is None:
168 return False
169 descriptor = _descriptor(achieved)
170 if descriptor not in self._target_set[problem]:
171 raise ValueError("The verifier returned an undeclared strategy descriptor.")
172 entry = EliteReplayEntry(problem, descriptor, solution, self._length(solution))
173 self._counts["verified"] += 1
174 incumbent = self._elites[problem].get(descriptor)
175 if incumbent is not None and incumbent.length <= entry.length:
176 return False
177 self._elites[problem][descriptor] = entry
178 self._counts["admissions"] += 1
179 return True
180
181
182 def run(self, propose, verify, *, budget, guided=True):
183 """Return a replay snapshot after budget additional proposal attempts.
184
185 propose(problem, target, parent, rng) returns solution text or
186 None. When guided, request an uncovered target first, with ties
187 favoring the least attempted target, and pass a verified parent
188 from another cell if available. In the independent control both
189 target and parent are None. Each attempt counts against budget.
190 """
191 if not callable(propose) or not callable(verify):
192 raise TypeError("Supply callable propose and verify callbacks.")
193 for _ in range(_positive_int(budget, "budget")):
194 problem = min(self._targets, key=lambda item: self._problem_attempts[item])
195 target, parent = None, None
196 if guided:
197 group = self._elites[problem]
198 target = min(self._targets[problem],
199 key=lambda cell: (cell in group, self._target_attempts[problem, cell]))
200 parents = [entry for cell, entry in group.items() if cell != target]
201 if parents:
202 parent = parents[int(self._rng.integers(len(parents)))]
203 self._target_attempts[problem, target] += 1
204 self._problem_attempts[problem] += 1
205 self._counts["proposals"] += 1
206 solution = propose(problem, target, parent, self._rng)
207 if solution is not None:
208 self.offer(problem, solution, verify)
209 return self.dataset()
A frozen snapshot for problem-then-cell sampling and JSONL export.
save(self, path)
Write one verified solution per UTF-8 JSONL record.
load(cls, path)
Load and validate a previously exported replay dataset.
sample(self, size, *, rng)
Draw uniform problems followed by uniform occupied cells.
A verified solution retained at its achieved strategy descriptor.
Count generations, verification work, and archive updates.
Illuminate a fixed set of verified strategies for each problem.
dataset(self)
Freeze the current elites for use during post-training.
run(self, propose, verify, *, budget, guided=True)
Allocate proposals to problems and sparsely explored targets.
offer(self, problem, solution, verify)
Verify and place a candidate at its achieved descriptor.