# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Model Merging of Natural Niches for aligned numeric checkpoints.
# @see https://doi.org/10.1145/3712256.3726329
"""Breed checkpoint populations with shared per-example credit."""
from dataclasses import dataclass
import numpy as np
from ._population import _attempt_budget
from .cycle_qd import _checkpoint
from .modern import _positive_int
__all__ = ["M2N2Model", "M2N2Result", "m2n2"]
## @brief A measured model and its evaluation panel.
[docs]
@dataclass(frozen=True, eq=False)
class M2N2Model:
"""Each checkpoint preserves the common ordered tensor shapes."""
checkpoint: tuple[np.ndarray, ...]
scores: tuple[float, ...]
@property
def quality(self):
"""Return mean unshared performance for reporting."""
return float(np.mean(self.scores))
## @brief Final checkpoint population and separate measurement counters.
[docs]
@dataclass(frozen=True)
class M2N2Result:
"""Keep the best raw-scoring model even if resource selection discards it."""
population: tuple[M2N2Model, ...]
best: M2N2Model
shared_fitness: tuple[float, ...]
evaluations: int
seed_evaluations: int
replacements: int
def _resource_weights(scores, competition):
if competition == "mean":
return np.full(scores.shape[1], 1. / scores.shape[1])
capacity = np.ones(scores.shape[1]) if competition == "binary" else scores.max(axis=0)
return capacity / (scores.sum(axis=0) + 1e-8)
def _attraction(first, scores, weights):
return np.maximum(scores - first, 0.) @ weights
def _draw(weights, rng, exclude=None):
indices = np.arange(len(weights))
if exclude is not None:
indices = indices[indices != exclude]
weights = weights[indices]
total = weights.sum()
return int(rng.choice(indices, p=weights / total if total else None))
def _slerp(left, right, mixing):
if not len(left):
return left.copy()
scale = max(float(abs(left).max()), float(abs(right).max()))
if not scale:
return left.copy()
a, b = left / scale, right / scale
left_norm, right_norm = np.linalg.norm(a), np.linalg.norm(b)
if left_norm and right_norm:
cosine = float(np.clip((a / left_norm) @ (b / right_norm), -1., 1.))
if abs(cosine) < .9995:
angle = np.arccos(cosine)
return (np.sin((1. - mixing) * angle) * a + np.sin(mixing * angle) * b) / np.sin(angle) * scale
return (1. - mixing) * left + mixing * right
def _merge(left, right, split, mixing):
merged = np.concatenate((_slerp(left[:split], right[:split], mixing),
_slerp(left[split:], right[split:], 1. - mixing)))
if not np.isfinite(merged).all():
raise ValueError("Merging overflowed. Rescale the checkpoints.")
return merged
## @brief Search dynamic split points and complementary parent pairs.
# @param checkpoints At least two seed checkpoints of aligned numeric tensors.
# @param evaluate Callable (checkpoint) returning one score in [0, 1] per fixed example.
# @param budget Total measured models, including every seed.
# @param population_size Maximum number of live models.
# @param competition "continuous", "binary", or mean-fitness control ("mean").
# @param attraction Whether to draw the second parent by its weighted complementary gains.
# @param schedule_power Positive power of search progress for expanding merge bounds.
# @param seed Private variation seed.
# @return M2N2Result containing the population, best raw model and counts.
[docs]
def m2n2(checkpoints, evaluate, *, budget, population_size=8, competition="continuous",
attraction=True, schedule_power=1., seed=0):
"""Evolve an aligned checkpoint population under per-example competition.
Sample the first parent by shared fitness, then the second by its
directional improvements on the first parent's evaluation panel.
Apply complementary SLERP ratios on the two sides of a flattened split.
The eligible range of each parameter grows around its midpoint as the
budget progresses. Rank prospective survivor pools with a common
resource weight for each example.
"""
budget, capacity = _attempt_budget(budget), _positive_int(population_size, "population_size")
seeds = tuple(checkpoints)
if (len(seeds) < 2 or budget < len(seeds) or capacity < 2
or competition not in ("continuous", "binary", "mean") or not 0. < schedule_power < np.inf):
raise ValueError("Use at least two seeds, enough evaluations and valid competition settings.")
if not callable(evaluate):
raise TypeError("Supply a callable score-panel evaluator.")
base = _checkpoint(seeds[0])
shapes = tuple(arr.shape for arr in base)
offsets = np.cumsum([arr.size for arr in base])[:-1]
seeds = (base, *(_checkpoint(row, shapes) for row in seeds[1:]))
rng = np.random.default_rng(seed)
width = None
def measure(model, flat=None):
nonlocal width
scores = np.asarray(evaluate(model), dtype=float)
if (scores.ndim != 1 or not len(scores) or (width is not None and len(scores) != width)
or not np.all((0. <= scores) & (scores <= 1.))):
raise ValueError("Evaluate must return a fixed panel of finite scores in [0, 1].")
if competition == "binary" and np.any((scores != 0.) & (scores != 1.)):
raise ValueError("Binary competition requires scores of zero or one.")
width = len(scores)
flat = np.concatenate([arr.ravel() for arr in model]) if flat is None else flat
return M2N2Model(model, tuple(map(float, scores))), flat
pool = [measure(model) for model in seeds]
best = max((entry for entry, _ in pool), key=lambda row: row.quality)
scores = np.asarray([entry.scores for entry, _ in pool])
if len(pool) > capacity:
shared = scores @ _resource_weights(scores, competition)
indices = np.argsort(-shared, kind="stable")[:capacity]
pool, scores = [pool[i] for i in indices], scores[indices]
replacements = 0
offspring = budget - len(seeds)
for step in range(offspring):
weights = _resource_weights(scores, competition)
first = _draw(scores @ weights, rng)
compatibility = _attraction(scores[first], scores, weights) if attraction else scores @ weights
second = _draw(compatibility, rng, exclude=first)
left, right = pool[first][1], pool[second][1]
radius = .5 * ((step + 1) / offspring) ** schedule_power
split = round(len(left) * rng.uniform(.5 - radius, .5 + radius))
mixing = rng.uniform(.5 - radius, .5 + radius)
flat = _merge(left, right, split, mixing)
tensors = tuple(array.reshape(shape) for array, shape in zip(np.split(flat, offsets), shapes))
for array in tensors:
array.setflags(write=False)
child = measure(tensors, flat)
if child[0].quality > best.quality:
best = child[0]
candidate_scores = np.vstack((scores, child[0].scores))
if len(pool) < capacity:
pool.append(child)
scores = candidate_scores
continue
values = candidate_scores @ _resource_weights(candidate_scores, competition)
worst = int(np.argmin(values[:-1]))
if values[-1] > values[worst]:
pool[worst] = child
scores[worst] = candidate_scores[-1]
replacements += 1
return M2N2Result(tuple(entry for entry, _ in pool), best,
tuple(map(float, scores @ _resource_weights(scores, competition))), budget, len(seeds), replacements)