QDpy
Loading...
Searching...
No Matches
qqd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Choose one local-search operator per candidate using QQD's cyclic Q-table."""
7
8from collections.abc import Mapping
9from dataclasses import dataclass
10from math import isfinite
11
12import numpy as np
13
14from qdpy.containers import Grid
15from qdpy.phenotype import Features, Fitness, Individual
16from ._population import _attempt_budget, _finite_vector
17from .modern import _positive_int
18
19__all__ = ["QQD", "QQDStats"]
20
21
22
23@dataclass(frozen=True)
25 """Count failed evaluations, archive admissions, and operator attempts."""
26
27 evaluations: int
28 failures: int
29 archive_updates: int
30 q_updates: int
31 operator_attempts: tuple[tuple[str, int], ...]
32
33
34
35class QQD:
36 """Run Qin et al.'s tabular operator selector with user-defined variation.
37
38 Select a parent uniformly from the archive and learn from admission
39 to its offspring's destination cell. A new cell yields one unit of
40 reward, improvement yields a scaled quality gain, and rejection
41 yields zero. The controller advances through batch positions
42 cyclically. Each operator call proposes one candidate.
43
44 :param archive: Parentless best-only Grid or CVTGrid with native scalar fitness.
45 :param sample: Callable (rng) returning a fresh genome.
46 :param operators: Ordered mapping of names to callbacks (genome, rng).
47 :param batch_size: Number of positions in the cyclic controller state.
48 :param initial_samples: Warm-up attempts, defaulting to batch_size.
49 :param controller: ``q-learning``, ``uniform``, or ``bandit``.
50 :param learning_rate: Initial Q-table step size in (0, 1].
51 :param discount: Bootstrapping coefficient in [0, 1].
52 :param epsilon: Initial exploration probability.
53 :param epsilon_decay: Multiplier applied after each local proposal.
54 :param anneal_batches: Optional batch count for annealing learning_rate toward .01.
55 :param improvement_scale: Positive denominator floor for relative improvement.
56 :param seed: Seed for selection, variation, and evaluator calls.
57 """
58
59 def __init__(self, archive, *, sample, operators, batch_size=16, initial_samples=None,
60 controller="q-learning", learning_rate=.5, discount=.9, epsilon=.3, epsilon_decay=.999,
61 anneal_batches=None, improvement_scale=1e-12, seed=0):
62 if (not isinstance(archive, Grid) or archive.parents or archive.max_items_per_bin != 1
63 or archive.discard_random_on_bin_overload or archive.fitness_score_names
64 or archive.features_score_names or len(archive.fitness_domain or ()) != 1
65 or len(archive.fitness_weights or ()) != 1 or not isfinite(archive.fitness_weights[0])
66 or not archive.fitness_weights[0]):
67 raise ValueError("Supply a parentless best-only grid with one signed native fitness.")
68 if (not callable(sample) or not isinstance(operators, Mapping) or not operators
69 or any(not isinstance(name, str) or not name or not callable(op) for name, op in operators.items())):
70 raise ValueError("Supply a sampler and a nonempty mapping of named local-search operators.")
71 if (controller not in ("q-learning", "uniform", "bandit") or not 0 < learning_rate <= 1
72 or not 0 <= discount <= 1 or not 0 <= epsilon <= 1 or not 0 < epsilon_decay <= 1
73 or not 0 < improvement_scale < np.inf):
74 raise ValueError("Use valid controller settings and positive finite improvement_scale.")
75 self.archive, self._sample, self._controller = archive, sample, controller
76 self._names, self._operators = tuple(operators), tuple(operators.values())
77 self._size = _positive_int(batch_size, "batch_size")
78 self._warmup = self._size if initial_samples is None else _attempt_budget(initial_samples)
79 self._anneal = None if anneal_batches is None else _positive_int(anneal_batches, "anneal_batches")
80 self._learning_rate, self._floor = learning_rate, min(learning_rate, .01)
81 self._discount, self._epsilon, self._decay, self._scale = discount, epsilon, epsilon_decay, improvement_scale
82 self._choice, self._variation, self._evaluation = map(
83 np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
84 self._values = np.zeros((self._size, len(self._names)))
85 self._attempts = np.zeros(len(self._names), dtype=int)
86 self._totals = np.zeros(len(self._names))
87 self._evaluations = self._failures = self._updates = self._learned = self._local = 0
88
89 @property
90 def q_values(self):
91 """Return a copy of the table in batch position and operator order."""
92 return self._values.copy()
93
94 @property
95 def stats(self):
96 """Return cumulative work and operator counts."""
97 return QQDStats(self._evaluations, self._failures, self._updates, self._learned,
98 tuple(zip(self._names, map(int, self._attempts))))
99
100 def _action(self, state):
101 if self._controller == "uniform":
102 return int(self._choice.integers(len(self._names)))
103 if self._controller == "q-learning":
104 if self._choice.random() < self._epsilon:
105 return int(self._choice.integers(len(self._names)))
106 scores = self._values[state]
107 else:
108 unseen = np.flatnonzero(self._attempts == 0)
109 if len(unseen):
110 return int(self._choice.choice(unseen))
111 scores = self._totals / self._attempts + np.sqrt(2. * np.log(self._local) / self._attempts)
112 return int(self._choice.choice(np.flatnonzero(scores == scores.max())))
113
114 def _offer(self, genome, result):
115 if result is None:
116 self._failures += 1
117 return 0.
118 quality, features = result
119 descriptor = _finite_vector(features, "Behavior descriptor", len(self.archive.features_domain))
120 quality = float(quality)
121 if not isfinite(quality):
122 raise ValueError("Fitness must be finite.")
123 grid = self.archive
124 if not grid.in_bounds((quality,), grid.fitness_domain) or not grid.in_bounds(descriptor, grid.features_domain):
125 return 0.
126 occupants = grid.solutions[grid.index_grid(descriptor)]
127 previous = grid.get_ind_fitness(occupants[0]).values[0] if occupants else None
128 before = grid.nb_added
129 grid.add(Individual(genome, fitness=Fitness((quality,), weights=grid.fitness_weights),
130 features=Features(descriptor)))
131 if grid.nb_added == before:
132 return 0.
133 self._updates += 1
134 if previous is None:
135 return 1.
136 scale = max(abs(previous), abs(quality), self._scale)
137 difference = abs(previous / scale - quality / scale)
138 denominator = max(abs(previous), self._scale) / scale
139 return 1. if difference >= denominator else difference / denominator
140
141
145 def run(self, evaluate, budget):
146 """Use the same next batch position when the search is continued."""
147 for _ in range(_attempt_budget(budget)):
148 action = None
149 state = self._local % self._size
150 if self._evaluations < self._warmup or not self.archive:
151 genome = tuple(self._sample(self._variation))
152 else:
153 parent = tuple(self.archive[int(self._choice.integers(len(self.archive)))])
154 action = self._action(state)
155 genome = tuple(self._operators[action](parent, self._variation))
156 self._attempts[action] += 1
157 self._evaluations += 1
158 reward = self._offer(genome, evaluate(genome, int(self._evaluation.integers(2**32))))
159 if action is None:
160 continue
161 self._totals[action] += reward
162 if self._controller == "q-learning":
163 successor = (state + 1) % self._size
164 expected = reward + self._discount * float(self._values[successor].max())
165 previous = self._values[state, action]
166 self._values[state, action] += self._learning_rate * (expected - previous)
167 self._epsilon *= self._decay
168 self._learned += 1
169 if self._anneal is not None:
170 progress = min((self._local // self._size + 1) / self._anneal, 1.)
171 self._learning_rate -= (self._learning_rate - self._floor) * progress
172 self._local += 1
173 return self.stats
Candidate and operator accounting for a QQD search.
Definition qqd.py:24
Select named local-search operators using one Q-table row per batch position.
Definition qqd.py:35
run(self, evaluate, budget)
Continue MAP-Elites and update the tabular controller in evaluation order.
Definition qqd.py:145
_action(self, state)
Definition qqd.py:100
_offer(self, genome, result)
Definition qqd.py:114
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405