6"""Assessment Coevolving with Diverse Capabilities on typed model and task payloads."""
8from dataclasses
import dataclass
9from typing
import Hashable
13from ._population
import _attempt_budget, _finite_vector
14from .modern
import _positive_int
16__all__ = [
"ACDCTaskRequest",
"ACDCResult",
"acdc"]
20@dataclass(frozen=True, slots=True)
22 """Use the current pass rate, parent and reference tasks to create an assessment."""
25 references: tuple[Hashable, ...]
31@dataclass(frozen=True)
33 """Keep active scores in model-major order and report task-force selection costs."""
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, ...]
44 team_uses_history: bool
53 def __init__(self, evaluate):
57 def pairs_needed(self, models, tasks):
58 return sum((model, task)
not in self.
values for model
in models
for task
in tasks)
60 def panel(self, models, tasks):
61 return np.asarray([[self.
score(model, task)
for task
in tasks]
for model
in models])
63 def score(self, model, task):
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].")
73def _task_direction(rate, threshold):
76 return "easier" if rate < threshold
else "novel"
79def _normalize_embedding(values, width=None):
80 vector = np.asarray(_finite_vector(values,
"Task embedding", width))
81 scale = float(np.abs(vector).max())
83 raise ValueError(
"Use nonzero task embeddings for cosine novelty.")
84 vector = vector / scale
85 return vector / np.linalg.norm(vector)
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)
96 weights /= weights.sum()
99 fitter = skills[quality > quality[i]]
101 gains = (skills[i] & ~fitter) @ weights
102 count = min(k, len(gains))
103 novelty = np.partition(gains, count - 1)[:count].mean()
106 local.append((i, novelty))
107 return [ranked[0], *(i
for i, _
in sorted(local, key=
lambda row: -row[1])[:capacity - 1])]
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)))
115 for _
in range(min(size, len(choices))):
116 best = max(choices, key=
lambda i: (np.count_nonzero(solved[i] & ~known), scores[i].mean()))
118 selected.append(models[best])
119 known |= solved[best]
120 return tuple(selected), float(known.mean())
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.
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.
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.
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))
195 model_rng, task_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
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)
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:
209 pool = dict.fromkeys(models)
210 for _
in range(offspring_size):
211 if len(scores.values) == budget:
213 indices = model_rng.choice(len(models), min(len(models), 2), replace=
False)
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)):
218 if len(scores.values) + scores.pairs_needed((child,), tasks) <= budget:
219 scores.panel((child,), tasks)
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:
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))
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)):
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()):
240 if (scores.panel(models, (task,)) >= passing_score).any():
241 embeddings[task] = vector
242 tasks = (*tasks, task)[-active_task_capacity:]
244 models = select(models)
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.
Information for generating a verifiable task variant.