24 """Provide a deterministic construction graph with terminal leaves.
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.
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()}
38 raise ValueError(
"The root needs at least one successor.")
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]), []
49 state = waiting.popleft()
51 for child
in edges[state]:
53 if indegree[child] == 0:
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)}
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)
65 """Return states in topological order starting at the root."""
70 """Return terminal states in topological order."""
88 """Train on a small named DAG with a fixed uniform backward policy.
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.
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.
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].")
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")
124 self.
_power = reward_power
126 self.
_rng = np.random.default_rng(seed)
127 self.
_generator = torch.Generator(device=
"cpu").manual_seed(seed)
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])
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)
142 nn.Linear(width, actions))
150 """Return the current training and audit work counters."""
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)
161 def _preference(self, value):
164 raise ValueError(
"Supply one preference.")
167 def _log_pf(self, states, prefs):
169 return self.
_forward(inputs).masked_fill(~self.
_mask[states], -float(
"inf")).log_softmax(dim=-1)
171 def _walk(self, prefs, exploration):
174 rows = torch.arange(n)
175 states = torch.zeros(n, dtype=torch.long)
176 finals = torch.empty_like(states)
178 with torch.no_grad():
180 probs = self.
_log_pf(states, prefs[rows]).exp()
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)
191 def _objective(self, terminal):
192 if terminal
not in self.
_known:
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]
200 def _rewards(self, terminal_ids, prefs):
201 values = np.stack([self.
_objective(int(i))
for i
in terminal_ids])
203 with np.errstate(divide=
"ignore"):
204 logs = np.logaddexp.reduce(np.log(values) + np.log(prefs), axis=-1)
208 def fit(self, preferences, *, updates, batch_size=64):
209 """Draw preferences uniformly from the supplied panel and train on sampled paths."""
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)
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.")
228 self.
_loss = float(loss.detach())
233 """Return a tuple sampled from the learned policy under one 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)
241 """Return exact terminal probabilities of the current forward policy."""
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))
250 for parent, probabilities
in zip(internal.tolist(), probs):
251 children = list(self.
graph._children[parent])
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}
259 """Measure previously unseen terminal rewards and return the desired probabilities."""
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))))
267 def illuminate(self, archive, evaluate, preferences, *, budget):
268 """Evaluate budget samples for (scalar fitness, descriptors) or None.
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.
274 _validate_grid(archive, empty=
False)
275 if archive.fitness_weights
is None:
276 archive._set_fitness_weights((1.,))
278 for step
in range(_positive_int(budget,
"budget")):
279 genome, = self.
sample(panel[step % len(panel)])
281 outcome = evaluate(genome)
282 if outcome
is not None:
283 fitness, descriptors = outcome
284 _offer(archive, _measurement(archive, ((fitness,), descriptors), (genome,)))