63 """Run the generic Enhanced POET curriculum and transfer loop.
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.
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.")
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()
106 """Return currently trained pairs in their admission order."""
107 return tuple(self.
_active.values())
111 """Return retired pairs still used as references in PATA-EC."""
116 """Return cumulative evaluation and event counts."""
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.")
126 def _score(self, task, policy, stage):
128 raise _BudgetFinished
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.")
137 def _train(self, task, policy, stage):
139 return updated, self.
_score(task, updated, stage)
141 def _replace(self, pair, *, reset):
144 self.
_recent[pair.task] = deque(maxlen=5)
145 self.
_recent[pair.task].append(pair.score)
147 def _reproduce(self):
153 parent = parents[self.
_rng.integers(len(parents))]
155 if child
is None or child
in self.
_active or child
in self.
_archived or child
in candidates:
157 score = self.
_score(child, parent.policy,
"criterion_evaluations")
159 candidates[child] =
POETPair(child, parent.policy, score, parent.task)
166 scores = [self.
_score(task, pair.policy,
"novelty_evaluations")
for pair
in panel]
167 return _pata_rank(scores, self.
_low, self.
_high)
169 existing = [profile(pair.task)
for pair
in panel]
170 distances = cdist([profile(task)
for task
in candidates], 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
179 oldest = next(iter(self.
_active))
185 for target
in initial:
187 threshold = max(self.
_recent[task])
189 for source
in initial:
190 if source.task == task:
192 direct = self.
_score(task, source.policy,
"transfer_evaluations")
193 if direct <= threshold:
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)
204 def run(self, evaluate, budget, *, rounds):
205 """Return cumulative stats with a hard evaluator-call budget.
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.
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")
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
223 policy, score = self.
_train(pair.task, pair.policy,
"training_evaluations")
230 except _BudgetFinished: