32 """Fit the vector-descriptor MLP and preserve Adam and sampler state."""
34 def __init__(self, dimension, seed):
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),
43 torch.nn.Linear(128, 128, **cpu),
45 torch.nn.Linear(128, 1, **cpu),
48 self.
generator = torch.Generator(device=
"cpu").manual_seed(seed)
50 def predict(self, descriptors):
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.")
57 return self.
network(points).squeeze(-1).numpy()
59 def fit(self, descriptors, targets):
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")
66 for indices
in torch.randperm(len(points), generator=self.
generator, device=
"cpu").split(32):
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.")
74 mse = torch.nn.functional.mse_loss(self.
network(points).squeeze(-1), targets)
82 """Native DMS with one CMA emitter and a CPU vector-descriptor model.
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.
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.
99 def __init__(self, container, budget, x0, sigma0, batch_size, threshold_min, *,
100 learning_rate=0.1, initial_anchors=256, empty_anchors=256, **kwargs):
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.")
114 self.
_cells = tuple(container.solutions)
115 if isinstance(container, CVTGrid):
116 self.
_centres = np.array(container.cluster_centers, copy=
True)
118 offsets = (np.asarray(self.
_cells) + 0.5) / np.asarray(container.shape)
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)
127 """Reset the discount model and emitter while retaining the result archive."""
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}
136 def _restart_center(self):
139 def _normalise(self, points):
142 def _anchor_points(self, rows, count):
143 selected = self.
_search_rng().sample(rows, min(len(rows), count))
156 """Return one signed discount per row after the model has been initialised."""
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.")
165 """Return the discount at a cell centre, or the initial floor before training."""
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]))
177 self.
_gains = np.full(len(evaluated), -np.inf)
178 indices = [slot
for slot, ind
in enumerate(evaluated)
if ind
is not None]
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)
187 self.
_gains[indices] = qualities - predictions
188 targets = _discount_targets(predictions, qualities, self.
learning_rate)
191 for slot, individual
in zip(indices, candidates):
197 empty = [row
for row, cell
in enumerate(self.
_cells)
if not self.
container.solutions[cell]]
199 training_input = self.
_normalise(np.concatenate((points, anchors), axis=0))
200 training_target = np.concatenate((targets, np.full(len(anchors), self.
threshold_min)))