# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Enhanced POET with performance-ranked task novelty and gated transfers.
"""Co-evolve caller-defined tasks and policies under an explicit evaluation budget."""
from collections import Counter, deque
from collections.abc import Hashable
from dataclasses import dataclass
from math import isfinite
import numpy as np
from scipy.spatial.distance import cdist
from scipy.stats import rankdata
from .modern import _positive_int
__all__ = ["EnhancedPOET", "POETPair", "POETStats"]
## @brief One immutable task and its current measured policy.
[docs]
@dataclass(frozen=True)
class POETPair:
"""Track a task, the policy paired with it, and its source task."""
task: Hashable
policy: tuple[float, ...]
score: float
parent: Hashable | None
## @brief Report evaluator costs of training, task admission and transfer.
[docs]
@dataclass(frozen=True)
class POETStats:
rounds: int = 0
training_evaluations: int = 0
criterion_evaluations: int = 0
novelty_evaluations: int = 0
transfer_evaluations: int = 0
admitted_tasks: int = 0
transfers: int = 0
fine_tuning_attempts: int = 0
@property
def evaluations(self):
"""Return all score calls, including task and transfer screening."""
return self.training_evaluations + self.criterion_evaluations + self.novelty_evaluations + self.transfer_evaluations
def _pata_rank(scores, low, high):
"""Clip each score, then map its midrank to [-0.5, 0.5]."""
if len(scores) == 1:
return np.zeros(1)
return (rankdata(np.clip(scores, low, high), method="average") - 1) / (len(scores) - 1) - .5
class _BudgetFinished(Exception):
pass
## @brief Grow and train a population of tasks and their paired policies.
[docs]
class EnhancedPOET:
"""Run the generic Enhanced POET curriculum and transfer loop.
:param initial_task: Immutable hashable encoding of the starting task.
:param initial_policy: One finite real vector.
:param mutate_task: Callable (task, rng) returning a new task or None.
:param improve: Callable (task, policy, score, rng) returning a policy.
Its score callback takes one policy and charges the current budget.
:param minimal_criterion: Inclusive (too hard, too easy) raw score bounds.
:param reproduction_threshold: Minimum score at which a task can reproduce.
:param active_limit: Maximum simultaneously trained pairs.
:param proposals: Number of task mutations per reproduction round.
:param new_tasks: Maximum newly admitted tasks per reproduction round.
:param mutate_every: Interval between task reproduction rounds.
:param transfer_every: Interval between transfer checks. Use None to disable.
:param novelty_neighbors: Number of nearest task profiles used for novelty.
:param seed: Private seed for evaluation, mutation and optimization order.
"""
def __init__(self, initial_task, initial_policy, *, mutate_task, improve, minimal_criterion,
reproduction_threshold, active_limit=8, proposals=8, new_tasks=2, mutate_every=4,
transfer_every=4, novelty_neighbors=5, seed=0):
if initial_task is None or not isinstance(initial_task, Hashable):
raise TypeError("Supply an immutable hashable initial task.")
hash(initial_task)
if not callable(mutate_task) or not callable(improve):
raise TypeError("mutate_task and improve must be callable.")
low, high = minimal_criterion
if not (isfinite(low) and isfinite(high) and low < high and isfinite(reproduction_threshold)):
raise ValueError("Use finite increasing criterion bounds and a finite reproduction threshold.")
self._initial = initial_task, self._policy(initial_policy)
self._mutate, self._improve = mutate_task, improve
self._low, self._high, self._reproduction = low, high, reproduction_threshold
self._active_limit = _positive_int(active_limit, "active_limit")
self._proposals, self._new_tasks = _positive_int(proposals, "proposals"), _positive_int(new_tasks, "new_tasks")
self._mutate_every = _positive_int(mutate_every, "mutate_every")
self._transfer_every = None if transfer_every is None else _positive_int(transfer_every, "transfer_every")
self._neighbors = _positive_int(novelty_neighbors, "novelty_neighbors")
self._rng = np.random.default_rng(seed)
self._active, self._archived, self._recent = {}, {}, {}
self._counts = Counter()
@property
def active(self):
"""Return currently trained pairs in their admission order."""
return tuple(self._active.values())
@property
def archived(self):
"""Return retired pairs still used as references in PATA-EC."""
return tuple(self._archived.values())
@property
def stats(self):
"""Return cumulative evaluation and event counts."""
return POETStats(**self._counts)
def _policy(self, policy):
result = tuple(map(float, policy))
if (not result or not all(map(isfinite, result))
or (hasattr(self, "_initial") and len(result) != len(self._initial[1]))):
raise ValueError("Policies must be finite vectors of a fixed positive length.")
return result
def _score(self, task, policy, stage):
if self._remaining == 0:
raise _BudgetFinished
policy = self._policy(policy)
self._remaining -= 1
self._counts[stage] += 1
value = float(self._evaluate(task, policy, int(self._rng.integers(2**32))))
if not isfinite(value):
raise ValueError("POET evaluation must return finite scalar fitness.")
return value
def _train(self, task, policy, stage):
updated = self._policy(self._improve(task, policy, lambda trial: self._score(task, trial, stage), self._rng))
return updated, self._score(task, updated, stage)
def _replace(self, pair, *, reset):
self._active[pair.task] = pair
if reset:
self._recent[pair.task] = deque(maxlen=5)
self._recent[pair.task].append(pair.score)
def _reproduce(self):
parents = [pair for pair in self._active.values() if pair.score >= self._reproduction]
if not parents:
return
candidates = {}
for _ in range(self._proposals):
parent = parents[self._rng.integers(len(parents))]
child = self._mutate(parent.task, self._rng)
if child is None or child in self._active or child in self._archived or child in candidates:
continue
score = self._score(child, parent.policy, "criterion_evaluations")
if self._low <= score <= self._high:
candidates[child] = POETPair(child, parent.policy, score, parent.task)
if not candidates:
return
panel = (*self.active, *self.archived)
def profile(task):
scores = [self._score(task, pair.policy, "novelty_evaluations") for pair in panel]
return _pata_rank(scores, self._low, self._high)
existing = [profile(pair.task) for pair in panel]
distances = cdist([profile(task) for task in candidates], existing)
k = min(self._neighbors, len(existing))
novelty = np.partition(distances, k - 1, axis=1)[:, :k].mean(axis=1)
order = self._rng.permutation(len(candidates))
pairs = tuple(candidates.values())
for slot in sorted(order, key=lambda i: -novelty[i])[:self._new_tasks]:
self._replace(pairs[slot], reset=True)
self._counts["admitted_tasks"] += 1
if len(self._active) > self._active_limit:
oldest = next(iter(self._active))
self._archived[oldest] = self._active.pop(oldest)
del self._recent[oldest]
def _transfer(self):
initial = self.active
for target in initial:
task = target.task
threshold = max(self._recent[task])
best = None
for source in initial:
if source.task == task:
continue
direct = self._score(task, source.policy, "transfer_evaluations")
if direct <= threshold:
continue
self._counts["fine_tuning_attempts"] += 1
policy, tuned = self._train(task, source.policy, "transfer_evaluations")
if tuned > threshold and (best is None or tuned > best.score):
best = POETPair(task, policy, tuned, target.parent)
if best is not None:
self._replace(best, reset=True)
self._counts["transfers"] += 1
## @brief Continue co-evolution at most the specified rounds and score calls.
[docs]
def run(self, evaluate, budget, *, rounds):
"""Return cumulative stats with a hard evaluator-call budget.
The evaluator accepts (task, policy, seed) and returns a scalar to
maximize. An interrupted round can leave completed pair updates in
place. Use the score callback for every evaluation in improve.
"""
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
self._remaining = _positive_int(budget, "budget")
rounds = _positive_int(rounds, "rounds")
self._evaluate = evaluate
try:
if not self._active:
task, policy = self._initial
self._replace(POETPair(task, policy, self._score(task, policy, "training_evaluations"), None), reset=True)
for _ in range(rounds):
number = self._counts["rounds"] + 1
for pair in self.active:
policy, score = self._train(pair.task, pair.policy, "training_evaluations")
self._replace(POETPair(pair.task, policy, score, pair.parent), reset=False)
if number % self._mutate_every == 0:
self._reproduce()
if self._transfer_every is not None and number % self._transfer_every == 0:
self._transfer()
self._counts["rounds"] += 1
except _BudgetFinished:
pass
finally:
del self._evaluate
return self.stats