QDpy
Loading...
Searching...
No Matches
asymmetric_islands.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Asymmetric Island Model using black-box evaluations and fixed role layouts."""
7
8from collections import Counter
9from collections.abc import Mapping
10from dataclasses import dataclass
11
12import numpy as np
13from scipy.special import log_softmax, softmax
14
15from qdpy.phenotype import Features, Fitness, _CellIndividual
16from qdpy.tools import iso_line_dd
17
18from .modern import _positive_int, _variation_settings
19from .task_search import _validate_grid
20
21__all__ = ["AIM", "AIMStats", "AIMTeam"]
22
23
24
25@dataclass(frozen=True)
26class AIMTeam:
27 """Genomes and contributions follow the optimizer's role order."""
28
29 genomes: tuple[tuple[float, ...], ...]
30 fitness: float
31 contributions: tuple[float, ...]
32
33
34
35@dataclass(frozen=True)
37 """Return migrations spend island_evaluations. Exported roles spend team evaluations."""
38
39 generations: int = 0
40 island_evaluations: int = 0
41 team_evaluations: int = 0
42 failed_island_evaluations: int = 0
43 failed_team_evaluations: int = 0
44 migration_rounds: int = 0
45 returning_evaluations: int = 0
46 exported_roles: int = 0
47
48
49
50class AIM:
51 """Maintain one Grid or CVTGrid per class and one team population per task.
52
53 Each mainland team has exactly one member of every class. Island
54 search uses bounded numeric variation and caller-defined descriptors.
55 Mainlands use elitism, tournament selection and within-class crossover.
56 On migration rounds, remeasure the members of the best mainland teams
57 on their islands. Then allocate new island exports to mainland slots
58 using a role-specific softmax learned from measured contributions.
59
60 :param islands: Mapping of role names to distinct empty native grids
61 with one explicit signed fitness objective.
62 :param tasks: Ordered iterable of at least two distinct mainland task IDs.
63 :param role_sizes: Mapping from the same roles to their genome lengths.
64 :param role_bounds: Optional mapping of roles to finite genome bounds.
65 The default is [0, 1] for each role.
66 :param population_size: Maximum teams per mainland.
67 :param elite_size: Teams retained in each mainland before selecting new offspring.
68 :param island_offspring: Local search evaluations per role and generation.
69 :param migration_period: Mainland generations between migration rounds.
70 :param migrants_per_role: Island exports per role on each migration round.
71 Defaults to population_size minus elite_size.
72 :param allocation_rate: Positive learning rate for mainland allocation logits.
73 :param entropy: Nonnegative regularization toward spread-out task allocation.
74 :param iso_sigma: Independent Gaussian variation scale on islands.
75 :param line_sigma: Shared Iso+LineDD direction scale on islands.
76 :param seed: Root seed for proposal, crossover and migration streams.
77 """
78
79 def __init__(self, islands, tasks, *, role_sizes, role_bounds=None, population_size=8,
80 elite_size=2, island_offspring=4, migration_period=3, migrants_per_role=None,
81 allocation_rate=.1, entropy=.01, iso_sigma=.05, line_sigma=.2, seed=0):
82 if (not isinstance(islands, Mapping) or len(islands) < 2
83 or len({id(grid) for grid in islands.values()}) != len(islands)):
84 raise ValueError("Supply at least two role names with distinct island archives.")
85 if not isinstance(role_sizes, Mapping) or role_sizes.keys() != islands.keys():
86 raise ValueError("Supply a genome length for every island role.")
87 if role_bounds is not None and (not isinstance(role_bounds, Mapping) or role_bounds.keys() != islands.keys()):
88 raise ValueError("Supply bounds for every island role.")
89 if isinstance(tasks, (str, bytes)):
90 raise ValueError("Supply an ordered collection of task IDs.")
91 self.tasks = tuple(tasks)
92 if len(self.tasks) < 2 or len(set(self.tasks)) != len(self.tasks):
93 raise ValueError("Supply at least two distinct mainland tasks.")
94 for archive in islands.values():
95 _validate_grid(archive)
96 if not archive.fitness_weights or archive.fitness_score_names or archive.features_score_names:
97 raise ValueError("Use direct island fitness and descriptors with explicit objective weights.")
98
99 self.roles = tuple(islands)
100 self._islands = dict(islands)
101 self._sizes = tuple(_positive_int(role_sizes[r], "role size") for r in self.roles)
102 bounds = ((0., 1.) for _ in self.roles) if role_bounds is None else (role_bounds[r] for r in self.roles)
103 self._bounds = tuple(_variation_settings(interval, iso_sigma, line_sigma) for interval in bounds)
104 if not all(np.isfinite(high - low) for low, high in self._bounds):
105 raise ValueError("Genome bounds must have finite spans.")
106 self._population = _positive_int(population_size, "population_size")
107 self._elites = _positive_int(elite_size, "elite_size")
108 if self._elites >= self._population:
109 raise ValueError("elite_size must be smaller than population_size.")
110 self._local = _positive_int(island_offspring, "island_offspring")
111 self._period = _positive_int(migration_period, "migration_period")
112 available = self._population - self._elites
113 self._migrants = available if migrants_per_role is None else _positive_int(migrants_per_role,
114 "migrants_per_role")
115 if self._migrants > available * len(self.tasks):
116 raise ValueError("Exports per role must fit the available mainland slots.")
117 if not (0 < allocation_rate < np.inf and 0 <= entropy < np.inf):
118 raise ValueError("Use finite positive allocation_rate and finite nonnegative entropy.")
119 self._allocation_rate, self._entropy = allocation_rate, entropy
120 self._iso_sigma, self._line_sigma = iso_sigma, line_sigma
121 self._mainlands = {task: () for task in self.tasks}
122 self._logits = np.zeros((len(self.roles), len(self.tasks)))
123 self._counts = Counter()
124 self._local_rng, self._team_rng, self._migration_rng = (
125 np.random.default_rng(stream) for stream in np.random.SeedSequence(seed).spawn(3))
126
127 @property
128 def islands(self):
129 """Return a shallow copy mapping role names to live island archives."""
130 return self._islands.copy()
131
132 @property
134 """Return the measured teams for each task in descending fitness order."""
135 return self._mainlands.copy()
136
137 @property
139 """Return the current mainland selection probabilities for each island."""
140 return {role: dict(zip(self.tasks, map(float, values)))
141 for role, values in zip(self.roles, softmax(self._logits, axis=1))}
142
143 @property
144 def stats(self):
145 """Return cumulative attempted evaluation counts and migrations."""
146 return AIMStats(**self._counts)
147
148 def _elites_by_task(self):
149 return {task: self._mainlands[task][:self._elites] for task in self.tasks}
150
151 def _migration_due(self):
152 n = self._counts["generations"]
153 return n > 0 and n % self._period == 0
154
155 def _costs(self, retained, migrate):
156 incumbents = sum(map(len, retained.values()))
157 return (self._local * len(self.roles) + (incumbents * len(self.roles) if migrate else 0),
158 self._population * len(self.tasks) - incumbents)
159
160 @property
162 """Return the island and team budget needed for one further generation."""
163 return self._costs(self._elites_by_task(), self._migration_due())
164
165 def _sample_role(self, role_index, rng):
166 archive = self._islands[self.roles[role_index]]
167 if len(archive):
168 return tuple(archive[rng.integers(len(archive))])
169 return tuple(map(float, rng.uniform(*self._bounds[role_index], size=self._sizes[role_index])))
170
171 def _measure_role(self, evaluate, role, genome, *, returning=False):
172 self._counts["island_evaluations"] += 1
173 self._counts["returning_evaluations"] += returning
174 result = evaluate(role, genome)
175 if result is None:
176 self._counts["failed_island_evaluations"] += 1
177 return
178 archive = self._islands[role]
179 value, descriptor = (np.asarray(field, dtype=float) for field in result)
180 if (value.shape not in ((), (1,)) or not np.isfinite(value).all()
181 or descriptor.shape != (len(archive.features_domain),) or not np.isfinite(descriptor).all()):
182 raise ValueError("Island evaluations must supply finite scalar fitness and a matching descriptor.")
183 fitness, features = (float(value.item()),), tuple(map(float, descriptor))
184 if (archive.in_bounds(fitness, archive.fitness_domain)
185 and archive.in_bounds(features, archive.features_domain)):
186 cell = archive.index_grid(features)
187 if archive.solutions[cell] or archive.free >= 1:
188 archive.add(_CellIndividual(genome, cell, fitness=Fitness(fitness, weights=archive.fitness_weights),
189 features=Features(features)))
190
191 def _advance_islands(self, evaluate):
192 for i, role in enumerate(self.roles):
193 archive, rng = self._islands[role], self._local_rng
194 for _ in range(self._local):
195 first = self._sample_role(i, rng)
196 if len(archive):
197 second = self._sample_role(i, rng)
198 child = iso_line_dd(first, second, bounds=self._bounds[i], iso_sigma=self._iso_sigma,
199 line_sigma=self._line_sigma, rng=rng)
200 first = tuple(map(float, child))
201 self._measure_role(evaluate, role, first)
202
203 def _update_allocation(self):
204 estimates = [np.mean([team.contributions for team in teams], axis=0) if teams else None
205 for teams in self._mainlands.values()]
206 present = [estimate for estimate in estimates if estimate is not None]
207 if not present:
208 return
209 average = np.mean(present, axis=0)
210 credit = np.stack([estimate if estimate is not None else average for estimate in estimates], axis=1)
211 log_probabilities = log_softmax(self._logits, axis=1)
212 probabilities = np.exp(log_probabilities)
213 utility = credit - self._entropy * log_probabilities
214 gradient = probabilities * (utility - (utility * probabilities).sum(axis=1, keepdims=True))
215 logits = self._logits + self._allocation_rate * gradient
216 if not np.isfinite(logits).all():
217 raise ValueError("Role contributions made the allocation logits nonfinite.")
218 self._logits = logits
219
220 def _migration_slots(self, asks):
221 slots = set()
222 for role_index in range(len(self.roles)):
223 rng = self._migration_rng
224 available = [list(range(count)) for count in asks]
225 for _ in range(self._migrants):
226 eligible = [i for i, slot in enumerate(available) if slot]
227 task_index = rng.choice(eligible, p=softmax(self._logits[role_index, eligible]))
228 selected = available[task_index].pop(rng.integers(len(available[task_index])))
229 slots.add((task_index, selected, role_index))
230 return slots
231
232 def _offspring(self, task, elites, slots):
233 rng = self._team_rng
234 if not elites:
235 return tuple(self._sample_role(role, rng) for role in range(len(self.roles)))
236 population = self._mainlands[task]
237 champion = elites[rng.integers(len(elites))]
238 # The population is fitness sorted, so the lower sampled rank wins.
239 contender = population[min(rng.integers(len(population), size=2))]
240 return tuple(self._sample_role(i, self._migration_rng) if i in slots else
241 tuple(map(float, np.where(rng.random(self._sizes[i]) < .5, first, second)))
242 for i, (first, second) in enumerate(zip(champion.genomes, contender.genomes)))
243
244 def _measure_team(self, evaluate, task, genomes):
245 self._counts["team_evaluations"] += 1
246 result = evaluate(task, genomes)
247 if result is None:
248 self._counts["failed_team_evaluations"] += 1
249 return None
250 fitness, contributions = (np.asarray(field, dtype=float) for field in result)
251 if (fitness.shape not in ((), (1,)) or not np.isfinite(fitness).all()
252 or contributions.shape != (len(self.roles),) or not np.isfinite(contributions).all()):
253 raise ValueError("Team evaluations must supply finite scalar fitness and one contribution per role.")
254 return AIMTeam(genomes, float(fitness.item()), tuple(map(float, contributions)))
255
256 def _advance_mainlands(self, evaluate, retained, migrate):
257 asks = [self._population - len(retained[task]) for task in self.tasks]
258 migration = self._migration_slots(asks) if migrate else set()
259 populations = {}
260 for task_index, (task, count) in enumerate(zip(self.tasks, asks)):
261 survivors = list(retained[task])
262 for slot in range(count):
263 exports = {i for i, role in enumerate(self.roles)
264 if (task_index, slot, i) in migration and len(self._islands[role])}
265 genomes = self._offspring(task, retained[task], exports)
266 self._counts["exported_roles"] += len(exports)
267 measured = self._measure_team(evaluate, task, genomes)
268 if measured is not None:
269 survivors.append(measured)
270 populations[task] = tuple(sorted(survivors, key=lambda team: team.fitness, reverse=True))
271 self._mainlands = populations
272
273
274 def run(self, evaluate_role, evaluate_team, *, island_budget, team_budget):
275 """Continue training and return cumulative AIMStats.
276
277 evaluate_role(role, genome) returns (fitness, descriptors).
278 evaluate_team(task, genomes) returns (fitness, role contributions).
279 Either evaluator can return None to report a failed call. The team
280 fitness is maximized. Retained teams keep their original measurements.
281 """
282 island_budget = _positive_int(island_budget, "island_budget")
283 team_budget = _positive_int(team_budget, "team_budget")
284 if not callable(evaluate_role) or not callable(evaluate_team):
285 raise TypeError("Supply both island and team evaluators.")
286 while True:
287 retained, migrate = self._elites_by_task(), self._migration_due()
288 island_cost, team_cost = self._costs(retained, migrate)
289 if island_cost > island_budget or team_cost > team_budget:
290 return self.stats
291 if migrate:
292 for elites in retained.values():
293 for elite in elites:
294 for role, genome in zip(self.roles, elite.genomes):
295 self._measure_role(evaluate_role, role, genome, returning=True)
296 self._update_allocation()
297 self._advance_islands(evaluate_role)
298 self._advance_mainlands(evaluate_team, retained, migrate)
299 island_budget -= island_cost
300 team_budget -= team_cost
301 self._counts["generations"] += 1
302 self._counts["migration_rounds"] += migrate
Cumulative evaluation and migration costs across islands and mainlands.
A measured mainland team with one genome and contribution per role.
Train heterogeneous teams through local QD and two-way policy migration.
_measure_team(self, evaluate, task, genomes)
run(self, evaluate_role, evaluate_team, *, island_budget, team_budget)
Spend separate hard budgets on whole island and mainland generations.
_advance_mainlands(self, evaluate, retained, migrate)
_measure_role(self, evaluate, role, genome, *, returning=False)
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405