QDpy
Loading...
Searching...
No Matches
poet.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Co-evolve caller-defined tasks and policies under an explicit evaluation budget."""
6
7from collections import Counter, deque
8from collections.abc import Hashable
9from dataclasses import dataclass
10from math import isfinite
11
12import numpy as np
13from scipy.spatial.distance import cdist
14from scipy.stats import rankdata
15
16from .modern import _positive_int
17
18__all__ = ["EnhancedPOET", "POETPair", "POETStats"]
19
20
21
22@dataclass(frozen=True)
24 """Track a task, the policy paired with it, and its source task."""
25
26 task: Hashable
27 policy: tuple[float, ...]
28 score: float
29 parent: Hashable | None
30
31
32
33@dataclass(frozen=True)
35 rounds: int = 0
36 training_evaluations: int = 0
37 criterion_evaluations: int = 0
38 novelty_evaluations: int = 0
39 transfer_evaluations: int = 0
40 admitted_tasks: int = 0
41 transfers: int = 0
42 fine_tuning_attempts: int = 0
43
44 @property
45 def evaluations(self):
46 """Return all score calls, including task and transfer screening."""
48
49
50def _pata_rank(scores, low, high):
51 """Clip each score, then map its midrank to [-0.5, 0.5]."""
52 if len(scores) == 1:
53 return np.zeros(1)
54 return (rankdata(np.clip(scores, low, high), method="average") - 1) / (len(scores) - 1) - .5
55
56
57class _BudgetFinished(Exception):
58 pass
59
60
61
62class EnhancedPOET:
63 """Run the generic Enhanced POET curriculum and transfer loop.
64
65 :param initial_task: Immutable hashable encoding of the starting task.
66 :param initial_policy: One finite real vector.
67 :param mutate_task: Callable (task, rng) returning a new task or None.
68 :param improve: Callable (task, policy, score, rng) returning a policy.
69 Its score callback takes one policy and charges the current budget.
70 :param minimal_criterion: Inclusive (too hard, too easy) raw score bounds.
71 :param reproduction_threshold: Minimum score at which a task can reproduce.
72 :param active_limit: Maximum simultaneously trained pairs.
73 :param proposals: Number of task mutations per reproduction round.
74 :param new_tasks: Maximum newly admitted tasks per reproduction round.
75 :param mutate_every: Interval between task reproduction rounds.
76 :param transfer_every: Interval between transfer checks. Use None to disable.
77 :param novelty_neighbors: Number of nearest task profiles used for novelty.
78 :param seed: Private seed for evaluation, mutation and optimization order.
79 """
80
81 def __init__(self, initial_task, initial_policy, *, mutate_task, improve, minimal_criterion,
82 reproduction_threshold, active_limit=8, proposals=8, new_tasks=2, mutate_every=4,
83 transfer_every=4, novelty_neighbors=5, seed=0):
84 if initial_task is None or not isinstance(initial_task, Hashable):
85 raise TypeError("Supply an immutable hashable initial task.")
86 hash(initial_task)
87 if not callable(mutate_task) or not callable(improve):
88 raise TypeError("mutate_task and improve must be callable.")
89 low, high = minimal_criterion
90 if not (isfinite(low) and isfinite(high) and low < high and isfinite(reproduction_threshold)):
91 raise ValueError("Use finite increasing criterion bounds and a finite reproduction threshold.")
92 self._initial = initial_task, self._policy(initial_policy)
93 self._mutate, self._improve = mutate_task, improve
94 self._low, self._high, self._reproduction = low, high, reproduction_threshold
95 self._active_limit = _positive_int(active_limit, "active_limit")
96 self._proposals, self._new_tasks = _positive_int(proposals, "proposals"), _positive_int(new_tasks, "new_tasks")
97 self._mutate_every = _positive_int(mutate_every, "mutate_every")
98 self._transfer_every = None if transfer_every is None else _positive_int(transfer_every, "transfer_every")
99 self._neighbors = _positive_int(novelty_neighbors, "novelty_neighbors")
100 self._rng = np.random.default_rng(seed)
101 self._active, self._archived, self._recent = {}, {}, {}
102 self._counts = Counter()
103
104 @property
105 def active(self):
106 """Return currently trained pairs in their admission order."""
107 return tuple(self._active.values())
108
109 @property
110 def archived(self):
111 """Return retired pairs still used as references in PATA-EC."""
112 return tuple(self._archived.values())
113
114 @property
115 def stats(self):
116 """Return cumulative evaluation and event counts."""
117 return POETStats(**self._counts)
118
119 def _policy(self, policy):
120 result = tuple(map(float, policy))
121 if (not result or not all(map(isfinite, result))
122 or (hasattr(self, "_initial") and len(result) != len(self._initial[1]))):
123 raise ValueError("Policies must be finite vectors of a fixed positive length.")
124 return result
125
126 def _score(self, task, policy, stage):
127 if self._remaining == 0:
128 raise _BudgetFinished
129 policy = self._policy(policy)
130 self._remaining -= 1
131 self._counts[stage] += 1
132 value = float(self._evaluate(task, policy, int(self._rng.integers(2**32))))
133 if not isfinite(value):
134 raise ValueError("POET evaluation must return finite scalar fitness.")
135 return value
136
137 def _train(self, task, policy, stage):
138 updated = self._policy(self._improve(task, policy, lambda trial: self._score(task, trial, stage), self._rng))
139 return updated, self._score(task, updated, stage)
140
141 def _replace(self, pair, *, reset):
142 self._active[pair.task] = pair
143 if reset:
144 self._recent[pair.task] = deque(maxlen=5)
145 self._recent[pair.task].append(pair.score)
146
147 def _reproduce(self):
148 parents = [pair for pair in self._active.values() if pair.score >= self._reproduction]
149 if not parents:
150 return
151 candidates = {}
152 for _ in range(self._proposals):
153 parent = parents[self._rng.integers(len(parents))]
154 child = self._mutate(parent.task, self._rng)
155 if child is None or child in self._active or child in self._archived or child in candidates:
156 continue
157 score = self._score(child, parent.policy, "criterion_evaluations")
158 if self._low <= score <= self._high:
159 candidates[child] = POETPair(child, parent.policy, score, parent.task)
160 if not candidates:
161 return
162
163 panel = (*self.active, *self.archived)
164
165 def profile(task):
166 scores = [self._score(task, pair.policy, "novelty_evaluations") for pair in panel]
167 return _pata_rank(scores, self._low, self._high)
168
169 existing = [profile(pair.task) for pair in panel]
170 distances = cdist([profile(task) for task in candidates], existing)
171 k = min(self._neighbors, len(existing))
172 novelty = np.partition(distances, k - 1, axis=1)[:, :k].mean(axis=1)
173 order = self._rng.permutation(len(candidates))
174 pairs = tuple(candidates.values())
175 for slot in sorted(order, key=lambda i: -novelty[i])[:self._new_tasks]:
176 self._replace(pairs[slot], reset=True)
177 self._counts["admitted_tasks"] += 1
178 if len(self._active) > self._active_limit:
179 oldest = next(iter(self._active))
180 self._archived[oldest] = self._active.pop(oldest)
181 del self._recent[oldest]
182
183 def _transfer(self):
184 initial = self.active
185 for target in initial:
186 task = target.task
187 threshold = max(self._recent[task])
188 best = None
189 for source in initial:
190 if source.task == task:
191 continue
192 direct = self._score(task, source.policy, "transfer_evaluations")
193 if direct <= threshold:
194 continue
195 self._counts["fine_tuning_attempts"] += 1
196 policy, tuned = self._train(task, source.policy, "transfer_evaluations")
197 if tuned > threshold and (best is None or tuned > best.score):
198 best = POETPair(task, policy, tuned, target.parent)
199 if best is not None:
200 self._replace(best, reset=True)
201 self._counts["transfers"] += 1
202
203
204 def run(self, evaluate, budget, *, rounds):
205 """Return cumulative stats with a hard evaluator-call budget.
206
207 The evaluator accepts (task, policy, seed) and returns a scalar to
208 maximize. An interrupted round can leave completed pair updates in
209 place. Use the score callback for every evaluation in improve.
210 """
211 if not callable(evaluate):
212 raise TypeError("evaluate must be callable.")
213 self._remaining = _positive_int(budget, "budget")
214 rounds = _positive_int(rounds, "rounds")
215 self._evaluate = evaluate
216 try:
217 if not self._active:
218 task, policy = self._initial
219 self._replace(POETPair(task, policy, self._score(task, policy, "training_evaluations"), None), reset=True)
220 for _ in range(rounds):
221 number = self._counts["rounds"] + 1
222 for pair in self.active:
223 policy, score = self._train(pair.task, pair.policy, "training_evaluations")
224 self._replace(POETPair(pair.task, policy, score, pair.parent), reset=False)
225 if number % self._mutate_every == 0:
226 self._reproduce()
227 if self._transfer_every is not None and number % self._transfer_every == 0:
228 self._transfer()
229 self._counts["rounds"] += 1
230 except _BudgetFinished:
231 pass
232 finally:
233 del self._evaluate
234 return self.stats
_score(self, task, policy, stage)
Definition poet.py:126
run(self, evaluate, budget, *, rounds)
Continue co-evolution at most the specified rounds and score calls.
Definition poet.py:204
_train(self, task, policy, stage)
Definition poet.py:137
_replace(self, pair, *, reset)
Definition poet.py:141
One immutable task and its current measured policy.
Definition poet.py:23
Report evaluator costs of training, task admission and transfer.
Definition poet.py:34