QDpy
Loading...
Searching...
No Matches
squad.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""NumPy implementation of Soft QD Using Approximated Diversity."""
6
7from dataclasses import dataclass
8from math import isfinite
9from operator import index
10
11import numpy as np
12from scipy.spatial.distance import cdist
13
14from qdpy.containers import Grid
15from qdpy.phenotype import Features, Fitness, Individual
16from .differentiable import GradientEvaluation
17from .modern import _positive_int
18from .task_search import _measure, _offer, _search_bounds, _validate_grid
19
20__all__ = ["SQUADResult", "squad_search", "soft_qd_score"]
21
22
23
24@dataclass(frozen=True)
26 """The raw measurements, evaluation count and optimizer objective."""
27
28 population: tuple[Individual, ...]
29 archive: Grid | None
30 evaluations: int
31 objective: float
32
33
34
35def soft_qd_score(qualities, descriptors, probes, *, sigma):
36 """Average the highest Gaussian-discounted quality at each probe.
37
38 Provide nonnegative qualities, one descriptor per solution, and a
39 nonempty matrix of probe descriptors. For uniform probes in a box,
40 multiplying by its volume estimates the integral over that box.
41 """
42 qualities, descriptors, probes = (np.asarray(values, dtype=float)
43 for values in (qualities, descriptors, probes))
44 if (qualities.ndim != 1 or descriptors.ndim != 2 or probes.ndim != 2
45 or len(qualities) != len(descriptors) or not len(probes)
46 or not probes.shape[1] or descriptors.shape[1] != probes.shape[1]
47 or any(not np.isfinite(array).all() for array in (qualities, descriptors, probes))
48 or np.any(qualities < 0) or not isfinite(sigma) or sigma <= 0):
49 raise ValueError("Supply finite aligned solutions and probes, nonnegative qualities, and positive sigma.")
50 if not len(qualities):
51 return 0.
52 with np.errstate(over="ignore"):
53 distances = cdist(probes, descriptors) / sigma
54 return float(np.mean(np.max(np.exp(-0.5 * distances ** 2) * qualities, axis=1)))
55
56
57def _batch_objective(quality, descriptors, rows, neighbors, gamma):
58 """Return the directed minibatch objective and its derivatives for all rows."""
59 gradient = np.zeros((len(quality), 1 + descriptors.shape[1]))
60 gradient[rows, 0] = 1.
61 value = quality[rows].sum()
62 if neighbors == 0:
63 return value, gradient
64
65 distances = cdist(descriptors[rows], descriptors, metric="sqeuclidean")
66 distances[np.arange(len(rows)), rows] = np.inf
67 adjacent = np.argsort(distances, axis=1, kind="stable")[:, :neighbors]
68 left, right = np.repeat(rows, neighbors), adjacent.ravel()
69 with np.errstate(over="ignore"):
70 diff = (descriptors[left] - descriptors[right]) / gamma
71 kernel = np.exp(-np.sum(diff * diff, axis=1))
72 weight = 0.5 * np.sqrt(quality[left]) * np.sqrt(quality[right]) * kernel
73 value -= weight.sum()
74 np.add.at(gradient[:, 0], left, -0.5 * weight / quality[left])
75 np.add.at(gradient[:, 0], right, -0.5 * weight / quality[right])
76 # At an underflowed kernel value, the representable repulsion is zero.
77 repulsion = (2. * weight[:, None] * np.where(kernel[:, None] > 0., diff, 0.)) / gamma
78 np.add.at(gradient[:, 1:], left, repulsion)
79 np.add.at(gradient[:, 1:], right, -repulsion)
80 return value, gradient
81
82
83
84def squad_search(gradient_evaluate, initial_population, *, epochs, gamma, quality_floor,
85 ind_domain=(0., 1.), batch_size=None, neighbors=None,
86 learning_rate=0.02, maximize=True, archive=None, seed=0):
87 """Maximize the SQUAD objective with seeded minibatch Adam updates.
88
89 :param gradient_evaluate: Callable returning a GradientEvaluation for
90 one genome. Its Jacobian rows match raw fitness and descriptor order.
91 :param initial_population: Matrix of finite bounded genomes.
92 :param epochs: Number of complete passes after the initial evaluations.
93 Every pass reevaluates each updated point once.
94 :param gamma: Positive distance scale in descriptor units.
95 :param quality_floor: Lower bound in signed fitness units. Each signed
96 fitness must strictly exceed it for the square-root gradient.
97 :param ind_domain: Common bounds. Adam proposals are projected to this interval.
98 :param batch_size: Number of points per update. Defaults to the entire population.
99 :param neighbors: Maximum nearest neighbors per point. Defaults to all other
100 points. Zero gives independent quality optimization.
101 :param learning_rate: Positive Adam step size.
102 :param maximize: False negates raw fitness and its derivative.
103 :param archive: Optional empty best-only Grid or CVTGrid for final reporting.
104 :param seed: Local seed for minibatch order.
105 :returns: Measured final population and optional reporting archive.
106 """
107 if not callable(gradient_evaluate):
108 raise TypeError("Supply a gradient evaluator.")
109 epochs = index(epochs)
110 bounds = _search_bounds(ind_domain)
111 population = np.array(initial_population, dtype=float, copy=True)
112 if (population.ndim != 2 or not all(population.shape) or not np.isfinite(population).all()
113 or np.any(population < bounds[0]) or np.any(population > bounds[1])):
114 raise ValueError("Supply a nonempty matrix of finite genomes inside ind_domain.")
115 if (epochs < 0 or not isfinite(quality_floor) or not isfinite(gamma) or gamma <= 0
116 or not isfinite(learning_rate) or learning_rate <= 0):
117 raise ValueError("Use nonnegative epochs, a finite quality floor, and positive gamma and learning rate.")
118 count, dimension = population.shape
119 size = count if batch_size is None else min(count, _positive_int(batch_size, "batch_size"))
120 neighbors = count - 1 if neighbors is None else index(neighbors)
121 if not 0 <= neighbors < count:
122 raise ValueError("neighbors must be between zero and the population size minus one.")
123 direction = 1. if maximize else -1.
124 if archive is not None:
125 _validate_grid(archive)
126 if archive.fitness_weights is not None and np.sign(archive.fitness_weights[0]) != direction:
127 raise ValueError("The reporting grid and optimizer must use the same fitness direction.")
128
129 def measure(genome, descriptor_size=None):
130 result = gradient_evaluate(tuple(genome))
131 if not isinstance(result, GradientEvaluation):
132 raise TypeError("SQUAD requires a GradientEvaluation.")
133 quality = direction * float(result.fitness) - quality_floor
134 descriptors = np.asarray(result.descriptors, dtype=float)
135 jacobian = np.array(result.jacobian, dtype=float, copy=True)
136 if (not isfinite(quality) or quality <= 0 or descriptors.ndim != 1 or not descriptors.size
137 or (descriptor_size is not None and descriptors.size != descriptor_size)
138 or jacobian.shape != (descriptors.size + 1, dimension)
139 or not np.isfinite(descriptors).all() or not np.isfinite(jacobian).all()):
140 raise ValueError("SQUAD needs positive shifted fitness, finite descriptors, and a matching finite Jacobian.")
141 jacobian[0] *= direction
142 return float(result.fitness), quality, descriptors.copy(), jacobian
143
144 measured = [measure(population[0])]
145 width = measured[0][2].size
146 measured.extend(measure(genome, width) for genome in population[1:])
147 raw, quality, descriptors, jacobians = map(np.array, zip(*measured))
148 if archive is not None and len(archive.features_domain) != width:
149 raise ValueError("Descriptor size must match the reporting grid.")
150 first, second = np.zeros_like(population), np.zeros_like(population)
151 rng = np.random.default_rng(seed)
152 for epoch in range(1, epochs + 1):
153 order = np.arange(count) if size == count else rng.permutation(count)
154 for start in range(0, count, size):
155 rows = order[start:start + size]
156 _, gradient = _batch_objective(quality, descriptors, rows, neighbors, gamma)
157 update = np.einsum("br,brd->bd", gradient[rows], jacobians[rows])
158 mean = 0.9 * first[rows] + 0.1 * update
159 moment = 0.999 * second[rows] + 0.001 * update ** 2
160 new = population[rows] + learning_rate * (mean / (1 - 0.9 ** epoch)) / (
161 np.sqrt(moment / (1 - 0.999 ** epoch)) + 1e-8)
162 if not np.isfinite(moment).all() or not np.isfinite(new).all():
163 raise FloatingPointError("The SQUAD update overflowed. Rescale the objective or descriptors.")
164 new = np.clip(new, *bounds)
165 measurements = [measure(genome, width) for genome in new]
166 raw[rows], quality[rows], descriptors[rows], jacobians[rows] = map(np.array, zip(*measurements))
167 population[rows], first[rows], second[rows] = new, mean, moment
168
169 objective, _ = _batch_objective(quality, descriptors, np.arange(count), neighbors, gamma)
170 result = tuple(Individual(genome, fitness=Fitness((value,), weights=(direction,)),
171 features=Features(tuple(features)))
172 for genome, value, features in zip(population, raw, descriptors))
173 if archive is not None:
174 if archive.fitness_weights is None:
175 archive._set_fitness_weights((direction,))
176 for individual in result:
177 measurement = _measure(archive, lambda: (tuple(individual.fitness), tuple(individual.features)),
178 (), individual)
179 if measurement is not None:
180 _offer(archive, measurement)
181 return SQUADResult(result, archive, count * (epochs + 1), float(objective))
Final evaluated population and optional reporting grid.
Definition squad.py:25
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405