QDpy
Loading...
Searching...
No Matches
set_scalarization.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Smooth Sum-of-Minimum and Smooth Tchebycheff Set optimization."""
7
8from dataclasses import dataclass
9from math import isfinite
10from operator import index
11
12import numpy as np
13from scipy.special import logsumexp
14
15from qdpy.containers import Grid
16from qdpy.phenotype import Features, Fitness, Individual
17from .differentiable import GradientEvaluation
18from .task_search import _measure, _offer, _search_bounds, _validate_grid
19
20__all__ = ["SetScalarizationResult", "set_scalarized_search"]
21
22
23
24@dataclass(frozen=True)
26 """Report the measured final set and unsmoothed minimum cost at each target.
27
28 The objective is the final smooth loss and is minimized. Target
29 costs retain probe order and are negative discounted qualities.
30 A reporting archive, if supplied, contains the final set's elites.
31 """
32
33 population: tuple[Individual, ...]
34 archive: Grid | None
35 evaluations: int
36 objective: float
37 target_costs: tuple[float, ...]
38
39
40def _target_cost(qualities, descriptors, targets, bandwidth):
41 with np.errstate(over="ignore"):
42 offsets = (descriptors[:, None, :] - targets) / bandwidth
43 kernel = np.exp(-np.square(offsets).sum(axis=-1))
44 return -qualities[:, None] * kernel, kernel, offsets
45
46
47def _scalarize(costs, smoothing, reference):
48 """Return the smooth loss and its derivatives with respect to probe costs."""
49 minimum = costs.min(axis=0)
50 with np.errstate(over="ignore"):
51 logits = (minimum - costs) / smoothing
52 normalizer = logsumexp(logits, axis=0)
53 soft_min = minimum - smoothing * normalizer
54 within = np.exp(logits - normalizer)
55 if reference is None:
56 return soft_min.sum(), within
57 shortfall = soft_min - reference
58 worst = shortfall.max()
59 logits = (shortfall - worst) / smoothing
60 normalizer = logsumexp(logits)
61 return worst + smoothing * normalizer, within * np.exp(logits - normalizer)
62
63
64
66def set_scalarized_search(gradient_evaluate, initial_population, targets, *, epochs, bandwidth,
67 smoothing=.05, scalarization="ssom", reference=None, quality_floor=0.,
68 learning_rate=.02, ind_domain=(0., 1.), maximize=True, archive=None):
69 """Use projected Adam on the SSoM or STCH-Set objective from Lin et al.
70
71 :param gradient_evaluate: Callback returning one GradientEvaluation per point.
72 :param initial_population: Nonempty matrix of bounded genomes.
73 :param targets: Nonempty matrix of desired descriptors in measurement units.
74 :param epochs: Full-population updates after the initial measurements.
75 :param bandwidth: Gaussian distance scale in descriptor units.
76 :param smoothing: Positive log-sum-exp temperature in quality units.
77 :param scalarization: "ssom" or "stch-set".
78 :param reference: Fixed target-wise ideal costs for STCH-Set. If omitted,
79 use each target's initial best cost minus smoothing.
80 :param quality_floor: Lower bound in signed fitness units. Shifted qualities
81 must be nonnegative for distance discounting.
82 :param learning_rate: Projected Adam step in genome units.
83 :param ind_domain: Inclusive common genome interval.
84 :param maximize: Use higher raw fitness as better if true.
85 :param archive: Optional empty best-only Grid or CVTGrid for final reporting.
86 """
87 if not callable(gradient_evaluate):
88 raise TypeError("Supply a gradient evaluator.")
89 epochs = index(epochs)
90 bounds = _search_bounds(ind_domain)
91 population = np.array(initial_population, dtype=float, copy=True)
92 targets = np.asarray(targets, dtype=float)
93 if (population.ndim != 2 or not all(population.shape) or not np.isfinite(population).all()
94 or not np.all((bounds[0] <= population) & (population <= bounds[1]))
95 or targets.ndim != 2 or not all(targets.shape) or not np.isfinite(targets).all()):
96 raise ValueError("Supply nonempty finite matrices of bounded genomes and behavior targets.")
97 if (epochs < 0 or not isfinite(quality_floor)
98 or not all(isfinite(value) and value > 0 for value in (bandwidth, smoothing, learning_rate))):
99 raise ValueError("Use nonnegative epochs, a finite quality floor, and finite positive optimizer scales.")
100 if scalarization not in ("ssom", "stch-set") or (reference is not None and scalarization != "stch-set"):
101 raise ValueError("Choose ssom or stch-set. Only stch-set takes a target reference.")
102 if reference is not None:
103 reference = np.asarray(reference, dtype=float)
104 if reference.shape != (len(targets),) or not np.isfinite(reference).all():
105 raise ValueError("Supply one finite reference cost per behavior target.")
106 direction = 1. if maximize else -1.
107 if archive is not None:
108 _validate_grid(archive)
109 if (len(archive.features_domain) != targets.shape[1]
110 or (archive.fitness_weights is not None and np.sign(archive.fitness_weights[0]) != direction)):
111 raise ValueError("Reporting archive descriptors and fitness direction must match the evaluator.")
112
113 def measure(genome):
114 result = gradient_evaluate(tuple(genome))
115 if not isinstance(result, GradientEvaluation):
116 raise TypeError("The evaluator must return a GradientEvaluation.")
117 fitness = float(result.fitness)
118 descriptor = np.asarray(result.descriptors, dtype=float)
119 jacobian = np.asarray(result.jacobian, dtype=float)
120 quality = direction * fitness - quality_floor
121 if (not isfinite(quality) or quality < 0 or descriptor.shape != (targets.shape[1],)
122 or jacobian.shape != (1 + targets.shape[1], population.shape[1])
123 or not np.isfinite(descriptor).all() or not np.isfinite(jacobian).all()):
124 raise ValueError("Expected nonnegative shifted fitness and finite descriptors with a matching Jacobian.")
125 return fitness, quality, descriptor.copy(), jacobian.copy()
126
127 first, second = np.zeros_like(population), np.zeros_like(population)
128 for epoch in range(epochs + 1):
129 raw, quality, descriptors, jacobians = map(np.array, zip(*(measure(genome) for genome in population)))
130 costs, kernel, offsets = _target_cost(quality, descriptors, targets, bandwidth)
131 if reference is None and scalarization == "stch-set":
132 reference = costs.min(axis=0) - smoothing
133 objective, weights = _scalarize(costs, smoothing, reference)
134 if not isfinite(objective):
135 raise FloatingPointError("The set objective overflowed. Rescale fitness or the reference.")
136 if epoch == epochs:
137 break
138 fitness_gradient = -direction * (weights * kernel).sum(axis=1)
139 offsets = np.where(kernel[..., None] > 0., offsets, 0.)
140 descriptor_gradient = -2. * np.einsum("pm,pmd->pd", weights * costs, offsets) / bandwidth
141 gradient = np.einsum("pr,prd->pd", np.column_stack((fitness_gradient, descriptor_gradient)), jacobians)
142 first = .9 * first + .1 * gradient
143 second = .999 * second + .001 * np.square(gradient)
144 proposal = population - learning_rate * (first / (1. - .9 ** (epoch + 1))) / (
145 np.sqrt(second / (1. - .999 ** (epoch + 1))) + 1e-8)
146 if not np.isfinite(second).all() or not np.isfinite(proposal).all():
147 raise FloatingPointError("The set gradient update overflowed. Rescale fitness or descriptors.")
148 population = np.clip(proposal, *bounds)
149
150 result = tuple(Individual(genome, fitness=Fitness((value,), weights=(direction,)),
151 features=Features(tuple(features)))
152 for genome, value, features in zip(population, raw, descriptors))
153 if archive is not None:
154 if archive.fitness_weights is None:
155 archive._set_fitness_weights((direction,))
156 for individual in result:
157 measurement = _measure(archive, lambda: (tuple(individual.fitness), tuple(individual.features)),
158 (), individual)
159 if measurement is not None:
160 _offer(archive, measurement)
161 return SetScalarizationResult(result, archive, len(result) * (epochs + 1), float(objective),
162 tuple(costs.min(axis=0)))
Final repertoire and per-target costs, with exact evaluator accounting.
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405