QDpy
Loading...
Searching...
No Matches
density_flow.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Fit a neural descriptor density and reuse the standard DDS search loop."""
7
8from dataclasses import dataclass, field
9from math import log, pi
10from time import perf_counter
11
12import numpy as np
13
14from .descriptor_cma import DDSResult, _density_descent
15from .modern import _positive_int
16
17__all__ = ["DDSCNFResult", "dds_cnf"]
18
19
20
21@dataclass(frozen=True)
23 """The first generation uses equal density ranks until measurements exist."""
24
25 model_fits: int
26 optimizer_steps: int
27 density_evaluations: int
28 fit_seconds: float = field(compare=False)
29 density_seconds: float = field(compare=False)
30
31
32def _log_density(torch, network, points, integration_steps):
33 """Integrate descriptors and the exact change-of-variables trace backward."""
34 def derivative(time, value):
35 with torch.enable_grad():
36 value = value.detach().requires_grad_(True)
37 velocity = network(torch.cat((value, value.new_full((len(value), 1), time)), dim=1))
38 divergence = value.new_zeros(len(value))
39 if velocity.requires_grad:
40 for column in range(value.shape[1]):
41 grad, = torch.autograd.grad(velocity[:, column].sum(), value,
42 retain_graph=column + 1 < value.shape[1], allow_unused=True)
43 if grad is not None:
44 divergence += grad[:, column]
45 return velocity.detach(), divergence
46
47 step = -1. / integration_steps
48 correction = points.new_zeros(len(points))
49 for i in range(integration_steps):
50 time = 1. + i * step
51 with torch.no_grad():
52 start = network(torch.cat((points, points.new_full((len(points), 1), time)), dim=1))
53 speed, trace = derivative(time + step / 2., points + step / 2. * start)
54 points = points + step * speed
55 correction += step * trace
56 return -.5 * (points.square().sum(dim=1) + points.shape[1] * log(2. * pi)) + correction
57
58
60 def __init__(self, torch, *, seed, width, fit_period, updates, batch_size, integration_steps, learning_rate):
61 self.torch = torch
62 self.seed, self.width, self.period = seed, width, fit_period
63 self.updates, self.batch_size, self.integration_steps, self.rate = updates, batch_size, integration_steps, learning_rate
64 self.rng = torch.Generator(device="cpu").manual_seed(seed)
65 self.network = None
66 self.last_fit = self.fits = self.steps = self.predictions = 0
67 self.fit_seconds = self.density_seconds = 0.
68
69 def _initialize(self, samples):
70 torch = self.torch
71 self.scale = samples.abs().amax(dim=0).clamp(min=1.)
72 scaled = samples / self.scale
73 self.center = scaled.mean(dim=0)
74 deviation = scaled.std(dim=0, correction=0)
75 self.spread = torch.where(deviation >= .02, deviation, 1.)
76 dimension = samples.shape[1]
77 with torch.random.fork_rng(devices=[]):
78 torch.random.default_generator.manual_seed(self.seed)
79 self.network = torch.nn.Sequential(
80 torch.nn.Linear(dimension + 1, self.width, device="cpu", dtype=torch.float64), torch.nn.Tanh(),
81 torch.nn.Linear(self.width, self.width, device="cpu", dtype=torch.float64), torch.nn.Tanh(),
82 torch.nn.Linear(self.width, dimension, device="cpu", dtype=torch.float64),
83 )
84 self.optimizer = torch.optim.Adam(self.network.parameters(), lr=self.rate)
85
86 def _normalize(self, points):
87 return (points / self.scale - self.center) / self.spread
88
89 def _fit(self, previous, iteration):
90 torch = self.torch
91 samples = torch.as_tensor(previous, dtype=torch.float64, device="cpu")
92 if self.network is None:
93 self._initialize(samples)
94 samples = self._normalize(samples)
95 # Conditional flow matching of paths from N(0, I) to a narrow Gaussian
96 # around each data point. The analytic target is the path velocity.
97 terminal_noise = .001
98 for _ in range(self.updates):
99 indices = torch.randint(len(samples), (self.batch_size,), generator=self.rng, device="cpu")
100 target = samples[indices]
101 base = torch.randn(target.shape, generator=self.rng, dtype=target.dtype, device="cpu")
102 time = torch.rand((len(target), 1), generator=self.rng, dtype=target.dtype, device="cpu")
103 point = (1. - (1. - terminal_noise) * time) * base + time * target
104 velocity = target - (1. - terminal_noise) * base
105 loss = (self.network(torch.cat((point, time), dim=1)) - velocity).square().mean()
106 if not torch.isfinite(loss):
107 raise ValueError("Flow fitting produced a nonfinite loss. Rescale the descriptors.")
108 self.optimizer.zero_grad(set_to_none=True)
109 loss.backward()
110 torch.nn.utils.clip_grad_norm_(self.network.parameters(), 10., error_if_nonfinite=True)
111 self.optimizer.step()
112 self.steps += 1
113 self.last_fit = iteration
114 self.fits += 1
115
116 def __call__(self, points, previous, iteration):
117 if not len(previous):
118 return np.zeros(len(points))
119 if self.network is None or iteration - self.last_fit >= self.period:
120 start = perf_counter()
121 with self.torch.enable_grad():
122 self._fit(previous, iteration)
123 self.fit_seconds += perf_counter() - start
124 start = perf_counter()
125 values = self._normalize(self.torch.as_tensor(points, dtype=self.torch.float64, device="cpu"))
126 scores = -_log_density(self.torch, self.network, values, self.integration_steps).numpy()
127 self.density_seconds += perf_counter() - start
128 if np.isnan(scores).any():
129 raise ValueError("Flow integration produced NaN scores. Rescale descriptors or increase the step count.")
130 self.predictions += len(scores)
131 return scores
132
133
134
153def dds_cnf(archive, evaluate, *, x0, budget, reservoir_size=1024, sigma0=.15, batch_size=16,
154 ind_domain=(0., 1.), seed=0, executor=None, on_step=None, model_width=32, fit_period=4,
155 fit_steps=20, fit_batch_size=32, integration_steps=8, learning_rate=.003):
156 """Run DDS with a CPU PyTorch flow trained by conditional flow matching.
157
158 Fit only on earlier descriptor batches. Score a candidate by mapping its
159 descriptor back to a standard Gaussian and integrating the velocity
160 divergence. A fixed affine normalization is learned from the first
161 nonempty reservoir. Its log determinant cancels in the ranking.
162 Fitness still controls only admission to the reporting archive.
163
164 Requires pycma and PyTorch, available through the existing ``dms`` extra.
165 """
166 try:
167 import torch
168 except ImportError as error:
169 raise ImportError("DDS-CNF needs PyTorch and the 'cma' extra. Install qdpy[dms].") from error
170 if not 0. < learning_rate < np.inf:
171 raise ValueError("Use a positive finite learning_rate.")
172 flow_seed = int(np.random.SeedSequence(seed).generate_state(1)[0])
173 model = _FlowDensity(
174 torch, seed=flow_seed, width=_positive_int(model_width, "model_width"),
175 fit_period=_positive_int(fit_period, "fit_period"), updates=_positive_int(fit_steps, "fit_steps"),
176 batch_size=_positive_int(fit_batch_size, "fit_batch_size"),
177 integration_steps=_positive_int(integration_steps, "integration_steps"), learning_rate=learning_rate,
178 )
179 result = _density_descent(archive, evaluate, x0, budget, reservoir_size, sigma0, batch_size,
180 ind_domain, seed, executor, on_step, model)
181 return DDSCNFResult(result.archive, result.attempts, result.failures, result.reservoir_size,
182 model.fits, model.steps, model.predictions, model.fit_seconds, model.density_seconds)
DDS accounting with separate model training and density prediction counts.
Live passive archive and density search accounting.