6"""Verified strategy search and balanced replay for external trainers."""
9from collections
import Counter
10from collections.abc
import Mapping
11from dataclasses
import asdict, dataclass
12from pathlib
import Path
18from .modern
import _positive_int
20__all__ = [
"EliteReplay",
"EliteReplayDataset",
"EliteReplayEntry",
"EliteReplayStats"]
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.")
31 if not isinstance(value, str)
or not value.strip():
32 raise ValueError(
"Problem IDs and solutions must be nonempty strings.")
37@dataclass(frozen=True)
39 """Store the raw text and its caller-defined positive length."""
42 descriptor: tuple[str, ...]
46 def __post_init__(self):
49 object.__setattr__(self,
"descriptor", _descriptor(self.
descriptor))
50 object.__setattr__(self,
"length", _positive_int(self.
length,
"length"))
55 """Replay verified solution text independently of the search or trainer.
57 :param entries: EliteReplayEntry records with unique problem/descriptor pairs.
60 def __init__(self, entries):
65 if not isinstance(entry, EliteReplayEntry):
66 raise TypeError(
"Supply EliteReplayEntry records.")
67 key = (entry.problem, entry.descriptor)
69 raise ValueError(
"Replay data must have only one entry per problem and descriptor.")
71 groups.setdefault(entry.problem, []).append(entry)
72 self.
_groups = tuple(tuple(group)
for group
in groups.values())
76 """Return the immutable replay records in archive order."""
84 """Return a tuple of entries sampled with replacement using a NumPy generator."""
86 raise ValueError(
"At least one problem must have a verified solution.")
88 for problem
in rng.integers(len(self.
_groups), size=_positive_int(size,
"size")):
90 samples.append(group[int(rng.integers(len(group)))])
95 """Export problem, descriptor, solution and length fields."""
96 with _atomic_output_path(path)
as temporary, temporary.open(
"w", encoding=
"utf-8")
as stream:
98 stream.write(json.dumps(asdict(entry), ensure_ascii=
False) +
"\n")
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())
109@dataclass(frozen=True)
111 """Cumulative counts for search and directly offered seed solutions."""
114 verifications: int = 0
121 """Build EliteReplay's pre-training solution data with generic callbacks.
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.
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.")
143 self.
_rng = np.random.default_rng(seed)
147 """Return cumulative proposal, verifier call, success, and admission counts."""
152 """Return an independent replay snapshot in declared problem order."""
156 def offer(self, problem, solution, verify):
157 """Return whether the verified solution filled a cell or shortened its elite.
159 verify(problem, solution) independently checks correctness and
160 returns a declared achieved descriptor or None on failure.
162 if problem
not in self.
_elites or not callable(verify):
163 raise ValueError(
"Use a declared problem ID and a callable verifier.")
165 self.
_counts[
"verifications"] += 1
166 achieved = verify(problem, solution)
169 descriptor = _descriptor(achieved)
171 raise ValueError(
"The verifier returned an undeclared strategy descriptor.")
174 incumbent = self.
_elites[problem].get(descriptor)
175 if incumbent
is not None and incumbent.length <= entry.length:
177 self.
_elites[problem][descriptor] = entry
178 self.
_counts[
"admissions"] += 1
182 def run(self, propose, verify, *, budget, guided=True):
183 """Return a replay snapshot after budget additional proposal attempts.
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.
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")):
195 target, parent =
None,
None
198 target = min(self.
_targets[problem],
200 parents = [entry
for cell, entry
in group.items()
if cell != target]
202 parent = parents[int(self.
_rng.integers(len(parents)))]
206 solution = propose(problem, target, parent, self.
_rng)
207 if solution
is not None:
208 self.
offer(problem, solution, verify)
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.