QDpy
Loading...
Searching...
No Matches
discount.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Learn a smooth discount field over a fixed reporting archive."""
6
7from math import sqrt
8
9import numpy as np
10
11from qdpy.base import registry
12from qdpy.containers import CVTGrid, Grid
13from .modern import CMAMAE, _positive_int
14
15__all__ = ["DiscountModelSearch"]
16
17# Leave headroom for squared losses and Adam's second moments in float32.
18_MAX_DISCOUNT_TARGET = sqrt(np.finfo(np.float32).max) / 128
19
20
21def _check_discount_targets(values):
22 if not np.all(np.abs(np.asarray(values, dtype=float)) <= _MAX_DISCOUNT_TARGET):
23 raise ValueError(f"DMS signed quality must be within ±{_MAX_DISCOUNT_TARGET:.2g}. "
24 "Rescale the objective or its weight.")
25
26
27def _discount_targets(previous, qualities, learning_rate):
28 return previous + learning_rate * np.maximum(qualities - previous, 0)
29
30
32 """Fit the vector-descriptor MLP and preserve Adam and sampler state."""
33
34 def __init__(self, dimension, seed):
35 import torch
36
37 with torch.random.fork_rng(devices=[]):
38 torch.random.default_generator.manual_seed(seed)
39 cpu = dict(device="cpu", dtype=torch.float32)
40 self.network = torch.nn.Sequential(
41 torch.nn.Linear(dimension, 128, **cpu),
42 torch.nn.ReLU(),
43 torch.nn.Linear(128, 128, **cpu),
44 torch.nn.ReLU(),
45 torch.nn.Linear(128, 1, **cpu),
46 )
47 self.optimizer = torch.optim.Adam(self.network.parameters(), lr=0.001)
48 self.generator = torch.Generator(device="cpu").manual_seed(seed)
49
50 def predict(self, descriptors):
51 import torch
52
53 points = torch.as_tensor(descriptors, dtype=torch.float32, device="cpu")
54 if not torch.isfinite(points).all():
55 raise ValueError("Normalised descriptors are outside the DMS model's finite range.")
56 with torch.no_grad():
57 return self.network(points).squeeze(-1).numpy()
58
59 def fit(self, descriptors, targets):
60 import torch
61
62 _check_discount_targets(targets)
63 points = torch.as_tensor(descriptors, dtype=torch.float32, device="cpu")
64 targets = torch.as_tensor(targets, dtype=torch.float32, device="cpu")
65 for _ in range(5):
66 for indices in torch.randperm(len(points), generator=self.generator, device="cpu").split(32):
67 self.optimizer.zero_grad()
68 loss = torch.nn.functional.mse_loss(self.network(points[indices]).squeeze(-1), targets[indices])
69 if not torch.isfinite(loss):
70 raise ValueError("DMS training loss is nonfinite. Rescale the objective or its weight.")
71 loss.backward()
72 self.optimizer.step()
73 with torch.no_grad():
74 mse = torch.nn.functional.mse_loss(self.network(points).squeeze(-1), targets)
75 if mse <= 0.05:
76 break
77
78
79
80@registry.register
82 """Native DMS with one CMA emitter and a CPU vector-descriptor model.
83
84 Install the optional ``dms`` extra. The fixed Grid or CVTGrid retains each
85 cell's best genuine evaluation. The MLP predicts a separate discount
86 in signed quality units and trains once per committed generation.
87
88 :param container: One-elite reporting grid.
89 :param budget: Attempted evaluations per run.
90 :param x0: Initial decision point.
91 :param sigma0: Initial CMA search scale.
92 :param batch_size: Full CMA population size.
93 :param threshold_min: Initial discount in signed quality units within the model's numeric range.
94 :param learning_rate: Archive target learning rate.
95 :param initial_anchors: Maximum sampled centres for model initialisation.
96 :param empty_anchors: Maximum sampled empty centres per generation.
97 """
98
99 def __init__(self, container, budget, x0, sigma0, batch_size, threshold_min, *,
100 learning_rate=0.1, initial_anchors=256, empty_anchors=256, **kwargs):
101 try:
102 import torch
103 except ImportError as error:
104 raise ImportError("DiscountModelSearch requires the QDpy 'dms' extra.") from error
105 if type(container) not in (Grid, CVTGrid):
106 raise ValueError("DMS requires a fixed Grid or CVTGrid.")
107 _check_discount_targets(threshold_min)
108 lower, upper = np.asarray(container.features_domain, dtype=float).T
109 widths = [float(high) - float(low) for low, high in zip(lower, upper)]
110 if not np.all(np.isfinite(widths)) or np.any(lower >= upper):
111 raise ValueError("DMS needs finite increasing descriptor bounds.")
112 self._descriptor_lower = lower
113 self._descriptor_width = np.asarray(widths)
114 self._cells = tuple(container.solutions)
115 if isinstance(container, CVTGrid):
116 self._centres = np.array(container.cluster_centers, copy=True)
117 else:
118 offsets = (np.asarray(self._cells) + 0.5) / np.asarray(container.shape)
119 self._centres = lower + offsets * self._descriptor_width
120 self._cell_rows = {cell: row for row, cell in enumerate(self._cells)}
121 self.initial_anchors = _positive_int(initial_anchors, "initial_anchors")
122 self.empty_anchors = _positive_int(empty_anchors, "empty_anchors")
123 super().__init__(container, budget, x0, sigma0, batch_size, threshold_min,
124 learning_rate=learning_rate, **kwargs)
125
126 def reinit(self):
127 """Reset the discount model and emitter while retaining the result archive."""
128 super().reinit()
129 self._discount_model = None
130
131 @property
132 def search_elites(self):
133 """Return the result-grid elites that can seed a restart."""
134 return {cell: entries[0] for cell, entries in self.container.solutions.items() if entries}
135
136 def _restart_center(self):
137 return self._search_rng().choice(self.container) if len(self.container) else self.x0
138
139 def _normalise(self, points):
140 return 2 * ((points - self._descriptor_lower) / self._descriptor_width) - 1
141
142 def _anchor_points(self, rows, count):
143 selected = self._search_rng().sample(rows, min(len(rows), count))
144 return self._centres[selected]
145
146 def _start_fixed_batch(self, size):
147 if self._discount_model is None:
148 seed = self._search_rng().randint(1, 2**32 - 1)
149 self._discount_model = _TorchDiscount(len(self._descriptor_lower), seed)
150 anchors = self._anchor_points(range(len(self._cells)), self.initial_anchors)
151 self._discount_model.fit(self._normalise(anchors), np.full(len(anchors), self.threshold_min))
152 super()._start_fixed_batch(size)
153
154
155 def predict_discount(self, descriptors):
156 """Return one signed discount per row after the model has been initialised."""
157 if self._discount_model is None:
158 raise RuntimeError("Start DMS before querying its discount model.")
159 points = np.atleast_2d(np.asarray(descriptors, dtype=float))
160 if points.ndim != 2 or points.shape[1] != len(self._descriptor_lower) or not np.all(np.isfinite(points)):
161 raise ValueError("Provide a finite matrix with one column per descriptor.")
162 return self._discount_model.predict(self._normalise(points))
163
164 def threshold(self, cell):
165 """Return the discount at a cell centre, or the initial floor before training."""
166 row = self._cell_rows[cell]
167 if self._discount_model is None:
168 return self.threshold_min
169 return float(self.predict_discount(self._centres[row])[0])
170
171 def _check_candidate(self, individual):
172 super()._check_candidate(individual)
173 fitness = self.container.get_ind_fitness(individual)
174 _check_discount_targets(float(fitness.values[0]) * float(fitness.weights[0]))
175
176 def _commit_generation(self, evaluated):
177 self._gains = np.full(len(evaluated), -np.inf)
178 indices = [slot for slot, ind in enumerate(evaluated) if ind is not None]
179 if not indices:
180 return set()
181 candidates = [evaluated[slot] for slot in indices]
182 points = np.asarray([tuple(self.container.get_ind_features(ind)) for ind in candidates])
183 qualities = np.array([
184 fitness.values[0] * fitness.weights[0] for fitness in map(self.container.get_ind_fitness, candidates)
185 ])
186 predictions = self.predict_discount(points)
187 self._gains[indices] = qualities - predictions
188 targets = _discount_targets(predictions, qualities, self.learning_rate)
189
190 admitted = set()
191 for slot, individual in zip(indices, candidates):
192 if self._offer_to_grid(individual, self.container.index_grid(individual)):
193 admitted.add(slot)
194 if len(evaluated) == self.batch_size:
195 self._adapt_strategy(self._vectors)
196
197 empty = [row for row, cell in enumerate(self._cells) if not self.container.solutions[cell]]
198 anchors = self._anchor_points(empty, self.empty_anchors)
199 training_input = self._normalise(np.concatenate((points, anchors), axis=0))
200 training_target = np.concatenate((targets, np.full(len(anchors), self.threshold_min)))
201 self._discount_model.fit(training_input, training_target)
202 return admitted
Rank a CMA generation against a learned continuous discount.
Definition discount.py:81
predict_discount(self, descriptors)
Predict signed discount values at evaluated descriptor vectors.
Definition discount.py:155
Adapt a covariance matrix using annealed cell-level improvement.
Definition modern.py:343
_offer_to_grid(self, individual, cell)
Definition modern.py:228