# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Build and export a verified solution repertoire for replay.
# @see https://doi.org/10.48550/arXiv.2610.22290
"""Verified strategy search and balanced replay for external trainers."""
import json
from collections import Counter
from collections.abc import Mapping
from dataclasses import asdict, dataclass
from pathlib import Path
import numpy as np
from qdpy.base import _atomic_output_path
from .modern import _positive_int
__all__ = ["EliteReplay", "EliteReplayDataset", "EliteReplayEntry", "EliteReplayStats"]
def _descriptor(labels):
labels = (labels,) if isinstance(labels, str) else tuple(labels)
if not labels or any(not isinstance(label, str) or not label for label in labels):
raise ValueError("A strategy descriptor needs one or more nonempty string labels.")
return labels
def _text(value):
if not isinstance(value, str) or not value.strip():
raise ValueError("Problem IDs and solutions must be nonempty strings.")
return value
## @brief A verified solution retained at its achieved strategy descriptor.
[docs]
@dataclass(frozen=True)
class EliteReplayEntry:
"""Store the raw text and its caller-defined positive length."""
problem: str
descriptor: tuple[str, ...]
solution: str
length: int
def __post_init__(self):
_text(self.problem)
_text(self.solution)
object.__setattr__(self, "descriptor", _descriptor(self.descriptor))
object.__setattr__(self, "length", _positive_int(self.length, "length"))
## @brief A frozen snapshot for problem-then-cell sampling and JSONL export.
[docs]
class EliteReplayDataset:
"""Replay verified solution text independently of the search or trainer.
:param entries: EliteReplayEntry records with unique problem/descriptor pairs.
"""
def __init__(self, entries):
self._entries = tuple(entries)
groups = {}
seen = set()
for entry in self._entries:
if not isinstance(entry, EliteReplayEntry):
raise TypeError("Supply EliteReplayEntry records.")
key = (entry.problem, entry.descriptor)
if key in seen:
raise ValueError("Replay data must have only one entry per problem and descriptor.")
seen.add(key)
groups.setdefault(entry.problem, []).append(entry)
self._groups = tuple(tuple(group) for group in groups.values())
@property
def entries(self):
"""Return the immutable replay records in archive order."""
return self._entries
def __len__(self):
return len(self._entries)
## @brief Draw uniform problems followed by uniform occupied cells.
[docs]
def sample(self, size, *, rng):
"""Return a tuple of entries sampled with replacement using a NumPy generator."""
if not self._groups:
raise ValueError("At least one problem must have a verified solution.")
samples = []
for problem in rng.integers(len(self._groups), size=_positive_int(size, "size")):
group = self._groups[problem]
samples.append(group[int(rng.integers(len(group)))])
return tuple(samples)
## @brief Write one verified solution per UTF-8 JSONL record.
[docs]
def save(self, path):
"""Export problem, descriptor, solution and length fields."""
with _atomic_output_path(path) as temporary, temporary.open("w", encoding="utf-8") as stream:
for entry in self._entries:
stream.write(json.dumps(asdict(entry), ensure_ascii=False) + "\n")
## @brief Load and validate a previously exported replay dataset.
[docs]
@classmethod
def load(cls, path):
"""Read UTF-8 JSONL and validate entries and cell uniqueness."""
with Path(path).open(encoding="utf-8") as stream:
return cls(EliteReplayEntry(**json.loads(line)) for line in stream if line.strip())
## @brief Count generations, verification work, and archive updates.
[docs]
@dataclass(frozen=True)
class EliteReplayStats:
"""Cumulative counts for search and directly offered seed solutions."""
proposals: int = 0
verifications: int = 0
verified: int = 0
admissions: int = 0
## @brief Illuminate a fixed set of verified strategies for each problem.
[docs]
class EliteReplay:
"""Build EliteReplay's pre-training solution data with generic callbacks.
:param targets: Mapping from problem IDs to ordered distinct strategy
descriptors. Each descriptor is a string or tuple of string labels.
:param length: Callback (solution) returning its positive token count
or another integer cost. The default counts characters.
:param seed: Seed for proposal randomness and cross-cell parent selection.
"""
def __init__(self, targets, *, length=len, seed=0):
if not isinstance(targets, Mapping) or not targets or not callable(length):
raise ValueError("Supply a nonempty problem mapping and a callable length function.")
self._targets = {_text(problem): tuple(map(_descriptor, cells))
for problem, cells in targets.items()}
if any(not cells or len(cells) != len(set(cells)) for cells in self._targets.values()):
raise ValueError("Each problem needs at least one target and distinct descriptors.")
self._target_set = {problem: frozenset(cells) for problem, cells in self._targets.items()}
self._elites = {problem: {} for problem in self._targets}
self._problem_attempts = Counter()
self._target_attempts = Counter()
self._counts = Counter()
self._length = length
self._rng = np.random.default_rng(seed)
@property
def stats(self):
"""Return cumulative proposal, verifier call, success, and admission counts."""
return EliteReplayStats(**self._counts)
## @brief Freeze the current elites for use during post-training.
[docs]
def dataset(self):
"""Return an independent replay snapshot in declared problem order."""
return EliteReplayDataset(entry for group in self._elites.values() for entry in group.values())
## @brief Verify and place a candidate at its achieved descriptor.
[docs]
def offer(self, problem, solution, verify):
"""Return whether the verified solution filled a cell or shortened its elite.
verify(problem, solution) independently checks correctness and
returns a declared achieved descriptor or None on failure.
"""
if problem not in self._elites or not callable(verify):
raise ValueError("Use a declared problem ID and a callable verifier.")
_text(solution)
self._counts["verifications"] += 1
achieved = verify(problem, solution)
if achieved is None:
return False
descriptor = _descriptor(achieved)
if descriptor not in self._target_set[problem]:
raise ValueError("The verifier returned an undeclared strategy descriptor.")
entry = EliteReplayEntry(problem, descriptor, solution, self._length(solution))
self._counts["verified"] += 1
incumbent = self._elites[problem].get(descriptor)
if incumbent is not None and incumbent.length <= entry.length:
return False
self._elites[problem][descriptor] = entry
self._counts["admissions"] += 1
return True
## @brief Allocate proposals to problems and sparsely explored targets.
[docs]
def run(self, propose, verify, *, budget, guided=True):
"""Return a replay snapshot after budget additional proposal attempts.
propose(problem, target, parent, rng) returns solution text or
None. When guided, request an uncovered target first, with ties
favoring the least attempted target, and pass a verified parent
from another cell if available. In the independent control both
target and parent are None. Each attempt counts against budget.
"""
if not callable(propose) or not callable(verify):
raise TypeError("Supply callable propose and verify callbacks.")
for _ in range(_positive_int(budget, "budget")):
problem = min(self._targets, key=lambda item: self._problem_attempts[item])
target, parent = None, None
if guided:
group = self._elites[problem]
target = min(self._targets[problem],
key=lambda cell: (cell in group, self._target_attempts[problem, cell]))
parents = [entry for cell, entry in group.items() if cell != target]
if parents:
parent = parents[int(self._rng.integers(len(parents)))]
self._target_attempts[problem, target] += 1
self._problem_attempts[problem] += 1
self._counts["proposals"] += 1
solution = propose(problem, target, parent, self._rng)
if solution is not None:
self.offer(problem, solution, verify)
return self.dataset()