6"""Breed checkpoint populations with shared per-example credit."""
8from dataclasses
import dataclass
12from ._population
import _attempt_budget
13from .cycle_qd
import _checkpoint
14from .modern
import _positive_int
16__all__ = [
"M2N2Model",
"M2N2Result",
"m2n2"]
20@dataclass(frozen=True, eq=False)
22 """Each checkpoint preserves the common ordered tensor shapes."""
24 checkpoint: tuple[np.ndarray, ...]
25 scores: tuple[float, ...]
29 """Return mean unshared performance for reporting."""
30 return float(np.mean(self.
scores))
34@dataclass(frozen=True)
36 """Keep the best raw-scoring model even if resource selection discards it."""
38 population: tuple[M2N2Model, ...]
40 shared_fitness: tuple[float, ...]
46def _resource_weights(scores, competition):
47 if competition ==
"mean":
48 return np.full(scores.shape[1], 1. / scores.shape[1])
49 capacity = np.ones(scores.shape[1])
if competition ==
"binary" else scores.max(axis=0)
50 return capacity / (scores.sum(axis=0) + 1e-8)
53def _attraction(first, scores, weights):
54 return np.maximum(scores - first, 0.) @ weights
57def _draw(weights, rng, exclude=None):
58 indices = np.arange(len(weights))
59 if exclude
is not None:
60 indices = indices[indices != exclude]
61 weights = weights[indices]
63 return int(rng.choice(indices, p=weights / total
if total
else None))
66def _slerp(left, right, mixing):
69 scale = max(float(abs(left).max()), float(abs(right).max()))
72 a, b = left / scale, right / scale
73 left_norm, right_norm = np.linalg.norm(a), np.linalg.norm(b)
74 if left_norm
and right_norm:
75 cosine = float(np.clip((a / left_norm) @ (b / right_norm), -1., 1.))
76 if abs(cosine) < .9995:
77 angle = np.arccos(cosine)
78 return (np.sin((1. - mixing) * angle) * a + np.sin(mixing * angle) * b) / np.sin(angle) * scale
79 return (1. - mixing) * left + mixing * right
82def _merge(left, right, split, mixing):
83 merged = np.concatenate((_slerp(left[:split], right[:split], mixing),
84 _slerp(left[split:], right[split:], 1. - mixing)))
85 if not np.isfinite(merged).all():
86 raise ValueError(
"Merging overflowed. Rescale the checkpoints.")
100def m2n2(checkpoints, evaluate, *, budget, population_size=8, competition="continuous",
101 attraction=True, schedule_power=1., seed=0):
102 """Evolve an aligned checkpoint population under per-example competition.
104 Sample the first parent by shared fitness, then the second by its
105 directional improvements on the first parent's evaluation panel.
106 Apply complementary SLERP ratios on the two sides of a flattened split.
107 The eligible range of each parameter grows around its midpoint as the
108 budget progresses. Rank prospective survivor pools with a common
109 resource weight for each example.
111 budget, capacity = _attempt_budget(budget), _positive_int(population_size,
"population_size")
112 seeds = tuple(checkpoints)
113 if (len(seeds) < 2
or budget < len(seeds)
or capacity < 2
114 or competition
not in (
"continuous",
"binary",
"mean")
or not 0. < schedule_power < np.inf):
115 raise ValueError(
"Use at least two seeds, enough evaluations and valid competition settings.")
116 if not callable(evaluate):
117 raise TypeError(
"Supply a callable score-panel evaluator.")
118 base = _checkpoint(seeds[0])
119 shapes = tuple(arr.shape
for arr
in base)
120 offsets = np.cumsum([arr.size
for arr
in base])[:-1]
121 seeds = (base, *(_checkpoint(row, shapes)
for row
in seeds[1:]))
122 rng = np.random.default_rng(seed)
125 def measure(model, flat=None):
127 scores = np.asarray(evaluate(model), dtype=float)
128 if (scores.ndim != 1
or not len(scores)
or (width
is not None and len(scores) != width)
129 or not np.all((0. <= scores) & (scores <= 1.))):
130 raise ValueError(
"Evaluate must return a fixed panel of finite scores in [0, 1].")
131 if competition ==
"binary" and np.any((scores != 0.) & (scores != 1.)):
132 raise ValueError(
"Binary competition requires scores of zero or one.")
134 flat = np.concatenate([arr.ravel()
for arr
in model])
if flat
is None else flat
135 return M2N2Model(model, tuple(map(float, scores))), flat
137 pool = [measure(model)
for model
in seeds]
138 best = max((entry
for entry, _
in pool), key=
lambda row: row.quality)
139 scores = np.asarray([entry.scores
for entry, _
in pool])
140 if len(pool) > capacity:
141 shared = scores @ _resource_weights(scores, competition)
142 indices = np.argsort(-shared, kind=
"stable")[:capacity]
143 pool, scores = [pool[i]
for i
in indices], scores[indices]
145 offspring = budget - len(seeds)
146 for step
in range(offspring):
147 weights = _resource_weights(scores, competition)
148 first = _draw(scores @ weights, rng)
149 compatibility = _attraction(scores[first], scores, weights)
if attraction
else scores @ weights
150 second = _draw(compatibility, rng, exclude=first)
151 left, right = pool[first][1], pool[second][1]
152 radius = .5 * ((step + 1) / offspring) ** schedule_power
153 split = round(len(left) * rng.uniform(.5 - radius, .5 + radius))
154 mixing = rng.uniform(.5 - radius, .5 + radius)
155 flat = _merge(left, right, split, mixing)
156 tensors = tuple(array.reshape(shape)
for array, shape
in zip(np.split(flat, offsets), shapes))
157 for array
in tensors:
158 array.setflags(write=
False)
159 child = measure(tensors, flat)
160 if child[0].quality > best.quality:
162 candidate_scores = np.vstack((scores, child[0].scores))
163 if len(pool) < capacity:
165 scores = candidate_scores
167 values = candidate_scores @ _resource_weights(candidate_scores, competition)
168 worst = int(np.argmin(values[:-1]))
169 if values[-1] > values[worst]:
171 scores[worst] = candidate_scores[-1]
173 return M2N2Result(tuple(entry
for entry, _
in pool), best,
174 tuple(map(float, scores @ _resource_weights(scores, competition))), budget, len(seeds), replacements)
A measured model and its evaluation panel.
Final checkpoint population and separate measurement counters.