QDpy
Loading...
Searching...
No Matches
gflownet.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
6
7"""Train a GFlowNet and sample candidates for a QD archive."""
8
9from collections import Counter, deque
10from collections.abc import Mapping
11from dataclasses import dataclass
12
13import numpy as np
14from scipy.special import softmax
15
16from .modern import _positive_int
17from .task_search import _measurement, _offer, _validate_grid
18
19__all__ = ["ConstructiveDAG", "GFlowNetStats", "PreferenceGFlowNet"]
20
21
22
24 """Provide a deterministic construction graph with terminal leaves.
25
26 :param root: Hashable starting state.
27 :param successors: Ordered mapping from every state to its distinct
28 successors. Use an empty sequence for a terminal state. Multiple
29 paths may lead to the same state. All states must be reachable.
30 An explicit stop action can lead to a separate terminal node.
31 """
32
33 def __init__(self, root, successors):
34 if not isinstance(successors, Mapping) or root not in successors:
35 raise ValueError("Declare every state including the root.")
36 edges = {state: tuple(children) for state, children in successors.items()}
37 if not edges[root]:
38 raise ValueError("The root needs at least one successor.")
39 indegree = Counter()
40 for children in edges.values():
41 if len(set(children)) != len(children) or any(child not in edges for child in children):
42 raise ValueError("Each node needs distinct declared successors.")
43 indegree.update(children)
44 parents = indegree.copy()
45 if [state for state in edges if not indegree[state]] != [root]:
46 raise ValueError("The root must be the single source.")
47 waiting, order = deque([root]), []
48 while waiting:
49 state = waiting.popleft()
50 order.append(state)
51 for child in edges[state]:
52 indegree[child] -= 1
53 if indegree[child] == 0:
54 waiting.append(child)
55 if len(order) != len(edges):
56 raise ValueError("The graph must be acyclic and reachable from the root.")
57 numbering = {state: i for i, state in enumerate(order)}
58 self._states = tuple(order)
59 self._children = tuple(tuple(numbering[child] for child in edges[state]) for state in order)
60 self._parents = tuple(parents[state] for state in order)
61 self._terminal = tuple(i for i, children in enumerate(self._children) if not children)
62
63 @property
64 def states(self):
65 """Return states in topological order starting at the root."""
66 return self._states
67
68 @property
69 def terminals(self):
70 """Return terminal states in topological order."""
71 return tuple(self._states[i] for i in self._terminal)
72
73
74
75@dataclass(frozen=True)
77 """Cumulative optimizer updates, training trajectories and evaluator calls."""
78
79 updates: int = 0
80 trajectories: int = 0
81 reward_calls: int = 0
82 archive_calls: int = 0
83 last_loss: float | None = None
84
85
86
88 """Train on a small named DAG with a fixed uniform backward policy.
89
90 The terminal target is proportional to
91 (preference.dot(positive_objectives)) ** reward_power. The forward
92 network and trajectory normalizer both receive the preference.
93 Terminal objectives are cached across trajectories and audits.
94 Import PyTorch only when a sampler is constructed.
95
96 :param graph: ConstructiveDAG containing the legal transitions.
97 :param reward: Callback (terminal) returning the positive objective vector.
98 :param objectives: Length of the objective and preference vectors.
99 :param hidden_size: Width of the state embeddings and hidden layers.
100 :param reward_power: Temper the terminal reward with this positive power.
101 :param learning_rate: Adam step size.
102 :param exploration: Probability of a uniform transition during training.
103 :param seed: Private seed for network initialization and sampling.
104 """
105
106 def __init__(self, graph, reward, *, objectives, hidden_size=32, reward_power=1.,
107 learning_rate=.01, exploration=.15, seed=0):
108 if not isinstance(graph, ConstructiveDAG) or not callable(reward):
109 raise TypeError("Supply a ConstructiveDAG and a terminal reward callback.")
110 if (not np.isfinite(reward_power) or reward_power <= 0.
111 or not np.isfinite(learning_rate) or learning_rate <= 0.
112 or not 0. <= exploration <= 1.):
113 raise ValueError("Use positive finite scales and exploration in [0, 1].")
114 try:
115 import torch
116 from torch import nn
117 except ImportError as error:
118 raise ImportError("PreferenceGFlowNet requires PyTorch. Install torch or qdpy[rl].") from error
119 width = _positive_int(hidden_size, "hidden_size")
120 self.objectives = _positive_int(objectives, "objectives")
121 self.graph = graph
122 self._torch = torch
123 self._reward = reward
124 self._power = reward_power
125 self._exploration = exploration
126 self._rng = np.random.default_rng(seed)
127 self._generator = torch.Generator(device="cpu").manual_seed(seed)
128 self._known = {}
129 self._updates = self._trajectories = self._reward_calls = self._archive_calls = 0
130 self._loss = None
131
132 counts = tuple(map(len, graph._children))
133 actions = max(counts)
134 self._degree = torch.tensor(counts)
135 self._edges = torch.tensor([row + (-1,) * (actions - len(row)) for row in graph._children])
136 self._mask = self._edges >= 0
137 self._log_backward = -torch.log(torch.tensor(graph._parents, dtype=torch.float32).clamp_min_(1))
138 with torch.random.fork_rng(devices=[]):
139 torch.random.default_generator.manual_seed(seed)
140 self._embedding = nn.Embedding(len(counts), width)
141 self._forward = nn.Sequential(nn.Linear(width + self.objectives, width), nn.Tanh(),
142 nn.Linear(width, actions))
143 self._normalizer = nn.Sequential(nn.Linear(self.objectives, width), nn.Tanh(), nn.Linear(width, 1))
144 self._optimizer = torch.optim.Adam(
145 [*self._embedding.parameters(), *self._forward.parameters(), *self._normalizer.parameters()],
146 lr=learning_rate)
147
148 @property
149 def stats(self):
150 """Return the current training and audit work counters."""
151 return GFlowNetStats(self._updates, self._trajectories, self._reward_calls, self._archive_calls, self._loss)
152
153 def _preferences(self, values):
154 prefs = np.atleast_2d(np.asarray(values, dtype=float))
155 if (prefs.ndim != 2 or prefs.shape[1] != self.objectives or not len(prefs)
156 or not np.isfinite(prefs).all() or (prefs < 0.).any() or (prefs.max(axis=1) <= 0.).any()):
157 raise ValueError("Supply finite nonnegative preference vectors with positive total weight.")
158 scaled = prefs / prefs.max(axis=1, keepdims=True)
159 return scaled / scaled.sum(axis=1, keepdims=True)
160
161 def _preference(self, value):
162 prefs = self._preferences(value)
163 if len(prefs) != 1:
164 raise ValueError("Supply one preference.")
165 return prefs
166
167 def _log_pf(self, states, prefs):
168 inputs = self._torch.cat((self._embedding(states), prefs), dim=-1)
169 return self._forward(inputs).masked_fill(~self._mask[states], -float("inf")).log_softmax(dim=-1)
170
171 def _walk(self, prefs, exploration):
172 torch = self._torch
173 n = len(prefs)
174 rows = torch.arange(n)
175 states = torch.zeros(n, dtype=torch.long)
176 finals = torch.empty_like(states)
177 transitions = []
178 with torch.no_grad():
179 while rows.numel():
180 probs = self._log_pf(states, prefs[rows]).exp()
181 if exploration:
182 probs = (1 - exploration) * probs + exploration * self._mask[states] / self._degree[states, None]
183 picked = torch.multinomial(probs, 1, generator=self._generator).squeeze(1)
184 children = self._edges[states, picked]
185 transitions.append(torch.stack((rows, states, picked, children)))
186 terminal = self._degree[children] == 0
187 finals[rows[terminal]] = children[terminal]
188 rows, states = rows[~terminal], children[~terminal]
189 return finals, torch.cat(transitions, dim=1)
190
191 def _objective(self, terminal):
192 if terminal not in self._known:
193 self._reward_calls += 1
194 values = np.array(self._reward(self.graph.states[terminal]), dtype=float, copy=True)
195 if values.shape != (self.objectives,) or not np.isfinite(values).all() or (values <= 0.).any():
196 raise ValueError("A terminal reward must be a vector of strictly positive finite objectives.")
197 self._known[terminal] = values
198 return self._known[terminal]
199
200 def _rewards(self, terminal_ids, prefs):
201 values = np.stack([self._objective(int(i)) for i in terminal_ids])
202 # Log-space dot product keeps positive subnormal rewards usable.
203 with np.errstate(divide="ignore"):
204 logs = np.logaddexp.reduce(np.log(values) + np.log(prefs), axis=-1)
205 return logs * self._power
206
207
208 def fit(self, preferences, *, updates, batch_size=64):
209 """Draw preferences uniformly from the supplied panel and train on sampled paths."""
210 torch = self._torch
211 panel = self._preferences(preferences)
212 size = _positive_int(batch_size, "batch_size")
213 for _ in range(_positive_int(updates, "updates")):
214 weights = panel[self._rng.integers(len(panel), size=size)]
215 prefs = torch.as_tensor(weights, dtype=torch.float32)
216 finals, (rows, states, actions, children) = self._walk(prefs, self._exploration)
217 self._trajectories += size
218 log_reward = torch.as_tensor(self._rewards(finals, weights), dtype=torch.float32)
219 log_forward = self._log_pf(states, prefs[rows]).gather(1, actions[:, None]).squeeze(1)
220 log_ratio = torch.zeros(size).index_add(0, rows, log_forward - self._log_backward[children])
221 loss = (self._normalizer(prefs).squeeze(1) + log_ratio - log_reward).square().mean()
222 if not torch.isfinite(loss):
223 raise ValueError("Trajectory balance loss is nonfinite. Check the reward scale.")
224 self._optimizer.zero_grad(set_to_none=True)
225 loss.backward()
226 self._optimizer.step()
227 self._updates += 1
228 self._loss = float(loss.detach())
229 return self.stats
230
231
232 def sample(self, preference, *, size=1):
233 """Return a tuple sampled from the learned policy under one preference."""
234 weights = self._preference(preference)
235 prefs = self._torch.as_tensor(weights, dtype=self._torch.float32).expand(_positive_int(size, "size"), -1)
236 finals, _ = self._walk(prefs, 0.)
237 return tuple(self.graph.states[int(i)] for i in finals)
238
239
240 def distribution(self, preference):
241 """Return exact terminal probabilities of the current forward policy."""
242 weights = self._preference(preference)
243 torch = self._torch
244 internal = self._degree.nonzero().flatten()
245 prefs = torch.as_tensor(weights, dtype=torch.float32).expand(len(internal), -1)
246 with torch.no_grad():
247 probs = self._log_pf(internal, prefs).exp().numpy().astype(float)
248 mass = np.zeros(len(self.graph.states))
249 mass[0] = 1.
250 for parent, probabilities in zip(internal.tolist(), probs):
251 children = list(self.graph._children[parent])
252 # Normalize after the float32 probability vector is converted to float64.
253 outgoing = probabilities[:len(children)]
254 mass[children] += mass[parent] * outgoing / outgoing.sum()
255 return {self.graph.states[i]: float(mass[i]) for i in self.graph._terminal}
256
257
258 def target_distribution(self, preference):
259 """Measure previously unseen terminal rewards and return the desired probabilities."""
260 weights = self._preference(preference)
261 logs = self._rewards(self.graph._terminal, weights)
262 if not np.isfinite(logs).all():
263 raise ValueError("The target log rewards must be finite.")
264 return dict(zip(self.graph.terminals, map(float, softmax(logs))))
265
266
267 def illuminate(self, archive, evaluate, preferences, *, budget):
268 """Evaluate budget samples for (scalar fitness, descriptors) or None.
269
270 Cycle preferences in the given order. Archive measurements are
271 independent of the training reward cache. Supply a parentless
272 best-only Grid or CVTGrid, optionally populated.
273 """
274 _validate_grid(archive, empty=False)
275 if archive.fitness_weights is None:
276 archive._set_fitness_weights((1.,))
277 panel = self._preferences(preferences)
278 for step in range(_positive_int(budget, "budget")):
279 genome, = self.sample(panel[step % len(panel)])
280 self._archive_calls += 1
281 outcome = evaluate(genome)
282 if outcome is not None:
283 fitness, descriptors = outcome
284 _offer(archive, _measurement(archive, ((fitness,), descriptors), (genome,)))
285 return archive
Define a finite rooted graph of legal construction steps.
Definition gflownet.py:23
Report the distinct costs of sampler training and archive evaluation.
Definition gflownet.py:76
Learn a multi-objective conditional sampler with trajectory balance.
Definition gflownet.py:87
sample(self, preference, *, size=1)
Generate new terminal objects without reward evaluations.
Definition gflownet.py:232
illuminate(self, archive, evaluate, preferences, *, budget)
Fill a native QD archive with measured GFlowNet proposals.
Definition gflownet.py:267
distribution(self, preference)
Sum learned path probabilities reaching each terminal.
Definition gflownet.py:240
_rewards(self, terminal_ids, prefs)
Definition gflownet.py:200
target_distribution(self, preference)
Enumerate the normalized target for a small graph.
Definition gflownet.py:258
fit(self, preferences, *, updates, batch_size=64)
Train on complete paths under supplied preferences.
Definition gflownet.py:208