Source code for qdpy.algorithms.cycle_qd

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Evolve merged checkpoints by rotating objective and descriptor tasks.
# @see https://proceedings.iclr.cc/paper_files/paper/2025/hash/755acd0c7c07180d78959b6d89768207-Abstract-Conference.html

"""CycleQD for numeric checkpoints with shared parameter layout and base."""

from dataclasses import dataclass
from operator import index

import numpy as np
from scipy.special import softmax

from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual

from .modern import _positive_int
from .parametric import _Coordinates

__all__ = ["CycleQD", "CycleQDStats"]


## @brief Per-call CycleQD measurement and archive admission counts.
[docs] @dataclass(frozen=True) class CycleQDStats: """Count each measured checkpoint once, independent of archive count.""" evaluations: int expert_evaluations: int archive_updates: int out_of_domain: int breeding_by_task: tuple[int, ...]
def _checkpoint(raw, shapes=None): arrays = [] for value in raw: array = np.asarray(value) if array.dtype.kind not in "iuf" or not array.size: raise ValueError("Checkpoint tensors must be nonempty real numeric arrays.") array = np.array(array, dtype=float, copy=True) if not np.isfinite(array).all(): raise ValueError("Checkpoint tensors must be finite.") array.setflags(write=False) arrays.append(array) if not arrays or (shapes is not None and tuple(a.shape for a in arrays) != shapes): raise ValueError("Checkpoints must share the same ordered tensor shapes.") return tuple(arrays) ## @brief Scale the singular components of a task delta, passing rank-one tensors through. def _mutate_delta(delta, limit, rng): if delta.ndim < 2: return delta matrix = delta.reshape(delta.shape[0], -1) left, singular, right = np.linalg.svd(matrix, full_matrices=False) tolerance = singular[0] * max(matrix.shape) * np.finfo(float).eps if np.count_nonzero(singular > tolerance) < 2: return delta factors = rng.uniform(0., limit, size=len(singular)) return ((left * (singular * factors)) @ right).reshape(delta.shape) ## @brief Rotate active task archives, merge parents, and reuse measured task scores.
[docs] class CycleQD: """Maintain one Grid for each objective role and score every checkpoint on all tasks. Each archive maximizes or minimizes its active task. Other tasks supply the descriptor axes in the original order. Every measured candidate is offered to all archives. Parent probabilities follow the product of rescaled task performances in the active archive. :param base: Ordered real numeric tensors from the common base model. :param experts: Nonempty checkpoints with the same ordered tensor shapes. :param task_domains: One finite increasing interval for each task score. :param bins: Common bin count or one bin count per task descriptor. :param fitness_weights: Optional signed weights for task directions. All tasks maximize by default. :param task_order: Optional sequence of breeding task indices. Defaults to all tasks in order. One task gives a fixed-role control. :param parent_weight_bounds: Positive (low, high) range for the product score. :param merge_mean: Mean of the two Gaussian crossover coefficients. :param merge_std: Standard deviation of the Gaussian crossover coefficients. :param svd_max: Upper bound for each singular-component multiplier. Set to None for crossover alone. :param seed: Private seed for parent choice, crossover and mutation. """ def __init__(self, base, experts, task_domains, *, bins=12, fitness_weights=None, task_order=None, parent_weight_bounds=(.1, 1.), merge_mean=1., merge_std=.3, svd_max=2., seed=0): domain = _Coordinates(task_domains) n = len(domain.bounds) if n < 2: raise ValueError("CycleQD requires at least two task score domains.") weights = np.ones(n) if fitness_weights is None else np.asarray(fitness_weights, dtype=float) if weights.shape != (n,) or not np.isfinite(weights).all() or np.any(weights == 0.): raise ValueError("Supply one finite nonzero fitness weight per task.") counts = ((_positive_int(bins, "bins"),) * n if np.isscalar(bins) else tuple(_positive_int(k, "bins") for k in bins)) if len(counts) != n: raise ValueError("Supply one bin count per task.") order = tuple(range(n)) if task_order is None else tuple(map(index, task_order)) if not order or any(not 0 <= task < n for task in order): raise ValueError("task_order must contain valid task indices.") lower, upper = parent_weight_bounds if not 0. < lower <= upper < np.inf: raise ValueError("Parent weights require positive finite bounds in increasing order.") if not 0. < merge_mean < np.inf or not 0. <= merge_std < np.inf: raise ValueError("Use a finite positive merge mean and nonnegative deviation.") if svd_max is not None and not 0. < svd_max < np.inf: raise ValueError("Use a finite positive svd_max or None.") self._base = _checkpoint(base) self._shapes = tuple(tensor.shape for tensor in self._base) self._experts = tuple(_checkpoint(model, self._shapes) for model in experts) if not self._experts: raise ValueError("Provide at least one aligned expert checkpoint.") self._domain, self._direction = domain, np.sign(weights) self._order, self._parent_bounds = order, (lower, upper) self._mean, self._std, self._svd_max = merge_mean, merge_std, svd_max self._rng = np.random.default_rng(seed) self._evaluations = self._expert_index = self._offspring = 0 self._axes = tuple(tuple(axis for axis in range(n) if axis != i) for i in range(n)) self.archives = tuple( Grid(shape=tuple(counts[axis] for axis in axes), fitness_domain=(domain.bounds[i],), features_domain=tuple(domain.bounds[axis] for axis in axes), fitness_weights=(weights[i],)) for i, axes in enumerate(self._axes) ) def _breed(self, archive): performance = self._domain.normalize([ind.scores["cycle_scores"] for ind in archive]) * self._direction span = np.ptp(performance, axis=0) normalized = np.divide(performance - performance.min(axis=0), span, out=np.zeros_like(performance), where=span > 0) lower, upper = self._parent_bounds weights = softmax(np.log(lower + (upper - lower) * normalized).sum(axis=1)) first, second = (archive[int(i)]._cycle_checkpoint for i in self._rng.choice(len(archive), 2, p=weights)) coefficients = self._rng.normal(self._mean, self._std, size=2) denominator = coefficients.sum() # A near-zero signed sum can create nonfinite checkpoint extrapolations. if abs(denominator) <= 1e-8 * np.max(np.abs(coefficients)): coefficients[:] = .5 else: coefficients /= denominator result = [] with np.errstate(over="ignore", invalid="ignore"): for base, left, right in zip(self._base, first, second, strict=True): delta = coefficients[0] * (left - base) + coefficients[1] * (right - base) if not np.isfinite(delta).all(): raise ValueError("The merged task vector is nonfinite.") if self._svd_max is not None: delta = _mutate_delta(delta, self._svd_max, self._rng) result.append(base + delta) return _checkpoint(result, self._shapes) ## @brief Copy an elite checkpoint for loading or external evaluation.
[docs] def checkpoint(self, elite): """Return independent writable arrays in the original tensor order.""" return tuple(array.copy() for array in elite._cycle_checkpoint)
## @brief Merge the highest-scoring elite from each archive using softmax weights.
[docs] def aggregate(self): """Return the paper's final weighted merge of the task specialists.""" if any(not archive for archive in self.archives): raise RuntimeError("Measure an admissible checkpoint before aggregating.") elites = [max(archive, key=lambda ind: (self._direction[task] * ind.fitness.values[0], ind[0])) for task, archive in enumerate(self.archives)] quality = [self._direction[task] * elite.fitness.values[0] for task, elite in enumerate(elites)] weights = softmax(quality) return tuple( np.sum([weight * elite._cycle_checkpoint[layer] for elite, weight in zip(elites, weights)], axis=0) for layer in range(len(self._base)) )
## @brief Measure experts and offspring sequentially under an additional checkpoint budget.
[docs] def run(self, evaluate, budget): """Call evaluate(checkpoint) for one score per task and return counters.""" if not callable(evaluate): raise TypeError("evaluate must be callable.") budget = _positive_int(budget, "budget") counts = [0] * len(self.archives) experts = updates = outside = 0 for _ in range(budget): if self._expert_index < len(self._experts): model = self._experts[self._expert_index] self._expert_index += 1 experts += 1 else: task = self._order[self._offspring % len(self._order)] archive = self.archives[task] if not archive: raise ValueError("At least one expert must score within all task domains.") model = self._breed(archive) self._offspring += 1 counts[task] += 1 self._evaluations += 1 scores = np.asarray(evaluate(tuple(array.copy() for array in model)), dtype=float) if scores.shape != (len(self.archives),) or not np.isfinite(scores).all(): raise ValueError("Return one finite score per task.") if np.any((scores < self._domain.lower) | (scores > self._domain.upper)): outside += 1 continue for task, (archive, axes) in enumerate(zip(self.archives, self._axes, strict=True)): elite = Individual([self._evaluations], fitness=Fitness((scores[task],), weights=archive.fitness_weights), features=Features(scores[list(axes)])) elite._cycle_checkpoint = model elite.scores["cycle_scores"] = tuple(scores) updates += archive.add(elite) is not None return CycleQDStats(budget, experts, updates, outside, tuple(counts))