Source code for qdpy.algorithms.gflownet

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Preference-conditioned trajectory balance on constructive DAGs.
# @see https://proceedings.mlr.press/v202/jain23a.html
# @see https://doi.org/10.48550/arXiv.2201.13259

"""Train a GFlowNet and sample candidates for a QD archive."""

from collections import Counter, deque
from collections.abc import Mapping
from dataclasses import dataclass

import numpy as np
from scipy.special import softmax

from .modern import _positive_int
from .task_search import _measurement, _offer, _validate_grid

__all__ = ["ConstructiveDAG", "GFlowNetStats", "PreferenceGFlowNet"]


## @brief Define a finite rooted graph of legal construction steps.
[docs] class ConstructiveDAG: """Provide a deterministic construction graph with terminal leaves. :param root: Hashable starting state. :param successors: Ordered mapping from every state to its distinct successors. Use an empty sequence for a terminal state. Multiple paths may lead to the same state. All states must be reachable. An explicit stop action can lead to a separate terminal node. """ def __init__(self, root, successors): if not isinstance(successors, Mapping) or root not in successors: raise ValueError("Declare every state including the root.") edges = {state: tuple(children) for state, children in successors.items()} if not edges[root]: raise ValueError("The root needs at least one successor.") indegree = Counter() for children in edges.values(): if len(set(children)) != len(children) or any(child not in edges for child in children): raise ValueError("Each node needs distinct declared successors.") indegree.update(children) parents = indegree.copy() if [state for state in edges if not indegree[state]] != [root]: raise ValueError("The root must be the single source.") waiting, order = deque([root]), [] while waiting: state = waiting.popleft() order.append(state) for child in edges[state]: indegree[child] -= 1 if indegree[child] == 0: waiting.append(child) if len(order) != len(edges): raise ValueError("The graph must be acyclic and reachable from the root.") numbering = {state: i for i, state in enumerate(order)} self._states = tuple(order) self._children = tuple(tuple(numbering[child] for child in edges[state]) for state in order) self._parents = tuple(parents[state] for state in order) self._terminal = tuple(i for i, children in enumerate(self._children) if not children) @property def states(self): """Return states in topological order starting at the root.""" return self._states @property def terminals(self): """Return terminal states in topological order.""" return tuple(self._states[i] for i in self._terminal)
## @brief Report the distinct costs of sampler training and archive evaluation.
[docs] @dataclass(frozen=True) class GFlowNetStats: """Cumulative optimizer updates, training trajectories and evaluator calls.""" updates: int = 0 trajectories: int = 0 reward_calls: int = 0 archive_calls: int = 0 last_loss: float | None = None
## @brief Learn a multi-objective conditional sampler with trajectory balance.
[docs] class PreferenceGFlowNet: """Train on a small named DAG with a fixed uniform backward policy. The terminal target is proportional to (preference.dot(positive_objectives)) ** reward_power. The forward network and trajectory normalizer both receive the preference. Terminal objectives are cached across trajectories and audits. Import PyTorch only when a sampler is constructed. :param graph: ConstructiveDAG containing the legal transitions. :param reward: Callback (terminal) returning the positive objective vector. :param objectives: Length of the objective and preference vectors. :param hidden_size: Width of the state embeddings and hidden layers. :param reward_power: Temper the terminal reward with this positive power. :param learning_rate: Adam step size. :param exploration: Probability of a uniform transition during training. :param seed: Private seed for network initialization and sampling. """ def __init__(self, graph, reward, *, objectives, hidden_size=32, reward_power=1., learning_rate=.01, exploration=.15, seed=0): if not isinstance(graph, ConstructiveDAG) or not callable(reward): raise TypeError("Supply a ConstructiveDAG and a terminal reward callback.") if (not np.isfinite(reward_power) or reward_power <= 0. or not np.isfinite(learning_rate) or learning_rate <= 0. or not 0. <= exploration <= 1.): raise ValueError("Use positive finite scales and exploration in [0, 1].") try: import torch from torch import nn except ImportError as error: raise ImportError("PreferenceGFlowNet requires PyTorch. Install torch or qdpy[rl].") from error width = _positive_int(hidden_size, "hidden_size") self.objectives = _positive_int(objectives, "objectives") self.graph = graph self._torch = torch self._reward = reward self._power = reward_power self._exploration = exploration self._rng = np.random.default_rng(seed) self._generator = torch.Generator(device="cpu").manual_seed(seed) self._known = {} self._updates = self._trajectories = self._reward_calls = self._archive_calls = 0 self._loss = None counts = tuple(map(len, graph._children)) actions = max(counts) self._degree = torch.tensor(counts) self._edges = torch.tensor([row + (-1,) * (actions - len(row)) for row in graph._children]) self._mask = self._edges >= 0 self._log_backward = -torch.log(torch.tensor(graph._parents, dtype=torch.float32).clamp_min_(1)) with torch.random.fork_rng(devices=[]): torch.random.default_generator.manual_seed(seed) self._embedding = nn.Embedding(len(counts), width) self._forward = nn.Sequential(nn.Linear(width + self.objectives, width), nn.Tanh(), nn.Linear(width, actions)) self._normalizer = nn.Sequential(nn.Linear(self.objectives, width), nn.Tanh(), nn.Linear(width, 1)) self._optimizer = torch.optim.Adam( [*self._embedding.parameters(), *self._forward.parameters(), *self._normalizer.parameters()], lr=learning_rate) @property def stats(self): """Return the current training and audit work counters.""" return GFlowNetStats(self._updates, self._trajectories, self._reward_calls, self._archive_calls, self._loss) def _preferences(self, values): prefs = np.atleast_2d(np.asarray(values, dtype=float)) if (prefs.ndim != 2 or prefs.shape[1] != self.objectives or not len(prefs) or not np.isfinite(prefs).all() or (prefs < 0.).any() or (prefs.max(axis=1) <= 0.).any()): raise ValueError("Supply finite nonnegative preference vectors with positive total weight.") scaled = prefs / prefs.max(axis=1, keepdims=True) return scaled / scaled.sum(axis=1, keepdims=True) def _preference(self, value): prefs = self._preferences(value) if len(prefs) != 1: raise ValueError("Supply one preference.") return prefs def _log_pf(self, states, prefs): inputs = self._torch.cat((self._embedding(states), prefs), dim=-1) return self._forward(inputs).masked_fill(~self._mask[states], -float("inf")).log_softmax(dim=-1) def _walk(self, prefs, exploration): torch = self._torch n = len(prefs) rows = torch.arange(n) states = torch.zeros(n, dtype=torch.long) finals = torch.empty_like(states) transitions = [] with torch.no_grad(): while rows.numel(): probs = self._log_pf(states, prefs[rows]).exp() if exploration: probs = (1 - exploration) * probs + exploration * self._mask[states] / self._degree[states, None] picked = torch.multinomial(probs, 1, generator=self._generator).squeeze(1) children = self._edges[states, picked] transitions.append(torch.stack((rows, states, picked, children))) terminal = self._degree[children] == 0 finals[rows[terminal]] = children[terminal] rows, states = rows[~terminal], children[~terminal] return finals, torch.cat(transitions, dim=1) def _objective(self, terminal): if terminal not in self._known: self._reward_calls += 1 values = np.array(self._reward(self.graph.states[terminal]), dtype=float, copy=True) if values.shape != (self.objectives,) or not np.isfinite(values).all() or (values <= 0.).any(): raise ValueError("A terminal reward must be a vector of strictly positive finite objectives.") self._known[terminal] = values return self._known[terminal] def _rewards(self, terminal_ids, prefs): values = np.stack([self._objective(int(i)) for i in terminal_ids]) # Log-space dot product keeps positive subnormal rewards usable. with np.errstate(divide="ignore"): logs = np.logaddexp.reduce(np.log(values) + np.log(prefs), axis=-1) return logs * self._power ## @brief Train on complete paths under supplied preferences.
[docs] def fit(self, preferences, *, updates, batch_size=64): """Draw preferences uniformly from the supplied panel and train on sampled paths.""" torch = self._torch panel = self._preferences(preferences) size = _positive_int(batch_size, "batch_size") for _ in range(_positive_int(updates, "updates")): weights = panel[self._rng.integers(len(panel), size=size)] prefs = torch.as_tensor(weights, dtype=torch.float32) finals, (rows, states, actions, children) = self._walk(prefs, self._exploration) self._trajectories += size log_reward = torch.as_tensor(self._rewards(finals, weights), dtype=torch.float32) log_forward = self._log_pf(states, prefs[rows]).gather(1, actions[:, None]).squeeze(1) log_ratio = torch.zeros(size).index_add(0, rows, log_forward - self._log_backward[children]) loss = (self._normalizer(prefs).squeeze(1) + log_ratio - log_reward).square().mean() if not torch.isfinite(loss): raise ValueError("Trajectory balance loss is nonfinite. Check the reward scale.") self._optimizer.zero_grad(set_to_none=True) loss.backward() self._optimizer.step() self._updates += 1 self._loss = float(loss.detach()) return self.stats
## @brief Generate new terminal objects without reward evaluations.
[docs] def sample(self, preference, *, size=1): """Return a tuple sampled from the learned policy under one preference.""" weights = self._preference(preference) prefs = self._torch.as_tensor(weights, dtype=self._torch.float32).expand(_positive_int(size, "size"), -1) finals, _ = self._walk(prefs, 0.) return tuple(self.graph.states[int(i)] for i in finals)
## @brief Sum learned path probabilities reaching each terminal.
[docs] def distribution(self, preference): """Return exact terminal probabilities of the current forward policy.""" weights = self._preference(preference) torch = self._torch internal = self._degree.nonzero().flatten() prefs = torch.as_tensor(weights, dtype=torch.float32).expand(len(internal), -1) with torch.no_grad(): probs = self._log_pf(internal, prefs).exp().numpy().astype(float) mass = np.zeros(len(self.graph.states)) mass[0] = 1. for parent, probabilities in zip(internal.tolist(), probs): children = list(self.graph._children[parent]) # Normalize after the float32 probability vector is converted to float64. outgoing = probabilities[:len(children)] mass[children] += mass[parent] * outgoing / outgoing.sum() return {self.graph.states[i]: float(mass[i]) for i in self.graph._terminal}
## @brief Enumerate the normalized target for a small graph.
[docs] def target_distribution(self, preference): """Measure previously unseen terminal rewards and return the desired probabilities.""" weights = self._preference(preference) logs = self._rewards(self.graph._terminal, weights) if not np.isfinite(logs).all(): raise ValueError("The target log rewards must be finite.") return dict(zip(self.graph.terminals, map(float, softmax(logs))))
## @brief Fill a native QD archive with measured GFlowNet proposals.
[docs] def illuminate(self, archive, evaluate, preferences, *, budget): """Evaluate budget samples for (scalar fitness, descriptors) or None. Cycle preferences in the given order. Archive measurements are independent of the training reward cache. Supply a parentless best-only Grid or CVTGrid, optionally populated. """ _validate_grid(archive, empty=False) if archive.fitness_weights is None: archive._set_fitness_weights((1.,)) panel = self._preferences(preferences) for step in range(_positive_int(budget, "budget")): genome, = self.sample(panel[step % len(panel)]) self._archive_calls += 1 outcome = evaluate(genome) if outcome is not None: fitness, descriptors = outcome _offer(archive, _measurement(archive, ((fitness,), descriptors), (genome,))) return archive