QDpy
Loading...
Searching...
No Matches
cycle_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""CycleQD for numeric checkpoints with shared parameter layout and base."""
7
8from dataclasses import dataclass
9from operator import index
10
11import numpy as np
12from scipy.special import softmax
13
14from qdpy.containers import Grid
15from qdpy.phenotype import Features, Fitness, Individual
16
17from .modern import _positive_int
18from .parametric import _Coordinates
19
20__all__ = ["CycleQD", "CycleQDStats"]
21
22
23
24@dataclass(frozen=True)
26 """Count each measured checkpoint once, independent of archive count."""
27
28 evaluations: int
29 expert_evaluations: int
30 archive_updates: int
31 out_of_domain: int
32 breeding_by_task: tuple[int, ...]
33
34
35def _checkpoint(raw, shapes=None):
36 arrays = []
37 for value in raw:
38 array = np.asarray(value)
39 if array.dtype.kind not in "iuf" or not array.size:
40 raise ValueError("Checkpoint tensors must be nonempty real numeric arrays.")
41 array = np.array(array, dtype=float, copy=True)
42 if not np.isfinite(array).all():
43 raise ValueError("Checkpoint tensors must be finite.")
44 array.setflags(write=False)
45 arrays.append(array)
46 if not arrays or (shapes is not None and tuple(a.shape for a in arrays) != shapes):
47 raise ValueError("Checkpoints must share the same ordered tensor shapes.")
48 return tuple(arrays)
49
50
51
52def _mutate_delta(delta, limit, rng):
53 if delta.ndim < 2:
54 return delta
55 matrix = delta.reshape(delta.shape[0], -1)
56 left, singular, right = np.linalg.svd(matrix, full_matrices=False)
57 tolerance = singular[0] * max(matrix.shape) * np.finfo(float).eps
58 if np.count_nonzero(singular > tolerance) < 2:
59 return delta
60 factors = rng.uniform(0., limit, size=len(singular))
61 return ((left * (singular * factors)) @ right).reshape(delta.shape)
62
63
64
65class CycleQD:
66 """Maintain one Grid for each objective role and score every checkpoint on all tasks.
67
68 Each archive maximizes or minimizes its active task. Other tasks
69 supply the descriptor axes in the original order. Every measured
70 candidate is offered to all archives. Parent probabilities follow
71 the product of rescaled task performances in the active archive.
72
73 :param base: Ordered real numeric tensors from the common base model.
74 :param experts: Nonempty checkpoints with the same ordered tensor shapes.
75 :param task_domains: One finite increasing interval for each task score.
76 :param bins: Common bin count or one bin count per task descriptor.
77 :param fitness_weights: Optional signed weights for task directions.
78 All tasks maximize by default.
79 :param task_order: Optional sequence of breeding task indices. Defaults
80 to all tasks in order. One task gives a fixed-role control.
81 :param parent_weight_bounds: Positive (low, high) range for the product score.
82 :param merge_mean: Mean of the two Gaussian crossover coefficients.
83 :param merge_std: Standard deviation of the Gaussian crossover coefficients.
84 :param svd_max: Upper bound for each singular-component multiplier.
85 Set to None for crossover alone.
86 :param seed: Private seed for parent choice, crossover and mutation.
87 """
88
89 def __init__(self, base, experts, task_domains, *, bins=12, fitness_weights=None,
90 task_order=None, parent_weight_bounds=(.1, 1.), merge_mean=1., merge_std=.3,
91 svd_max=2., seed=0):
92 domain = _Coordinates(task_domains)
93 n = len(domain.bounds)
94 if n < 2:
95 raise ValueError("CycleQD requires at least two task score domains.")
96 weights = np.ones(n) if fitness_weights is None else np.asarray(fitness_weights, dtype=float)
97 if weights.shape != (n,) or not np.isfinite(weights).all() or np.any(weights == 0.):
98 raise ValueError("Supply one finite nonzero fitness weight per task.")
99 counts = ((_positive_int(bins, "bins"),) * n if np.isscalar(bins)
100 else tuple(_positive_int(k, "bins") for k in bins))
101 if len(counts) != n:
102 raise ValueError("Supply one bin count per task.")
103 order = tuple(range(n)) if task_order is None else tuple(map(index, task_order))
104 if not order or any(not 0 <= task < n for task in order):
105 raise ValueError("task_order must contain valid task indices.")
106 lower, upper = parent_weight_bounds
107 if not 0. < lower <= upper < np.inf:
108 raise ValueError("Parent weights require positive finite bounds in increasing order.")
109 if not 0. < merge_mean < np.inf or not 0. <= merge_std < np.inf:
110 raise ValueError("Use a finite positive merge mean and nonnegative deviation.")
111 if svd_max is not None and not 0. < svd_max < np.inf:
112 raise ValueError("Use a finite positive svd_max or None.")
113
114 self._base = _checkpoint(base)
115 self._shapes = tuple(tensor.shape for tensor in self._base)
116 self._experts = tuple(_checkpoint(model, self._shapes) for model in experts)
117 if not self._experts:
118 raise ValueError("Provide at least one aligned expert checkpoint.")
119 self._domain, self._direction = domain, np.sign(weights)
120 self._order, self._parent_bounds = order, (lower, upper)
121 self._mean, self._std, self._svd_max = merge_mean, merge_std, svd_max
122 self._rng = np.random.default_rng(seed)
123 self._evaluations = self._expert_index = self._offspring = 0
124 self._axes = tuple(tuple(axis for axis in range(n) if axis != i) for i in range(n))
125 self.archives = tuple(
126 Grid(shape=tuple(counts[axis] for axis in axes), fitness_domain=(domain.bounds[i],),
127 features_domain=tuple(domain.bounds[axis] for axis in axes), fitness_weights=(weights[i],))
128 for i, axes in enumerate(self._axes)
129 )
130
131 def _breed(self, archive):
132 performance = self._domain.normalize([ind.scores["cycle_scores"] for ind in archive]) * self._direction
133 span = np.ptp(performance, axis=0)
134 normalized = np.divide(performance - performance.min(axis=0), span,
135 out=np.zeros_like(performance), where=span > 0)
136 lower, upper = self._parent_bounds
137 weights = softmax(np.log(lower + (upper - lower) * normalized).sum(axis=1))
138 first, second = (archive[int(i)]._cycle_checkpoint for i in self._rng.choice(len(archive), 2, p=weights))
139 coefficients = self._rng.normal(self._mean, self._std, size=2)
140 denominator = coefficients.sum()
141 # A near-zero signed sum can create nonfinite checkpoint extrapolations.
142 if abs(denominator) <= 1e-8 * np.max(np.abs(coefficients)):
143 coefficients[:] = .5
144 else:
145 coefficients /= denominator
146 result = []
147 with np.errstate(over="ignore", invalid="ignore"):
148 for base, left, right in zip(self._base, first, second, strict=True):
149 delta = coefficients[0] * (left - base) + coefficients[1] * (right - base)
150 if not np.isfinite(delta).all():
151 raise ValueError("The merged task vector is nonfinite.")
152 if self._svd_max is not None:
153 delta = _mutate_delta(delta, self._svd_max, self._rng)
154 result.append(base + delta)
155 return _checkpoint(result, self._shapes)
156
157
158 def checkpoint(self, elite):
159 """Return independent writable arrays in the original tensor order."""
160 return tuple(array.copy() for array in elite._cycle_checkpoint)
161
162
163 def aggregate(self):
164 """Return the paper's final weighted merge of the task specialists."""
165 if any(not archive for archive in self.archives):
166 raise RuntimeError("Measure an admissible checkpoint before aggregating.")
167 elites = [max(archive, key=lambda ind: (self._direction[task] * ind.fitness.values[0], ind[0]))
168 for task, archive in enumerate(self.archives)]
169 quality = [self._direction[task] * elite.fitness.values[0] for task, elite in enumerate(elites)]
170 weights = softmax(quality)
171 return tuple(
172 np.sum([weight * elite._cycle_checkpoint[layer] for elite, weight in zip(elites, weights)], axis=0)
173 for layer in range(len(self._base))
174 )
175
176
177 def run(self, evaluate, budget):
178 """Call evaluate(checkpoint) for one score per task and return counters."""
179 if not callable(evaluate):
180 raise TypeError("evaluate must be callable.")
181 budget = _positive_int(budget, "budget")
182 counts = [0] * len(self.archives)
183 experts = updates = outside = 0
184 for _ in range(budget):
185 if self._expert_index < len(self._experts):
186 model = self._experts[self._expert_index]
187 self._expert_index += 1
188 experts += 1
189 else:
190 task = self._order[self._offspring % len(self._order)]
191 archive = self.archives[task]
192 if not archive:
193 raise ValueError("At least one expert must score within all task domains.")
194 model = self._breed(archive)
195 self._offspring += 1
196 counts[task] += 1
197 self._evaluations += 1
198 scores = np.asarray(evaluate(tuple(array.copy() for array in model)), dtype=float)
199 if scores.shape != (len(self.archives),) or not np.isfinite(scores).all():
200 raise ValueError("Return one finite score per task.")
201 if np.any((scores < self._domain.lower) | (scores > self._domain.upper)):
202 outside += 1
203 continue
204 for task, (archive, axes) in enumerate(zip(self.archives, self._axes, strict=True)):
205 elite = Individual([self._evaluations], fitness=Fitness((scores[task],), weights=archive.fitness_weights),
206 features=Features(scores[list(axes)]))
207 elite._cycle_checkpoint = model
208 elite.scores["cycle_scores"] = tuple(scores)
209 updates += archive.add(elite) is not None
210 return CycleQDStats(budget, experts, updates, outside, tuple(counts))
Per-call CycleQD measurement and archive admission counts.
Definition cycle_qd.py:25
Rotate active task archives, merge parents, and reuse measured task scores.
Definition cycle_qd.py:65
checkpoint(self, elite)
Copy an elite checkpoint for loading or external evaluation.
Definition cycle_qd.py:158
run(self, evaluate, budget)
Measure experts and offspring sequentially under an additional checkpoint budget.
Definition cycle_qd.py:177
aggregate(self)
Merge the highest-scoring elite from each archive using softmax weights.
Definition cycle_qd.py:163
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405