# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Distribution-matched continuous design proposals from a fixed data log.
# @see https://proceedings.mlr.press/v267/yao25b.html
"""Finite-pool DynAMO with an empirical Wasserstein source critic."""
from dataclasses import dataclass
import numpy as np
from scipy.optimize import brentq, linprog
from scipy.sparse import coo_matrix
from scipy.spatial.distance import cdist
from scipy.special import logsumexp, softmax
from .modern import _bounds, _positive_int
from .offline import _frozen_matern
__all__ = ["DynAMO", "DynAMODesign", "DynAMOResult"]
def _empirical_critic(source, weights, proposals):
"""Solve the finite transport problem and recover a normalized Lipschitz critic."""
costs = cdist(source, proposals)
m, n = costs.shape
slots = np.arange(m * n)
rows = np.concatenate((np.repeat(np.arange(m), n), m + np.tile(np.arange(n), m)))
equality = coo_matrix((np.ones(2 * m * n), (rows, np.tile(slots, 2))),
shape=(m + n, m * n)).tocsr()
transport = linprog(costs.ravel(), A_eq=equality, b_eq=np.r_[weights, np.full(n, 1. / n)], method="highs")
if not transport.success:
raise RuntimeError(f"DynAMO transport solve failed: {transport.message}")
values = transport.eqlin.marginals[:m]
# The dual potentials are unique only up to an additive gauge.
# Shift them to start at zero for the scalar DynAMO dual.
return values - values.min(), max(0., float(transport.fun))
def _dual_multiplier(values, weights, radius, cap):
"""Maximize the bounded scalar dual of the KL-regularized objective."""
target = weights @ values - radius
def derivative(multiplier):
exponent = np.clip(multiplier * values - 1., -745., 700.)
return float(target - (weights * values) @ np.exp(exponent))
if derivative(0.) <= 0.:
return 0.
if derivative(cap) >= 0.:
return cap
return float(brentq(derivative, 0., cap))
## @brief One sampled design and its score under the frozen reward surrogate.
[docs]
@dataclass(frozen=True)
class DynAMODesign:
"""Keep raw predicted fitness and the probability of this design in the final pool."""
genome: tuple[float, ...]
predicted_fitness: float
probability: float
## @brief Return a batch and separate surrogate and transport counts.
[docs]
@dataclass(frozen=True)
class DynAMOResult:
"""Report predictions, solved transport problems, and the final minibatch diagnostic."""
designs: tuple[DynAMODesign, ...]
predictions: int
transport_solves: int
multiplier: float
source_distance: float
## @brief Optimize a categorical design distribution on an expanding continuous candidate pool.
[docs]
class DynAMO:
"""Implement the continuous distribution-matching objective of Yao et al.
A frozen GP scores a bounded candidate pool. A Gaussian mixture
smooths the reward-tilted empirical data distribution onto that pool.
Each round solves finite optimal transport between the weighted
reference and the new proposals to fit a Wasserstein critic. The
reward surrogate, the categorical KL term, and the critic adjustment
define the proposal probabilities. Draw the final batch without
replacement using the final scores. There is no descriptor grid.
:param genomes: Logged real design vectors within ind_domain.
:param fitnesses: One measured scalar objective per design.
:param ind_domain: Shared inclusive lower and upper genome bounds.
:param maximize: Maximize fitness if true, minimize it otherwise.
:param temperature: Positive tilt of the reference weights on scaled fitness.
:param beta: Positive KL penalty strength relative to the predicted objective.
:param transport_limit: Nonnegative target Wasserstein radius in normalized coordinates.
:param max_multiplier: Positive search cap for the transport dual variable.
:param bandwidth: Positive scale of the smoothing kernel in normalized coordinates.
:param batch_size: New designs per transport round.
:param reference_size: Maximum number of reference designs for each transport solve.
:param proposal_sigma: Positive local proposal scale in normalized coordinates.
:param length_scale: Fixed Matérn length scale for the frozen reward model.
:param noise: Positive covariance nugget for the frozen reward model.
:param seed: Seed for reference selection, variation, and batch sampling.
"""
def __init__(self, genomes, fitnesses, *, ind_domain=(0., 1.), maximize=True, temperature=1.,
beta=1., transport_limit=.03, max_multiplier=16., bandwidth=.15, batch_size=24,
reference_size=64, proposal_sigma=.10, length_scale=.3, noise=1e-6, seed=0):
self._lower, self._upper = _bounds(tuple(map(float, ind_domain)))
self._span = self._upper - self._lower
if not np.isfinite(self._span):
raise ValueError("Genome bounds must have a finite span.")
positive = (temperature, beta, max_multiplier, bandwidth, proposal_sigma, length_scale, noise)
if (not all(0. < value < np.inf for value in positive) or not 0. <= transport_limit < np.inf
or not (np.isfinite(temperature / beta) and np.isfinite(temperature * max_multiplier))):
raise ValueError("Use finite positive DynAMO scales and a finite nonnegative transport limit.")
vectors, fitness = np.asarray(genomes, dtype=float), np.asarray(fitnesses, dtype=float)
if (vectors.ndim != 2 or len(vectors) < 2 or not vectors.shape[1] or fitness.shape != (len(vectors),)
or not np.isfinite(fitness).all() or not np.all((vectors >= self._lower) & (vectors <= self._upper))):
raise ValueError("Supply at least two aligned, finite, in-domain design and fitness rows.")
self._direction = 1. if maximize else -1.
signed = self._direction * fitness
self._base = float(signed.min())
self._scale = float(signed.max()) - self._base or 1.
if not np.isfinite(self._scale):
raise ValueError("Observed fitness must have a finite span.")
self._vectors = (vectors - self._lower) / self._span
self._quality = (signed - self._base) / self._scale
self._temperature, self._reward_scale = temperature, temperature / beta
self._radius, self._max_multiplier, self._bandwidth = transport_limit, max_multiplier, bandwidth
self._batch_size = _positive_int(batch_size, "batch_size")
self._reference_size = min(_positive_int(reference_size, "reference_size"), len(vectors))
self._sigma, self.seed = proposal_sigma, seed
self._model = _frozen_matern(self._vectors, self._quality, length_scale, noise)
## @brief Sample a design batch while using only logged data and surrogate queries.
[docs]
def run(self, budget, *, count=16):
"""Assess budget proposals and return at most count distinct designs."""
budget = _positive_int(budget, "budget")
count = _positive_int(count, "count")
reference_rng, proposal_rng, draw_rng = map(np.random.default_rng, np.random.SeedSequence(self.seed).spawn(3))
slots = (np.arange(len(self._vectors)) if self._reference_size == len(self._vectors)
else reference_rng.choice(len(self._vectors), self._reference_size, replace=False))
reference = self._vectors[slots]
logits = self._temperature * (self._quality[slots] - self._quality[slots].max())
log_weights = logits - logsumexp(logits)
weights = np.exp(log_weights)
if np.any(weights == 0.):
active = weights > 0.
reference, weights, log_weights = reference[active], weights[active], log_weights[active]
pool = {}
probabilities = None
solves = 0
for start in range(0, budget, self._batch_size):
size = min(self._batch_size, budget - start)
proposals = proposal_rng.random((size, reference.shape[1]))
local = size - size // 4
if not pool:
proposals[:local] = reference[proposal_rng.choice(len(reference), size=local, p=weights)]
else:
parents = proposal_rng.choice(len(pool), size=local, p=probabilities)
proposals[:local] = np.clip(points[parents] + proposal_rng.normal(0., self._sigma,
size=(local, reference.shape[1])), 0., 1.)
predictions = self._model.predict(proposals)
if not np.isfinite(predictions).all():
raise ValueError("The frozen reward surrogate produced nonfinite predictions.")
for point, score in zip(proposals, predictions):
pool.setdefault(tuple(point), float(score))
potential, source_distance = _empirical_critic(reference, weights, proposals)
solves += 1
multiplier = _dual_multiplier(potential, weights, self._radius, self._max_multiplier)
points = np.asarray(tuple(pool))
distances = cdist(points, reference)
# The largest Lipschitz lower extension decays away from observed designs.
critic = (potential - distances).max(axis=1)
with np.errstate(over="ignore"):
density = logsumexp(-.5 * np.square(distances / self._bandwidth) + log_weights, axis=1)
scores = density + self._reward_scale * np.asarray(tuple(pool.values())) + (
self._temperature * multiplier) * critic
if not np.isfinite(scores).all():
raise ValueError("DynAMO acquisition became nonfinite. Reduce the scale ratios.")
probabilities = softmax(scores)
order = np.argsort(-(scores - scores.max() + draw_rng.gumbel(size=len(scores))), kind="stable")
predicted = self._direction * (self._base + self._scale * np.asarray(tuple(pool.values())))
if not np.isfinite(predicted).all():
raise ValueError("Predicted fitness exceeds the raw objective range.")
physical = np.clip(self._lower + self._span * points, self._lower, self._upper)
designs = {}
for i in order:
point = tuple(physical[i])
designs.setdefault(point, DynAMODesign(point, float(predicted[i]), float(probabilities[i])))
if len(designs) == count:
break
return DynAMOResult(tuple(designs.values()), budget, solves, multiplier, source_distance)