QDpy
Loading...
Searching...
No Matches
dynamo.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Finite-pool DynAMO with an empirical Wasserstein source critic."""
7
8from dataclasses import dataclass
9
10import numpy as np
11from scipy.optimize import brentq, linprog
12from scipy.sparse import coo_matrix
13from scipy.spatial.distance import cdist
14from scipy.special import logsumexp, softmax
15
16from .modern import _bounds, _positive_int
17from .offline import _frozen_matern
18
19__all__ = ["DynAMO", "DynAMODesign", "DynAMOResult"]
20
21
22def _empirical_critic(source, weights, proposals):
23 """Solve the finite transport problem and recover a normalized Lipschitz critic."""
24 costs = cdist(source, proposals)
25 m, n = costs.shape
26 slots = np.arange(m * n)
27 rows = np.concatenate((np.repeat(np.arange(m), n), m + np.tile(np.arange(n), m)))
28 equality = coo_matrix((np.ones(2 * m * n), (rows, np.tile(slots, 2))),
29 shape=(m + n, m * n)).tocsr()
30 transport = linprog(costs.ravel(), A_eq=equality, b_eq=np.r_[weights, np.full(n, 1. / n)], method="highs")
31 if not transport.success:
32 raise RuntimeError(f"DynAMO transport solve failed: {transport.message}")
33 values = transport.eqlin.marginals[:m]
34 # The dual potentials are unique only up to an additive gauge.
35 # Shift them to start at zero for the scalar DynAMO dual.
36 return values - values.min(), max(0., float(transport.fun))
37
38
39def _dual_multiplier(values, weights, radius, cap):
40 """Maximize the bounded scalar dual of the KL-regularized objective."""
41 target = weights @ values - radius
42
43 def derivative(multiplier):
44 exponent = np.clip(multiplier * values - 1., -745., 700.)
45 return float(target - (weights * values) @ np.exp(exponent))
46
47 if derivative(0.) <= 0.:
48 return 0.
49 if derivative(cap) >= 0.:
50 return cap
51 return float(brentq(derivative, 0., cap))
52
53
54
55@dataclass(frozen=True)
57 """Keep raw predicted fitness and the probability of this design in the final pool."""
58
59 genome: tuple[float, ...]
60 predicted_fitness: float
61 probability: float
62
63
64
65@dataclass(frozen=True)
67 """Report predictions, solved transport problems, and the final minibatch diagnostic."""
68
69 designs: tuple[DynAMODesign, ...]
70 predictions: int
71 transport_solves: int
72 multiplier: float
73 source_distance: float
74
75
76
77class DynAMO:
78 """Implement the continuous distribution-matching objective of Yao et al.
79
80 A frozen GP scores a bounded candidate pool. A Gaussian mixture
81 smooths the reward-tilted empirical data distribution onto that pool.
82 Each round solves finite optimal transport between the weighted
83 reference and the new proposals to fit a Wasserstein critic. The
84 reward surrogate, the categorical KL term, and the critic adjustment
85 define the proposal probabilities. Draw the final batch without
86 replacement using the final scores. There is no descriptor grid.
87
88 :param genomes: Logged real design vectors within ind_domain.
89 :param fitnesses: One measured scalar objective per design.
90 :param ind_domain: Shared inclusive lower and upper genome bounds.
91 :param maximize: Maximize fitness if true, minimize it otherwise.
92 :param temperature: Positive tilt of the reference weights on scaled fitness.
93 :param beta: Positive KL penalty strength relative to the predicted objective.
94 :param transport_limit: Nonnegative target Wasserstein radius in normalized coordinates.
95 :param max_multiplier: Positive search cap for the transport dual variable.
96 :param bandwidth: Positive scale of the smoothing kernel in normalized coordinates.
97 :param batch_size: New designs per transport round.
98 :param reference_size: Maximum number of reference designs for each transport solve.
99 :param proposal_sigma: Positive local proposal scale in normalized coordinates.
100 :param length_scale: Fixed Matérn length scale for the frozen reward model.
101 :param noise: Positive covariance nugget for the frozen reward model.
102 :param seed: Seed for reference selection, variation, and batch sampling.
103 """
104
105 def __init__(self, genomes, fitnesses, *, ind_domain=(0., 1.), maximize=True, temperature=1.,
106 beta=1., transport_limit=.03, max_multiplier=16., bandwidth=.15, batch_size=24,
107 reference_size=64, proposal_sigma=.10, length_scale=.3, noise=1e-6, seed=0):
108 self._lower, self._upper = _bounds(tuple(map(float, ind_domain)))
109 self._span = self._upper - self._lower
110 if not np.isfinite(self._span):
111 raise ValueError("Genome bounds must have a finite span.")
112 positive = (temperature, beta, max_multiplier, bandwidth, proposal_sigma, length_scale, noise)
113 if (not all(0. < value < np.inf for value in positive) or not 0. <= transport_limit < np.inf
114 or not (np.isfinite(temperature / beta) and np.isfinite(temperature * max_multiplier))):
115 raise ValueError("Use finite positive DynAMO scales and a finite nonnegative transport limit.")
116 vectors, fitness = np.asarray(genomes, dtype=float), np.asarray(fitnesses, dtype=float)
117 if (vectors.ndim != 2 or len(vectors) < 2 or not vectors.shape[1] or fitness.shape != (len(vectors),)
118 or not np.isfinite(fitness).all() or not np.all((vectors >= self._lower) & (vectors <= self._upper))):
119 raise ValueError("Supply at least two aligned, finite, in-domain design and fitness rows.")
120 self._direction = 1. if maximize else -1.
121 signed = self._direction * fitness
122 self._base = float(signed.min())
123 self._scale = float(signed.max()) - self._base or 1.
124 if not np.isfinite(self._scale):
125 raise ValueError("Observed fitness must have a finite span.")
126 self._vectors = (vectors - self._lower) / self._span
127 self._quality = (signed - self._base) / self._scale
128 self._temperature, self._reward_scale = temperature, temperature / beta
129 self._radius, self._max_multiplier, self._bandwidth = transport_limit, max_multiplier, bandwidth
130 self._batch_size = _positive_int(batch_size, "batch_size")
131 self._reference_size = min(_positive_int(reference_size, "reference_size"), len(vectors))
132 self._sigma, self.seed = proposal_sigma, seed
133 self._model = _frozen_matern(self._vectors, self._quality, length_scale, noise)
134
135
136 def run(self, budget, *, count=16):
137 """Assess budget proposals and return at most count distinct designs."""
138 budget = _positive_int(budget, "budget")
139 count = _positive_int(count, "count")
140 reference_rng, proposal_rng, draw_rng = map(np.random.default_rng, np.random.SeedSequence(self.seed).spawn(3))
141 slots = (np.arange(len(self._vectors)) if self._reference_size == len(self._vectors)
142 else reference_rng.choice(len(self._vectors), self._reference_size, replace=False))
143 reference = self._vectors[slots]
144 logits = self._temperature * (self._quality[slots] - self._quality[slots].max())
145 log_weights = logits - logsumexp(logits)
146 weights = np.exp(log_weights)
147 if np.any(weights == 0.):
148 active = weights > 0.
149 reference, weights, log_weights = reference[active], weights[active], log_weights[active]
150 pool = {}
151 probabilities = None
152 solves = 0
153 for start in range(0, budget, self._batch_size):
154 size = min(self._batch_size, budget - start)
155 proposals = proposal_rng.random((size, reference.shape[1]))
156 local = size - size // 4
157 if not pool:
158 proposals[:local] = reference[proposal_rng.choice(len(reference), size=local, p=weights)]
159 else:
160 parents = proposal_rng.choice(len(pool), size=local, p=probabilities)
161 proposals[:local] = np.clip(points[parents] + proposal_rng.normal(0., self._sigma,
162 size=(local, reference.shape[1])), 0., 1.)
163 predictions = self._model.predict(proposals)
164 if not np.isfinite(predictions).all():
165 raise ValueError("The frozen reward surrogate produced nonfinite predictions.")
166 for point, score in zip(proposals, predictions):
167 pool.setdefault(tuple(point), float(score))
168
169 potential, source_distance = _empirical_critic(reference, weights, proposals)
170 solves += 1
171 multiplier = _dual_multiplier(potential, weights, self._radius, self._max_multiplier)
172 points = np.asarray(tuple(pool))
173 distances = cdist(points, reference)
174 # The largest Lipschitz lower extension decays away from observed designs.
175 critic = (potential - distances).max(axis=1)
176 with np.errstate(over="ignore"):
177 density = logsumexp(-.5 * np.square(distances / self._bandwidth) + log_weights, axis=1)
178 scores = density + self._reward_scale * np.asarray(tuple(pool.values())) + (
179 self._temperature * multiplier) * critic
180 if not np.isfinite(scores).all():
181 raise ValueError("DynAMO acquisition became nonfinite. Reduce the scale ratios.")
182 probabilities = softmax(scores)
183
184 order = np.argsort(-(scores - scores.max() + draw_rng.gumbel(size=len(scores))), kind="stable")
185 predicted = self._direction * (self._base + self._scale * np.asarray(tuple(pool.values())))
186 if not np.isfinite(predicted).all():
187 raise ValueError("Predicted fitness exceeds the raw objective range.")
188 physical = np.clip(self._lower + self._span * points, self._lower, self._upper)
189 designs = {}
190 for i in order:
191 point = tuple(physical[i])
192 designs.setdefault(point, DynAMODesign(point, float(predicted[i]), float(probabilities[i])))
193 if len(designs) == count:
194 break
195 return DynAMOResult(tuple(designs.values()), budget, solves, multiplier, source_distance)
One sampled design and its score under the frozen reward surrogate.
Definition dynamo.py:56
Return a batch and separate surrogate and transport counts.
Definition dynamo.py:66
Optimize a categorical design distribution on an expanding continuous candidate pool.
Definition dynamo.py:77
run(self, budget, *, count=16)
Sample a design batch while using only logged data and surrogate queries.
Definition dynamo.py:136