# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Coevolve specialist models and measured assessment tasks.
# @see https://openreview.net/pdf?id=efNINVs2So
"""Assessment Coevolving with Diverse Capabilities on typed model and task payloads."""
from dataclasses import dataclass
from typing import Hashable
import numpy as np
from ._population import _attempt_budget, _finite_vector
from .modern import _positive_int
__all__ = ["ACDCTaskRequest", "ACDCResult", "acdc"]
## @brief Information for generating a verifiable task variant.
[docs]
@dataclass(frozen=True, slots=True)
class ACDCTaskRequest:
"""Use the current pass rate, parent and reference tasks to create an assessment."""
parent: Hashable
references: tuple[Hashable, ...]
pass_rate: float
direction: str
## @brief Model and task archives after a bounded AC/DC run.
[docs]
@dataclass(frozen=True)
class ACDCResult:
"""Keep active scores in model-major order and report task-force selection costs."""
models: tuple[Hashable, ...]
tasks: tuple[Hashable, ...]
skill_vectors: tuple[tuple[float, ...], ...]
historical_models: tuple[Hashable, ...]
historical_tasks: tuple[Hashable, ...]
team: tuple[Hashable, ...]
team_tasks: tuple[Hashable, ...]
team_coverage: float
team_assessments: int
team_uses_history: bool
assessments: int
model_proposals: int
task_proposals: int
accepted_tasks: int
rounds: int
class _Assessments:
def __init__(self, evaluate):
self.evaluate = evaluate
self.values = {}
def pairs_needed(self, models, tasks):
return sum((model, task) not in self.values for model in models for task in tasks)
def panel(self, models, tasks):
return np.asarray([[self.score(model, task) for task in tasks] for model in models])
def score(self, model, task):
key = (model, task)
if key not in self.values:
score = float(self.evaluate(model, task))
if not 0. <= score <= 1.:
raise ValueError("Assessment scores must be finite and in [0, 1].")
self.values[key] = score
return self.values[key]
def _task_direction(rate, threshold):
if rate > threshold:
return "harder"
return "easier" if rate < threshold else "novel"
def _normalize_embedding(values, width=None):
vector = np.asarray(_finite_vector(values, "Task embedding", width))
scale = float(np.abs(vector).max())
if not scale:
raise ValueError("Use nonzero task embeddings for cosine novelty.")
vector = vector / scale
return vector / np.linalg.norm(vector)
def _skill_selection(scores, capacity, k, passing, selection):
skills = scores >= passing
quality = skills.mean(axis=1)
ranked = sorted(range(len(quality)), key=lambda i: -quality[i])
if selection == "quality" or len(ranked) <= capacity:
return ranked[:capacity]
weights = 1. - skills.mean(axis=0)
if weights.sum():
weights /= weights.sum()
local = []
for i in ranked[1:]:
fitter = skills[quality > quality[i]]
if len(fitter):
gains = (skills[i] & ~fitter) @ weights
count = min(k, len(gains))
novelty = np.partition(gains, count - 1)[:count].mean()
else:
novelty = np.inf
local.append((i, novelty))
return [ranked[0], *(i for i, _ in sorted(local, key=lambda row: -row[1])[:capacity - 1])]
def _team_selection(models, scores, passing, size):
solved = scores >= passing
known = np.zeros(scores.shape[1], dtype=bool)
choices = list(range(len(models)))
selected = []
for _ in range(min(size, len(choices))):
best = max(choices, key=lambda i: (np.count_nonzero(solved[i] & ~known), scores[i].mean()))
choices.remove(best)
selected.append(models[best])
known |= solved[best]
return tuple(selected), float(known.mean())
## @brief Evolve model skills and assess new tasks under exact pairwise call budgets.
# @param initial_models Ordered, distinct immutable model payloads.
# @param initial_tasks Ordered, distinct immutable seed assessment payloads.
# @param vary_model Callable (parents, rng), returning a new immutable model or None.
# @param propose_task Optional callable (ACDCTaskRequest, rng), returning a new task or None.
# @param evaluate Callable (model, task), returning a deterministic score in [0, 1].
# @param task_descriptor Callable (task) returning a fixed-width nonzero embedding.
# @param budget Search assessment cap, including seed pairs and new task screening.
# @param rounds Maximum model generations.
# @param model_capacity Number of active parent models.
# @param offspring_size Maximum number of model proposals each generation.
# @param active_task_capacity Maximum number of active assessment tasks.
# @param task_period Generations between task proposal batches.
# @param task_proposals Maximum number of new task proposals each task generation.
# @param task_novelty Minimum cosine distance from every previous accepted task.
# @param passing_score Score needed to solve a task, in (0, 1].
# @param difficulty_target Pass rate used to request easier or harder variants.
# @param novelty_neighbors Maximum number of fitter models used in skill novelty.
# @param selection "novelty" for AC/DC or "quality" for mean-solved selection.
# @param valid_model Optional predicate to reject invalid models before measuring them.
# @param valid_task Optional predicate for task validation before assessment.
# @param team_size Maximum number of deployable models selected for task coverage.
# @param team_budget Separate cap on final missing historical assessments.
# @param seed Private model and task seeds.
# @return Active and historical archives, skill vectors, and separate assessment counts.
[docs]
def acdc(initial_models, initial_tasks, *, vary_model, propose_task, evaluate, task_descriptor,
budget, rounds, model_capacity=8, offspring_size=8, active_task_capacity=16,
task_period=2, task_proposals=4, task_novelty=.05, passing_score=.5,
difficulty_target=.5, novelty_neighbors=3, selection="novelty", valid_model=None,
valid_task=None, team_size=3, team_budget=0, seed=0):
"""Select models for unique skills and keep novel, solvable assessments.
Measure every active model on new tasks before admitting them. Retain
the best model and rank the others by difficulty-weighted solved tasks
missed by fitter models. Task proposals receive the parent's pass rate
and direction. The active task panel rolls forward as novel tasks enter.
A proposal is measured only when its whole assessment panel fits the
search budget. Scores for identical pairs are reused across generations.
For final team selection, score the historical panel if its missing
pairs fit the separate team budget. Otherwise score coverage on the
fully observed active panel. Both stages use caller-owned evaluators.
"""
budget, rounds = _attempt_budget(budget), _attempt_budget(rounds)
task_proposals, team_size, team_budget = map(_attempt_budget, (task_proposals, team_size, team_budget))
model_capacity = _positive_int(model_capacity, "model_capacity")
offspring_size = _positive_int(offspring_size, "offspring_size")
active_task_capacity = _positive_int(active_task_capacity, "active_task_capacity")
task_period = _positive_int(task_period, "task_period")
k = _positive_int(novelty_neighbors, "novelty_neighbors")
if not (0 <= task_novelty <= 2 and 0 < passing_score <= 1 and 0 <= difficulty_target <= 1):
raise ValueError("Invalid task novelty, passing score, or difficulty target.")
if selection not in ("novelty", "quality"):
raise ValueError("Choose novelty or quality selection.")
if (not all(map(callable, (vary_model, evaluate, task_descriptor)))
or any(cb is not None and not callable(cb) for cb in (propose_task, valid_model, valid_task))):
raise TypeError("Use callable model, task, and assessment operations.")
models, tasks = tuple(initial_models), tuple(initial_tasks)
if (not models or not tasks or None in models or None in tasks or len(set(models)) != len(models)
or len(set(tasks)) != len(tasks) or len(tasks) > active_task_capacity):
raise ValueError("Supply distinct nonempty model/task seeds and room for every seed task.")
if valid_model is not None and not all(map(valid_model, models)):
raise ValueError("Every seed model must pass valid_model.")
if valid_task is not None and not all(map(valid_task, tasks)):
raise ValueError("Every seed task must pass valid_task.")
if len(models) * len(tasks) > budget:
raise ValueError("The budget cannot cover the initial model-task panel.")
first = _normalize_embedding(task_descriptor(tasks[0]))
embeddings = {tasks[0]: first}
for task in tasks[1:]:
embeddings[task] = _normalize_embedding(task_descriptor(task), len(first))
model_rng, task_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
scores = _Assessments(evaluate)
def select(pool):
matrix = scores.panel(pool, tasks)
order = _skill_selection(matrix, model_capacity, k, passing_score, selection)
return tuple(pool[i] for i in order)
models = select(models)
history = dict.fromkeys(models)
model_attempts = task_attempts = accepted = completed = 0
for tick in range(1, rounds + 1):
if len(scores.values) == budget:
break
pool = dict.fromkeys(models)
for _ in range(offspring_size):
if len(scores.values) == budget:
break
indices = model_rng.choice(len(models), min(len(models), 2), replace=False)
model_attempts += 1
child = vary_model(tuple(models[i] for i in indices), model_rng)
if child is None or child in pool or (valid_model is not None and not valid_model(child)):
continue
if len(scores.values) + scores.pairs_needed((child,), tasks) <= budget:
scores.panel((child,), tasks)
pool[child] = None
models = select(tuple(pool))
history.update(dict.fromkeys(models))
if propose_task is not None and tick % task_period == 0:
for _ in range(task_proposals):
if len(scores.values) + len(models) > budget:
break
parent_index = int(task_rng.integers(len(tasks)))
parent = tasks[parent_index]
others = [i for i in range(len(tasks)) if i != parent_index]
references = tuple(tasks[i] for i in task_rng.permutation(others)[:3])
rate = float((scores.panel(models, (parent,)) >= passing_score).mean())
request = ACDCTaskRequest(parent, references, rate, _task_direction(rate, difficulty_target))
task_attempts += 1
task = propose_task(request, task_rng)
if task is None or task in embeddings or (valid_task is not None and not valid_task(task)):
continue
vector = _normalize_embedding(task_descriptor(task), len(first))
if any(np.clip(1. - vector @ other, 0., 2.) < task_novelty for other in embeddings.values()):
continue
if (scores.panel(models, (task,)) >= passing_score).any():
embeddings[task] = vector
tasks = (*tasks, task)[-active_task_capacity:]
accepted += 1
models = select(models)
completed += 1
assessments = len(scores.values)
historical_models, historical_tasks = tuple(history), tuple(embeddings)
missing = scores.pairs_needed(historical_models, historical_tasks)
historical = bool(team_size and missing <= team_budget)
panel_models, panel_tasks = (historical_models, historical_tasks) if historical else (models, tasks)
team, coverage = _team_selection(panel_models, scores.panel(panel_models, panel_tasks), passing_score, team_size)
active = tuple(tuple(map(float, row)) for row in scores.panel(models, tasks))
return ACDCResult(models, tasks, active, historical_models, historical_tasks, team, panel_tasks,
coverage, len(scores.values) - assessments, historical, assessments, model_attempts,
task_attempts, accepted, completed)