6"""Fit a neural descriptor density and reuse the standard DDS search loop."""
8from dataclasses
import dataclass, field
9from math
import log, pi
10from time
import perf_counter
14from .descriptor_cma
import DDSResult, _density_descent
15from .modern
import _positive_int
17__all__ = [
"DDSCNFResult",
"dds_cnf"]
21@dataclass(frozen=True)
23 """The first generation uses equal density ranks until measurements exist."""
27 density_evaluations: int
28 fit_seconds: float = field(compare=
False)
29 density_seconds: float = field(compare=
False)
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)
44 divergence += grad[:, column]
45 return velocity.detach(), divergence
47 step = -1. / integration_steps
48 correction = points.new_zeros(len(points))
49 for i
in range(integration_steps):
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
60 def __init__(self, torch, *, seed, width, fit_period, updates, batch_size, integration_steps, learning_rate):
64 self.
rng = torch.Generator(device=
"cpu").manual_seed(seed)
66 self.
last_fit = self.fits = self.steps = self.predictions = 0
69 def _initialize(self, samples):
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),
86 def _normalize(self, points):
89 def _fit(self, previous, iteration):
91 samples = torch.as_tensor(previous, dtype=torch.float64, device=
"cpu")
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)
110 torch.nn.utils.clip_grad_norm_(self.
network.parameters(), 10., error_if_nonfinite=
True)
116 def __call__(self, points, previous, iteration):
117 if not len(previous):
118 return np.zeros(len(points))
120 start = perf_counter()
121 with self.
torch.enable_grad():
122 self.
_fit(previous, iteration)
124 start = perf_counter()
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)
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.
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.
164 Requires pycma and PyTorch, available through the existing ``dms`` extra.
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])
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,
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.
_fit(self, previous, iteration)
_initialize(self, samples)
Live passive archive and density search accounting.