QDpy
Loading...
Searching...
No Matches
acdc.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Assessment Coevolving with Diverse Capabilities on typed model and task payloads."""
7
8from dataclasses import dataclass
9from typing import Hashable
10
11import numpy as np
12
13from ._population import _attempt_budget, _finite_vector
14from .modern import _positive_int
15
16__all__ = ["ACDCTaskRequest", "ACDCResult", "acdc"]
17
18
19
20@dataclass(frozen=True, slots=True)
22 """Use the current pass rate, parent and reference tasks to create an assessment."""
23
24 parent: Hashable
25 references: tuple[Hashable, ...]
26 pass_rate: float
27 direction: str
28
29
30
31@dataclass(frozen=True)
33 """Keep active scores in model-major order and report task-force selection costs."""
34
35 models: tuple[Hashable, ...]
36 tasks: tuple[Hashable, ...]
37 skill_vectors: tuple[tuple[float, ...], ...]
38 historical_models: tuple[Hashable, ...]
39 historical_tasks: tuple[Hashable, ...]
40 team: tuple[Hashable, ...]
41 team_tasks: tuple[Hashable, ...]
42 team_coverage: float
43 team_assessments: int
44 team_uses_history: bool
45 assessments: int
46 model_proposals: int
47 task_proposals: int
48 accepted_tasks: int
49 rounds: int
50
51
53 def __init__(self, evaluate):
54 self.evaluate = evaluate
55 self.values = {}
56
57 def pairs_needed(self, models, tasks):
58 return sum((model, task) not in self.values for model in models for task in tasks)
59
60 def panel(self, models, tasks):
61 return np.asarray([[self.score(model, task) for task in tasks] for model in models])
62
63 def score(self, model, task):
64 key = (model, task)
65 if key not in self.values:
66 score = float(self.evaluate(model, task))
67 if not 0. <= score <= 1.:
68 raise ValueError("Assessment scores must be finite and in [0, 1].")
69 self.values[key] = score
70 return self.values[key]
71
72
73def _task_direction(rate, threshold):
74 if rate > threshold:
75 return "harder"
76 return "easier" if rate < threshold else "novel"
77
78
79def _normalize_embedding(values, width=None):
80 vector = np.asarray(_finite_vector(values, "Task embedding", width))
81 scale = float(np.abs(vector).max())
82 if not scale:
83 raise ValueError("Use nonzero task embeddings for cosine novelty.")
84 vector = vector / scale
85 return vector / np.linalg.norm(vector)
86
87
88def _skill_selection(scores, capacity, k, passing, selection):
89 skills = scores >= passing
90 quality = skills.mean(axis=1)
91 ranked = sorted(range(len(quality)), key=lambda i: -quality[i])
92 if selection == "quality" or len(ranked) <= capacity:
93 return ranked[:capacity]
94 weights = 1. - skills.mean(axis=0)
95 if weights.sum():
96 weights /= weights.sum()
97 local = []
98 for i in ranked[1:]:
99 fitter = skills[quality > quality[i]]
100 if len(fitter):
101 gains = (skills[i] & ~fitter) @ weights
102 count = min(k, len(gains))
103 novelty = np.partition(gains, count - 1)[:count].mean()
104 else:
105 novelty = np.inf
106 local.append((i, novelty))
107 return [ranked[0], *(i for i, _ in sorted(local, key=lambda row: -row[1])[:capacity - 1])]
108
109
110def _team_selection(models, scores, passing, size):
111 solved = scores >= passing
112 known = np.zeros(scores.shape[1], dtype=bool)
113 choices = list(range(len(models)))
114 selected = []
115 for _ in range(min(size, len(choices))):
116 best = max(choices, key=lambda i: (np.count_nonzero(solved[i] & ~known), scores[i].mean()))
117 choices.remove(best)
118 selected.append(models[best])
119 known |= solved[best]
120 return tuple(selected), float(known.mean())
121
122
123
148def acdc(initial_models, initial_tasks, *, vary_model, propose_task, evaluate, task_descriptor,
149 budget, rounds, model_capacity=8, offspring_size=8, active_task_capacity=16,
150 task_period=2, task_proposals=4, task_novelty=.05, passing_score=.5,
151 difficulty_target=.5, novelty_neighbors=3, selection="novelty", valid_model=None,
152 valid_task=None, team_size=3, team_budget=0, seed=0):
153 """Select models for unique skills and keep novel, solvable assessments.
154
155 Measure every active model on new tasks before admitting them. Retain
156 the best model and rank the others by difficulty-weighted solved tasks
157 missed by fitter models. Task proposals receive the parent's pass rate
158 and direction. The active task panel rolls forward as novel tasks enter.
159
160 A proposal is measured only when its whole assessment panel fits the
161 search budget. Scores for identical pairs are reused across generations.
162 For final team selection, score the historical panel if its missing
163 pairs fit the separate team budget. Otherwise score coverage on the
164 fully observed active panel. Both stages use caller-owned evaluators.
165 """
166 budget, rounds = _attempt_budget(budget), _attempt_budget(rounds)
167 task_proposals, team_size, team_budget = map(_attempt_budget, (task_proposals, team_size, team_budget))
168 model_capacity = _positive_int(model_capacity, "model_capacity")
169 offspring_size = _positive_int(offspring_size, "offspring_size")
170 active_task_capacity = _positive_int(active_task_capacity, "active_task_capacity")
171 task_period = _positive_int(task_period, "task_period")
172 k = _positive_int(novelty_neighbors, "novelty_neighbors")
173 if not (0 <= task_novelty <= 2 and 0 < passing_score <= 1 and 0 <= difficulty_target <= 1):
174 raise ValueError("Invalid task novelty, passing score, or difficulty target.")
175 if selection not in ("novelty", "quality"):
176 raise ValueError("Choose novelty or quality selection.")
177 if (not all(map(callable, (vary_model, evaluate, task_descriptor)))
178 or any(cb is not None and not callable(cb) for cb in (propose_task, valid_model, valid_task))):
179 raise TypeError("Use callable model, task, and assessment operations.")
180 models, tasks = tuple(initial_models), tuple(initial_tasks)
181 if (not models or not tasks or None in models or None in tasks or len(set(models)) != len(models)
182 or len(set(tasks)) != len(tasks) or len(tasks) > active_task_capacity):
183 raise ValueError("Supply distinct nonempty model/task seeds and room for every seed task.")
184 if valid_model is not None and not all(map(valid_model, models)):
185 raise ValueError("Every seed model must pass valid_model.")
186 if valid_task is not None and not all(map(valid_task, tasks)):
187 raise ValueError("Every seed task must pass valid_task.")
188 if len(models) * len(tasks) > budget:
189 raise ValueError("The budget cannot cover the initial model-task panel.")
190 first = _normalize_embedding(task_descriptor(tasks[0]))
191 embeddings = {tasks[0]: first}
192 for task in tasks[1:]:
193 embeddings[task] = _normalize_embedding(task_descriptor(task), len(first))
194
195 model_rng, task_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
196 scores = _Assessments(evaluate)
197
198 def select(pool):
199 matrix = scores.panel(pool, tasks)
200 order = _skill_selection(matrix, model_capacity, k, passing_score, selection)
201 return tuple(pool[i] for i in order)
202
203 models = select(models)
204 history = dict.fromkeys(models)
205 model_attempts = task_attempts = accepted = completed = 0
206 for tick in range(1, rounds + 1):
207 if len(scores.values) == budget:
208 break
209 pool = dict.fromkeys(models)
210 for _ in range(offspring_size):
211 if len(scores.values) == budget:
212 break
213 indices = model_rng.choice(len(models), min(len(models), 2), replace=False)
214 model_attempts += 1
215 child = vary_model(tuple(models[i] for i in indices), model_rng)
216 if child is None or child in pool or (valid_model is not None and not valid_model(child)):
217 continue
218 if len(scores.values) + scores.pairs_needed((child,), tasks) <= budget:
219 scores.panel((child,), tasks)
220 pool[child] = None
221 models = select(tuple(pool))
222 history.update(dict.fromkeys(models))
223 if propose_task is not None and tick % task_period == 0:
224 for _ in range(task_proposals):
225 if len(scores.values) + len(models) > budget:
226 break
227 parent_index = int(task_rng.integers(len(tasks)))
228 parent = tasks[parent_index]
229 others = [i for i in range(len(tasks)) if i != parent_index]
230 references = tuple(tasks[i] for i in task_rng.permutation(others)[:3])
231 rate = float((scores.panel(models, (parent,)) >= passing_score).mean())
232 request = ACDCTaskRequest(parent, references, rate, _task_direction(rate, difficulty_target))
233 task_attempts += 1
234 task = propose_task(request, task_rng)
235 if task is None or task in embeddings or (valid_task is not None and not valid_task(task)):
236 continue
237 vector = _normalize_embedding(task_descriptor(task), len(first))
238 if any(np.clip(1. - vector @ other, 0., 2.) < task_novelty for other in embeddings.values()):
239 continue
240 if (scores.panel(models, (task,)) >= passing_score).any():
241 embeddings[task] = vector
242 tasks = (*tasks, task)[-active_task_capacity:]
243 accepted += 1
244 models = select(models)
245 completed += 1
246
247 assessments = len(scores.values)
248 historical_models, historical_tasks = tuple(history), tuple(embeddings)
249 missing = scores.pairs_needed(historical_models, historical_tasks)
250 historical = bool(team_size and missing <= team_budget)
251 panel_models, panel_tasks = (historical_models, historical_tasks) if historical else (models, tasks)
252 team, coverage = _team_selection(panel_models, scores.panel(panel_models, panel_tasks), passing_score, team_size)
253 active = tuple(tuple(map(float, row)) for row in scores.panel(models, tasks))
254 return ACDCResult(models, tasks, active, historical_models, historical_tasks, team, panel_tasks,
255 coverage, len(scores.values) - assessments, historical, assessments, model_attempts,
256 task_attempts, accepted, completed)
Model and task archives after a bounded AC/DC run.
Definition acdc.py:32
Information for generating a verifiable task variant.
Definition acdc.py:21
score(self, model, task)
Definition acdc.py:63