66 """Maintain one Grid for each objective role and score every checkpoint on all tasks.
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.
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.
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,
93 n = len(domain.bounds)
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))
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.")
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)
118 raise ValueError(
"Provide at least one aligned expert checkpoint.")
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))
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)
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)
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()
142 if abs(denominator) <= 1e-8 * np.max(np.abs(coefficients)):
145 coefficients /= denominator
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.")
154 result.append(base + delta)
155 return _checkpoint(result, self.
_shapes)
159 """Return independent writable arrays in the original tensor order."""
160 return tuple(array.copy()
for array
in elite._cycle_checkpoint)
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)
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))
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")
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
193 raise ValueError(
"At least one expert must score within all task domains.")
194 model = self.
_breed(archive)
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)):
204 for task, (archive, axes)
in enumerate(zip(self.
archives, self.
_axes, strict=
True)):
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))