Source code for qdpy.algorithms.density_flow

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Rank Density Descent Search candidates with a continuous normalizing flow.
# @see https://doi.org/10.1145/3638529.3654001

"""Fit a neural descriptor density and reuse the standard DDS search loop."""

from dataclasses import dataclass, field
from math import log, pi
from time import perf_counter

import numpy as np

from .descriptor_cma import DDSResult, _density_descent
from .modern import _positive_int

__all__ = ["DDSCNFResult", "dds_cnf"]


## @brief DDS accounting with separate model training and density prediction counts.
[docs] @dataclass(frozen=True) class DDSCNFResult(DDSResult): """The first generation uses equal density ranks until measurements exist.""" model_fits: int optimizer_steps: int density_evaluations: int fit_seconds: float = field(compare=False) density_seconds: float = field(compare=False)
def _log_density(torch, network, points, integration_steps): """Integrate descriptors and the exact change-of-variables trace backward.""" def derivative(time, value): with torch.enable_grad(): value = value.detach().requires_grad_(True) velocity = network(torch.cat((value, value.new_full((len(value), 1), time)), dim=1)) divergence = value.new_zeros(len(value)) if velocity.requires_grad: for column in range(value.shape[1]): grad, = torch.autograd.grad(velocity[:, column].sum(), value, retain_graph=column + 1 < value.shape[1], allow_unused=True) if grad is not None: divergence += grad[:, column] return velocity.detach(), divergence step = -1. / integration_steps correction = points.new_zeros(len(points)) for i in range(integration_steps): time = 1. + i * step with torch.no_grad(): start = network(torch.cat((points, points.new_full((len(points), 1), time)), dim=1)) speed, trace = derivative(time + step / 2., points + step / 2. * start) points = points + step * speed correction += step * trace return -.5 * (points.square().sum(dim=1) + points.shape[1] * log(2. * pi)) + correction class _FlowDensity: def __init__(self, torch, *, seed, width, fit_period, updates, batch_size, integration_steps, learning_rate): self.torch = torch self.seed, self.width, self.period = seed, width, fit_period self.updates, self.batch_size, self.integration_steps, self.rate = updates, batch_size, integration_steps, learning_rate self.rng = torch.Generator(device="cpu").manual_seed(seed) self.network = None self.last_fit = self.fits = self.steps = self.predictions = 0 self.fit_seconds = self.density_seconds = 0. def _initialize(self, samples): torch = self.torch self.scale = samples.abs().amax(dim=0).clamp(min=1.) scaled = samples / self.scale self.center = scaled.mean(dim=0) deviation = scaled.std(dim=0, correction=0) self.spread = torch.where(deviation >= .02, deviation, 1.) dimension = samples.shape[1] with torch.random.fork_rng(devices=[]): torch.random.default_generator.manual_seed(self.seed) self.network = torch.nn.Sequential( torch.nn.Linear(dimension + 1, self.width, device="cpu", dtype=torch.float64), torch.nn.Tanh(), torch.nn.Linear(self.width, self.width, device="cpu", dtype=torch.float64), torch.nn.Tanh(), torch.nn.Linear(self.width, dimension, device="cpu", dtype=torch.float64), ) self.optimizer = torch.optim.Adam(self.network.parameters(), lr=self.rate) def _normalize(self, points): return (points / self.scale - self.center) / self.spread def _fit(self, previous, iteration): torch = self.torch samples = torch.as_tensor(previous, dtype=torch.float64, device="cpu") if self.network is None: self._initialize(samples) samples = self._normalize(samples) # Conditional flow matching of paths from N(0, I) to a narrow Gaussian # around each data point. The analytic target is the path velocity. terminal_noise = .001 for _ in range(self.updates): indices = torch.randint(len(samples), (self.batch_size,), generator=self.rng, device="cpu") target = samples[indices] base = torch.randn(target.shape, generator=self.rng, dtype=target.dtype, device="cpu") time = torch.rand((len(target), 1), generator=self.rng, dtype=target.dtype, device="cpu") point = (1. - (1. - terminal_noise) * time) * base + time * target velocity = target - (1. - terminal_noise) * base loss = (self.network(torch.cat((point, time), dim=1)) - velocity).square().mean() if not torch.isfinite(loss): raise ValueError("Flow fitting produced a nonfinite loss. Rescale the descriptors.") self.optimizer.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(self.network.parameters(), 10., error_if_nonfinite=True) self.optimizer.step() self.steps += 1 self.last_fit = iteration self.fits += 1 def __call__(self, points, previous, iteration): if not len(previous): return np.zeros(len(points)) if self.network is None or iteration - self.last_fit >= self.period: start = perf_counter() with self.torch.enable_grad(): self._fit(previous, iteration) self.fit_seconds += perf_counter() - start start = perf_counter() values = self._normalize(self.torch.as_tensor(points, dtype=self.torch.float64, device="cpu")) scores = -_log_density(self.torch, self.network, values, self.integration_steps).numpy() self.density_seconds += perf_counter() - start if np.isnan(scores).any(): raise ValueError("Flow integration produced NaN scores. Rescale descriptors or increase the step count.") self.predictions += len(scores) return scores ## @brief Use a flow-matched continuous density in the standard CMA-based DDS loop. # @param archive Empty parentless best-only Grid or CVTGrid used for reporting. # @param evaluate Callable (genome) returning singleton fitness and a descriptor vector. # @param x0 Initial CMA mean. # @param budget Total attempted evaluations, including failures. # @param reservoir_size Number of previous measurements retained for the density model. # @param sigma0 CMA sampling scale. # @param batch_size Candidate batch size. # @param ind_domain Shared genome bounds, or None for unbounded search. # @param seed Private search and flow seed. # @param executor Optional ordered map executor for evaluations. # @param on_step Optional callback receiving archive, iteration, and evaluation count. # @param model_width Width of the two hidden layers. # @param fit_period Batches between model updates. # @param fit_steps Adam updates at each refit. # @param fit_batch_size Descriptor samples per Adam update. # @param integration_steps Midpoint integration steps per density calculation. # @param learning_rate Flow Adam learning rate. # @return DDSCNFResult with separate search, training, and prediction accounting.
[docs] def dds_cnf(archive, evaluate, *, x0, budget, reservoir_size=1024, sigma0=.15, batch_size=16, ind_domain=(0., 1.), seed=0, executor=None, on_step=None, model_width=32, fit_period=4, fit_steps=20, fit_batch_size=32, integration_steps=8, learning_rate=.003): """Run DDS with a CPU PyTorch flow trained by conditional flow matching. Fit only on earlier descriptor batches. Score a candidate by mapping its descriptor back to a standard Gaussian and integrating the velocity divergence. A fixed affine normalization is learned from the first nonempty reservoir. Its log determinant cancels in the ranking. Fitness still controls only admission to the reporting archive. Requires pycma and PyTorch, available through the existing ``dms`` extra. """ try: import torch except ImportError as error: raise ImportError("DDS-CNF needs PyTorch and the 'cma' extra. Install qdpy[dms].") from error if not 0. < learning_rate < np.inf: raise ValueError("Use a positive finite learning_rate.") flow_seed = int(np.random.SeedSequence(seed).generate_state(1)[0]) model = _FlowDensity( torch, seed=flow_seed, width=_positive_int(model_width, "model_width"), fit_period=_positive_int(fit_period, "fit_period"), updates=_positive_int(fit_steps, "fit_steps"), batch_size=_positive_int(fit_batch_size, "fit_batch_size"), integration_steps=_positive_int(integration_steps, "integration_steps"), learning_rate=learning_rate, ) result = _density_descent(archive, evaluate, x0, budget, reservoir_size, sigma0, batch_size, ind_domain, seed, executor, on_step, model) return DDSCNFResult(result.archive, result.attempts, result.failures, result.reservoir_size, model.fits, model.steps, model.predictions, model.fit_seconds, model.density_seconds)