QDpy
Loading...
Searching...
No Matches
me_gide.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Guide categorical proposals with derivatives of a one-hot relaxation."""
6
7import numpy as np
8from scipy.special import entr, softmax
9
10from qdpy.base import registry
11from qdpy.containers import CVTGrid, Grid
12from .differentiable import GradientEvaluation, _gradient_basis
13from .modern import _FixedGeneration, _positive_int
14
15__all__ = ["MEGIDE"]
16
17
18def _flip_probabilities(deltas, entropy_fraction):
19 deltas = np.asarray(deltas, dtype=float)
20 uniform = np.full(len(deltas), 1. / len(deltas))
21 if entropy_fraction == 1:
22 return uniform
23 maxima = deltas == deltas.max()
24 target = entropy_fraction * np.log(len(deltas))
25 if target <= np.log(maxima.sum()):
26 return maxima / maxima.sum()
27
28 # Centre at the maximum and search log inverse temperature for stability.
29 costs = deltas.max() - deltas
30 positive = costs[costs > 0]
31 low = -np.log(positive.max()) - 40
32 high = -np.log(positive.min()) + 40
33 log_cost = np.log(positive)
34 logits = np.zeros_like(costs)
35 for _ in range(48):
36 middle = (low + high) / 2
37 logits[~maxima] = -np.exp(np.clip(log_cost + middle, -745, 700))
38 probabilities = softmax(logits)
39 if entr(probabilities).sum() > target:
40 low = middle
41 else:
42 high = middle
43 return probabilities
44
45
46
47@registry.register
49 """MAP-Elites with the Gradient-Informed Discrete Emitter.
50
51 Return a :class:`GradientEvaluation` for each integer candidate. Its
52 Jacobian has rows for the objective followed by the descriptors, and
53 columns for adjacent one-hot blocks of the configured category counts.
54 Each call supplies the exact discrete measurements and derivatives of
55 a caller-provided smooth relaxation at that one-hot point.
56
57 Derivatives are cached for retained elites, so use a fixed evaluator
58 throughout a run. The entropy is controlled separately for each
59 proposal. Like the paper's softmax, each current category is included
60 in its block and may yield an unchanged proposal.
61
62 :param container: Best-only single-objective Grid or CVTGrid.
63 :param budget: Number of candidate calls, including the initialization.
64 :param nvec: Sequence of positive category counts, with at least two alternatives
65 in one coordinate. Categories are zero-indexed.
66 :param batch_size: Number of candidates selected from a frozen repertoire.
67 :param entropy_fraction: Desired entropy as a fraction of uniform entropy.
68 :param seed: Optional seed for initialization, parent sampling and edits.
69 """
70
71 _requires_proposed_genome = True
72
73 def __init__(self, container, budget, nvec, batch_size=32, *, entropy_fraction=.5, seed=None, **kwargs):
74 if type(container) not in (Grid, CVTGrid) or container.max_items_per_bin != 1 or len(container.fitness_domain) != 1:
75 raise ValueError("MEGIDE requires a best-only single-objective Grid or CVTGrid.")
76 self.nvec = tuple(_positive_int(n, "category count") for n in nvec)
77 if not self.nvec or max(self.nvec) < 2 or not 0 <= entropy_fraction <= 1:
78 raise ValueError("Use a mutable categorical genome and entropy_fraction in [0, 1].")
79 self.entropy_fraction, self.seed = entropy_fraction, seed
80 self._offsets = np.cumsum((0, *self.nvec))
81 self._blocks = np.repeat(np.arange(len(self.nvec)), self.nvec)
82 self._bases = {}
83 kwargs.setdefault("optimisation_task", container.fitness_weights)
84 super().__init__(container, _positive_int(budget, "budget"),
85 batch_size=_positive_int(batch_size, "batch_size"),
86 dimension=len(self.nvec), **kwargs)
87
88 def reinit(self):
89 """Reset accounting and proposals while preserving live elite gradients."""
90 super().reinit()
91 self._rng = np.random.default_rng(self.seed)
92 self._new_bases = {}
93 self._parents = ()
94
95 def _start_fixed_batch(self, size):
96 super()._start_fixed_batch(size)
97 self._bases = {id(ind): self._bases[id(ind)] for ind in self.container if id(ind) in self._bases}
98 self._parents = tuple(self._bases.values())
99
100 def _clear_generation(self):
101 super()._clear_generation()
102 self._new_bases.clear()
103 self._parents = ()
104
105 def _internal_ask(self, base_ind):
106 if not self._parents:
107 base_ind[:] = self._rng.integers(self.nvec).tolist()
108 return base_ind
109 entry, basis = self._parents[self._rng.integers(len(self._parents))]
110 parent = tuple(entry)
111 weights = self._rng.normal(size=basis.shape[0])
112 weights[0] = abs(weights[0])
113 gradient = weights @ basis
114 deltas = gradient - gradient[self._offsets[:-1] + parent][self._blocks]
115 edit = self._rng.choice(len(deltas), p=_flip_probabilities(deltas, self.entropy_fraction))
116 block = self._blocks[edit]
117 base_ind[:] = parent
118 base_ind[block] = int(edit - self._offsets[block])
119 return base_ind
120
121 def _tell_evaluation_result(self, individual, result, elapsed, verbose):
122 if not isinstance(result, GradientEvaluation):
123 raise TypeError("The MEGIDE evaluator must return a GradientEvaluation.")
124 descriptors = np.asarray(result.descriptors, dtype=float)
125 count = len(self.container.features_domain)
126 jacobian = np.asarray(result.jacobian, dtype=float)
127 if (descriptors.shape != (count,) or not np.isfinite(descriptors).all()
128 or jacobian.shape != (count + 1, self._offsets[-1]) or not np.isfinite(jacobian).all()):
129 raise ValueError("MEGIDE requires finite descriptors and one Jacobian column per category.")
130 self.tell(individual, fitness=(float(result.fitness),), features=tuple(descriptors),
131 elapsed=elapsed, verbose=verbose)
132 self._new_bases[id(individual)] = _gradient_basis(jacobian, self._fitness_weights[0])
133 return True
134
135 def _commit_generation(self, evaluated):
136 offered = {}
137 for slot, individual in enumerate(evaluated):
138 if individual is None:
139 continue
140 cell = self.container.index_grid(individual)
141 if self._offer_to_grid(individual, cell):
142 offered[id(individual)] = slot
143 admitted = set()
144 for individual in self.container:
145 identifier = id(individual)
146 if identifier in offered:
147 self._bases[identifier] = (individual, self._new_bases[identifier])
148 admitted.add(offered[identifier])
149 self._bases = {id(ind): self._bases[id(ind)] for ind in self.container if id(ind) in self._bases}
150 return admitted
Search a categorical genome with entropy-controlled, gradient-informed edits.
Definition me_gide.py:48
_commit_generation(self, evaluated)
Definition me_gide.py:135
_internal_ask(self, base_ind)
Definition me_gide.py:105
_offer_to_grid(self, individual, cell)
Definition modern.py:228