QDpy
Loading...
Searching...
No Matches
diffusion_evolution.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Generate offspring with fitness-weighted Gaussian denoising."""
7
8import numpy as np
9from scipy.spatial.distance import cdist
10from scipy.special import softmax
11
12from qdpy.base import registry
13
14from .modern import _FixedGeneration, _positive_int
15from .task_search import _search_bounds, _validate_grid
16
17__all__ = ["DiffusionEvolution", "DiffusionMAPElites"]
18
19
20def _denoise(particles, references, log_density, alpha, next_alpha, noise_scale, rng):
21 """Apply one reverse diffusion step in normalized genome coordinates."""
22 signal = np.sqrt(alpha)
23 variance = 1. - alpha
24 logits = cdist(particles, signal * references, "sqeuclidean")
25 logits *= -.5 / variance
26 logits += log_density
27 estimate = softmax(logits, axis=1) @ references
28 residual = (particles - signal * estimate) / np.sqrt(variance)
29 next_variance = 1. - next_alpha
30 sigma = noise_scale * np.sqrt(next_variance / variance * (1. - alpha / next_alpha))
31 residual_scale = np.sqrt(max(0., next_variance - sigma**2))
32 return np.sqrt(next_alpha) * estimate + residual_scale * residual + sigma * rng.normal(size=particles.shape)
33
34
35def _log_density(quality, temperature):
36 """Map signed fitness monotonically to positive relative sampling weights."""
37 scaled = quality / (np.max(np.abs(quality)) or 1.)
38 span = np.ptp(scaled)
39 if span == 0.:
40 return np.zeros_like(quality)
41 with np.errstate(over="ignore"):
42 return np.maximum(((scaled - np.max(scaled)) / span) / temperature, -700.)
43
44
45
46@registry.register
48 """Run bounded, population-only Diffusion Evolution with a reporting grid.
49
50 Shape Gaussian denoising estimates using the previous generation's
51 signed objective. The reporting archive fills from measured candidates
52 and stays outside the proposal loop. Progress through a cosine
53 schedule, then start another Gaussian population if more budget
54 remains. Bounds and fitness scaling adapt the paper to the native
55 fixed-generation evaluator API.
56
57 :param container: Parentless best-only scalar Grid or CVTGrid.
58 :param budget: Number of attempted candidate evaluations.
59 :param dimension: Number of real genome coordinates.
60 :param batch_size: Maximum population size.
61 :param ind_domain: Shared finite lower and upper bounds.
62 :param diffusion_steps: Generations per cosine schedule, at least two.
63 :param temperature: Positive fitness temperature for denoising weights.
64 :param noise_scale: DDIM noise multiplier between zero and one.
65 :param seed: Private seed for Gaussian proposals and restart populations.
66 :param kwargs: Native optimizer options, such as optimisation_task.
67 """
68
69 _requires_proposed_genome = True
70
71 def __init__(self, container, budget, dimension, batch_size, *, ind_domain=(-1., 1.),
72 diffusion_steps=20, temperature=.25, noise_scale=1., seed=0, **kwargs):
73 _validate_grid(container, empty=False)
74 self.ind_domain = _search_bounds(ind_domain)
75 steps = _positive_int(diffusion_steps, "diffusion_steps")
76 if (steps < 2 or not np.isfinite(temperature) or temperature <= 0.
77 or not 0. <= noise_scale <= 1.):
78 raise ValueError("Use at least two steps, positive finite temperature, and noise_scale in [0, 1].")
79 self._schedule = 1e-4 + (1. - 2e-4) * np.square(np.sin(np.linspace(0., np.pi / 2, steps)))
80 self._temperature, self._noise, self._seed = temperature, noise_scale, seed
81 kwargs.setdefault("optimisation_task", container.fitness_weights or "maximisation")
82 super().__init__(container, _positive_int(budget, "budget"),
83 dimension=_positive_int(dimension, "dimension"),
84 batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
85 if not np.isfinite(self._fitness_weights[0]) or self._fitness_weights[0] == 0.:
86 raise ValueError("Use a finite nonzero objective weight.")
87
88 def reinit(self):
89 """Reset the diffusion schedule and its previous measured population."""
90 super().reinit()
91 self._rng = np.random.default_rng(self._seed)
92 self._population = ()
93 self._proposals = ()
95
96 @property
98 """Return the number of candidates produced by completed denoising steps."""
99 return self._diffusion_proposals
100
101 def _normalize(self, entries):
102 lower, upper = self.ind_domain
103 return 2. * ((np.asarray(entries, dtype=float) - lower) / (upper - lower)) - 1.
104
105 def _sources(self, size, alpha):
106 if not self._population:
107 return None
108 vectors, quality = self._population
109 parent_ids = np.arange(size) if len(vectors) == size else self._rng.integers(len(vectors), size=size)
110 return vectors[parent_ids], vectors, quality
111
112 def _start_fixed_batch(self, size):
113 super()._start_fixed_batch(size)
114 stage = self.current_iter % len(self._schedule)
115 sources = self._sources(size, self._schedule[stage - 1]) if stage else None
116 if sources is None:
117 latent = self._rng.normal(size=(size, self.dimension))
118 else:
119 particles, vectors, quality = sources
120 latent = _denoise(particles, vectors, _log_density(quality, self._temperature),
121 self._schedule[stage - 1], self._schedule[stage], self._noise, self._rng)
122 self._diffusion_proposals += size
123 lower, upper = self.ind_domain
124 proportion = (.5 + .5 * np.clip(latent, -1., 1.))
125 self._proposals = np.clip(lower + (upper - lower) * proportion, lower, upper)
126
127 def _internal_ask(self, base_ind):
128 base_ind[:] = self._proposals[len(self._issued)].tolist()
129 return base_ind
130
131 def _clear_generation(self):
132 super()._clear_generation()
133 self._proposals = ()
134
135 def _check_candidate(self, individual):
136 self._check_measurements(individual)
137 fitness = self.container.get_ind_fitness(individual)
138 features = self.container.get_ind_features(individual)
139 if len(fitness.values) != 1 or len(features) != len(self.container.features_domain):
140 raise ValueError("Return one fitness value and the reporting grid's descriptor vector.")
141
142 def _fitness(self, individual):
143 return self.container.get_ind_fitness(individual).values[0]
144
145 def _reference_data(self, entries):
146 genomes = self._normalize(entries)
147 direction = 1. if self._fitness_weights[0] > 0. else -1.
148 fitness = direction * np.array([self._fitness(item) for item in entries], dtype=float)
149 return genomes, fitness
150
151 def _commit_generation(self, evaluated):
152 valid = [item for item in evaluated if item is not None]
153 self._population = self._reference_data(valid) if valid else ()
154 admitted = set()
155 archive = self.container
156 for slot, item in enumerate(evaluated):
157 if item is None:
158 continue
159 features = archive.get_ind_features(item)
160 if (archive.in_bounds(features, archive.features_domain)
161 and archive.in_bounds((self._fitness(item),), archive.fitness_domain)
162 and self._offer_to_grid(item, archive.index_grid(item))):
163 admitted.add(slot)
164 return admitted
165
166
167
168@registry.register
170 """Use archive elites as references and seed particles across occupied niches.
171
172 Each reference is a genuinely measured elite. Draw an occupied cell
173 for each particle and add forward noise at the current schedule stage.
174 The same reverse update as DiffusionEvolution proposes offspring.
175 Select a bounded uniform subset if the archive grows too large.
176
177 :param max_elites: Maximum number of occupied cells in the denoising reference pool.
178 """
179
180 def __init__(self, container, budget, dimension, batch_size, *, max_elites=256, **kwargs):
181 self.max_elites = _positive_int(max_elites, "max_elites")
182 super().__init__(container, budget, dimension, batch_size, **kwargs)
183
184 def _sources(self, size, alpha):
185 if not self.container:
186 return super()._sources(size, alpha)
187 indices = np.arange(len(self.container))
188 if len(indices) > self.max_elites:
189 indices = self._rng.choice(indices, size=self.max_elites, replace=False)
190 vectors, fitness = self._reference_data([self.container[int(i)] for i in indices])
191 if (vectors.shape != (len(indices), self.dimension) or not np.isfinite(vectors).all()
192 or (np.abs(vectors) > 1. + 1e-12).any() or not np.isfinite(fitness).all()):
193 raise ValueError("Seeded elites must have finite in-domain genomes with the configured dimension.")
194 parents = vectors[self._rng.integers(len(vectors), size=size)]
195 particles = np.sqrt(alpha) * parents + np.sqrt(1. - alpha) * self._rng.normal(size=parents.shape)
196 return particles, vectors, fitness
Optimize a measured population with the reverse diffusion update.
Denoise Gaussian particles around uniformly sampled archive cells.
_check_measurements(self, individual)
Definition modern.py:216
_offer_to_grid(self, individual, cell)
Definition modern.py:228