QDpy
Loading...
Searching...
No Matches
subgoal_mcts.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Deterministic, finite-action QD-guided subgoal Monte Carlo tree search."""
7
8from dataclasses import dataclass, field
9from math import isfinite, log1p, sqrt
10from operator import index
11
12import numpy as np
13
14from .modern import _positive_int
15
16__all__ = ["MCTSPlan", "MCTSResult", "qd_subgoal_mcts", "primitive_mcts"]
17
18
19
20@dataclass(frozen=True)
22 """Hold the actual successor, reward sequence, and terminal flag."""
23
24 actions: tuple
25 final_state: object
26 rewards: tuple[float, ...]
27 terminated: bool
28
29 @property
30 def return_(self):
31 """Return the undiscounted sum of rewards."""
32 return sum(self.rewards)
33
34
35
36@dataclass(frozen=True)
38 """Return the best observed path and the published subgoals at the root."""
39
40 plan: MCTSPlan
41 root_subgoals: tuple[MCTSPlan, ...]
42 simulator_calls: int
43 low_level_calls: int
44 simulations: int
45 published_subgoals: int
46
47
48def _return(rewards, discount):
49 value = 0.
50 for reward in reversed(rewards):
51 value = reward + discount * value
52 return value
53
54
55def _backup(node, value):
56 node.visits += 1
57 node.total += value
58
59
60def _ucb(node, children, exploration, value):
61 scale = log1p(node.visits)
62 return max(children, key=lambda edge: value(edge) + exploration * sqrt(scale / edge.node.visits))
63
64
65@dataclass
67 state: object
68 terminated: bool
69 visits: int = 0
70 total: float = 0.
71 children: list = field(default_factory=list)
72 untried: list | None = None
73 exhausted: bool = False
74 descriptor: np.ndarray | None = None
75
76
77@dataclass
78class _Action:
79 action: object
80 reward: float
81 node: _Primitive
82
83
84@dataclass
86 state: object
87 terminated: bool
88 visits: int = 0
89 total: float = 0.
90 children: list | None = None
91 local: _Primitive | None = None
92 candidates: list = field(default_factory=list)
93 exhausted: bool = False
94
95
96@dataclass
98 plan: MCTSPlan
99 node: _Subgoal
100
101
102def _normalized(values):
103 span = values.max() - values.min()
104 return (values - values.min()) / span if span else np.zeros_like(values)
105
106
107
108def _select_subgoals(candidates, descriptors, count, neighbors, reward_weight, discount):
109 rewards = np.asarray([_return(plan.rewards, discount) for plan in candidates])
110 first = int(np.argmax(rewards))
111 chosen = [first]
112 remaining = [i for i in range(len(candidates)) if i != first]
113 while remaining and len(chosen) < count:
114 distance = np.hypot.reduce(descriptors[remaining, None, :] - descriptors[None, chosen, :], axis=2)
115 if not np.isfinite(distance).all():
116 raise ValueError("Descriptor distances must be finite.")
117 closest = np.argsort(distance, axis=1, kind="stable")[:, :neighbors]
118 novelty = np.take_along_axis(distance, closest, axis=1).mean(axis=1)
119 better = (rewards[remaining, None] > rewards[np.asarray(chosen)[closest]]).mean(axis=1)
120 scores = (1. - reward_weight) * _normalized(novelty) + reward_weight * _normalized(better)
121 chosen.append(remaining.pop(int(np.argmax(scores))))
122 return [candidates[i] for i in chosen]
123
124
126 """Own one planning call and charge every transition at the simulator boundary."""
127
128 def __init__(self, actions, simulate, budget, horizon, discount, exploration, seed):
129 if not callable(actions) or not callable(simulate):
130 raise TypeError("actions and simulate must be callable.")
131 self.actions, self.simulate = actions, simulate
132 self.budget = index(budget)
133 self.horizon = _positive_int(horizon, "horizon")
134 if self.budget < 0 or not 0. < discount <= 1. or not 0. <= exploration < np.inf:
135 raise ValueError("Require nonnegative budget and exploration, and a discount in (0, 1].")
136 self.discount, self.exploration = discount, exploration
137 self.rng = np.random.default_rng(seed)
138 self.calls = self.low_calls = self.simulations = self.published = 0
139 self.best = self._best_key = None
140
141 def _step(self, state, action, low_level):
142 self.calls += 1
143 self.low_calls += low_level
144 successor, reward, terminal = self.simulate(state, action)
145 reward = float(reward)
146 if not isfinite(reward):
147 raise ValueError("The simulator must return a finite reward.")
148 return successor, reward, bool(terminal)
149
150 def _visit_path(self, root, limit, distance=None):
151 """Extend and traverse a primitive tree while spending only uncached transitions."""
152 nodes = [root]
153 actions, rewards, returns = [], [], []
154 node = root
155 reached_boundary = False
156
157 def immediate(edge):
158 return edge.reward if distance is None else distance(edge.node) - distance(node)
159
160 for _ in range(limit):
161 if node.terminated:
162 reached_boundary = True
163 break
164 if node.untried is None:
165 node.untried = list(self.actions(node.state))
166 if node.untried:
167 if self.calls == self.budget:
168 break
169 slot = int(self.rng.integers(len(node.untried)))
170 action = node.untried.pop(slot)
171 successor, reward, terminal = self._step(node.state, action, distance is not None)
172 edge = _Action(action, reward, _Primitive(successor, terminal))
173 node.children.append(edge)
174 else:
175 available = [edge for edge in node.children if not edge.node.exhausted]
176 if not available:
177 reached_boundary = True
178 break
179 edge = _ucb(node, available, self.exploration, lambda child:
180 immediate(child) + self.discount * child.node.total / child.node.visits)
181
182 actions.append(edge.action)
183 rewards.append(edge.reward)
184 returns.append(immediate(edge))
185 node = edge.node
186 nodes.append(node)
187
188 reached_boundary |= node.terminated or len(actions) == limit
189 if reached_boundary:
190 node.exhausted = True
191 _backup(node, 0.)
192 value = 0.
193 for parent, reward in zip(reversed(nodes[:-1]), reversed(returns), strict=True):
194 value = reward + self.discount * value
195 _backup(parent, value)
196 parent.exhausted = not parent.untried and all(edge.node.exhausted for edge in parent.children)
197 return MCTSPlan(tuple(actions), node.state, tuple(rewards), node.terminated), reached_boundary
198
199 def _rollout(self, start, terminal, limit):
200 actions, rewards = [], []
201 state = start
202 dead_end = False
203 for _ in range(limit):
204 if terminal or self.calls == self.budget:
205 break
206 choices = tuple(self.actions(state))
207 if not choices:
208 dead_end = True
209 break
210 action = choices[int(self.rng.integers(len(choices)))]
211 state, reward, terminal = self._step(state, action, False)
212 actions.append(action)
213 rewards.append(reward)
214 plan = MCTSPlan(tuple(actions), state, tuple(rewards), terminal)
215 return plan, terminal or dead_end or len(actions) == limit
216
217 def _report(self, start, terminated, root_subgoals=()):
218 plan = self.best or MCTSPlan((), start, (), terminated)
219 return MCTSResult(plan, root_subgoals, self.calls, self.low_calls, self.simulations, self.published)
220
221 def _consider(self, plan, complete):
222 if plan.actions:
223 score = _return(plan.rewards, self.discount)
224 key = complete, score, plan.terminated, -len(plan.actions)
225 if self.best is None or key > self._best_key:
226 self.best, self._best_key = plan, key
227
228
230 def __init__(self, actions, simulate, budget, horizon, discount, exploration, seed,
231 describe, macro_steps, probes, subgoals, neighbors, reward_weight):
232 super().__init__(actions, simulate, budget, horizon, discount, exploration, seed)
233 if not callable(describe) or not 0. <= reward_weight <= 1.:
234 raise ValueError("Require a callable descriptor and a reward_weight in [0, 1].")
235 self.describe = describe
236 self.macro_steps = _positive_int(macro_steps, "macro_steps")
237 self.probes = _positive_int(probes, "probes")
238 self.subgoals = _positive_int(subgoals, "subgoals")
239 self.neighbors = _positive_int(neighbors, "neighbors")
240 self.reward_weight = reward_weight
241 self.shape = None
242
243 def _features(self, state):
244 point = np.array(self.describe(state), dtype=float, copy=True)
245 if point.ndim != 1 or not len(point) or not np.isfinite(point).all() or (
246 self.shape is not None and self.shape != point.shape):
247 raise ValueError("Describe each state with a fixed nonempty finite vector.")
248 self.shape = point.shape
249 return point
250
251 def _distance(self, node, origin):
252 if node.descriptor is None:
253 node.descriptor = self._features(node.state)
254 value = float(np.hypot.reduce(node.descriptor - origin))
255 if not isfinite(value):
256 raise ValueError("Descriptor distances must be finite.")
257 return value
258
259 def _discover(self, node, left):
260 if node.local is None:
261 node.local = _Primitive(node.state, node.terminated)
262 node.local.descriptor = self._features(node.state)
263 origin = node.local.descriptor
264 trial, complete = self._visit_path(node.local, min(left, self.macro_steps),
265 lambda point: self._distance(point, origin))
266 if trial.actions and complete:
267 node.candidates.append(trial)
268 if len(node.candidates) >= self.probes or node.local.exhausted:
269 if node.candidates:
270 descriptors = np.asarray([self._features(plan.final_state) for plan in node.candidates])
271 selected = _select_subgoals(node.candidates, descriptors, self.subgoals, self.neighbors,
272 self.reward_weight, self.discount)
273 node.children = [
274 _MacroAction(plan, _Subgoal(plan.final_state, plan.terminated,
275 exhausted=plan.terminated or len(plan.actions) == left))
276 for plan in selected
277 ]
278 self.published += len(selected)
279 else:
280 node.children = []
281 node.local = None
282 node.candidates.clear()
283 return trial
284
285 def plan(self, start, terminated):
286 root = _Subgoal(start, terminated, exhausted=terminated)
287 while self.calls < self.budget and not root.exhausted:
288 node = root
289 actions, rewards, path = [], [], []
290 while True:
291 path.append((node, len(actions)))
292 if node.children is None:
293 probe = self._discover(node, self.horizon - len(actions))
294 actions.extend(probe.actions)
295 rewards.extend(probe.rewards)
296 tail, complete = self._rollout(probe.final_state, probe.terminated, self.horizon - len(actions))
297 actions.extend(tail.actions)
298 rewards.extend(tail.rewards)
299 self._consider(MCTSPlan(tuple(actions), tail.final_state, tuple(rewards), tail.terminated), complete)
300 break
301 edges = [edge for edge in node.children if not edge.node.exhausted]
302 if not edges:
303 break
304 edge = next((edge for edge in edges if edge.node.visits == 0), None)
305 if edge is None:
306 edge = _ucb(node, edges, self.exploration, lambda child:
307 _return(child.plan.rewards, self.discount) + self.discount ** len(child.plan.actions)
308 * child.node.total / child.node.visits)
309 actions.extend(edge.plan.actions)
310 rewards.extend(edge.plan.rewards)
311 node = edge.node
312 self.simulations += 1
313 for ancestor, start_index in reversed(path):
314 _backup(ancestor, _return(rewards[start_index:], self.discount))
315 ancestor.exhausted = ancestor.children is not None and all(
316 edge.node.exhausted for edge in ancestor.children)
317 return self._report(start, terminated, tuple(edge.plan for edge in root.children or ()))
318
319
320
321def primitive_mcts(start, *, actions, simulate, budget, horizon, discount=.99, exploration=1.4,
322 start_terminated=False, seed=0):
323 """Run the primitive-action control with cached deterministic transitions.
324
325 See :func:`qd_subgoal_mcts` for the simulator contract. The same
326 horizon, reward discount, and simulator-call cap apply. Tree
327 traversals pick an untried action uniformly or use UCB over
328 existing children. Search ends early if the finite tree is exhausted.
329 """
330 search = _Search(actions, simulate, budget, horizon, discount, exploration, seed)
331 root = _Primitive(start, bool(start_terminated), exhausted=bool(start_terminated))
332 while search.calls < search.budget and not root.exhausted:
333 trial, complete = search._visit_path(root, search.horizon)
334 search._consider(trial, complete)
335 search.simulations += 1
336 return search._report(start, bool(start_terminated))
337
338
339
340def qd_subgoal_mcts(start, *, actions, simulate, describe, budget, horizon, macro_steps=3,
341 probes=8, subgoals=3, neighbors=3, reward_weight=.5, discount=.99,
342 exploration=1.4, start_terminated=False, seed=0):
343 """Interleave local trajectory discovery with a high-level subgoal tree.
344
345 Each visit to an unexpanded macro node samples one path in its
346 low-level tree. Local UCB uses discounted distance gains from that
347 node. Once enough paths are available, keep a small set using
348 novelty and local reward comparisons. High-level UCB backs up task
349 rewards and uses the sampled endpoints for continuation rollouts.
350 Return the best complete primitive path under discounted reward,
351 or a measured prefix if the budget allowed only partial paths.
352
353 :param start: Initial simulator snapshot.
354 :param actions: Callable yielding available actions for a snapshot.
355 :param simulate: Pure deterministic callback (state, action) returning
356 (successor, finite reward, terminated). Treat snapshots as immutable.
357 :param describe: Callable returning a fixed nonempty numeric state descriptor.
358 :param budget: Maximum total calls to simulate, including low-level search.
359 :param horizon: Maximum primitive steps in any searched path.
360 :param macro_steps: Target primitive length of a subgoal trajectory.
361 Terminal and dead-end paths can be shorter.
362 :param probes: Complete low-level samples before publishing subgoals,
363 or fewer if the local tree is exhausted.
364 :param subgoals: Maximum number of macro-actions published per node.
365 :param neighbors: Nearest selected endpoints used in the local comparison.
366 :param reward_weight: Weight of local competition relative to novelty.
367 :param discount: Per-primitive-step reward and distance discount.
368 :param exploration: UCB exploration coefficient in both trees.
369 :param start_terminated: Whether the initial snapshot is already terminal.
370 :param seed: Private action-selection and rollout seed.
371 """
372 search = _SubgoalSearch(actions, simulate, budget, horizon, discount, exploration, seed,
373 describe, macro_steps, probes, subgoals, neighbors, reward_weight)
374 return search.plan(start, bool(start_terminated))
A measured simulator path, with its primitive actions and rewards.
A plan and its simulator transition costs, including the low-level search.
_step(self, state, action, low_level)
_report(self, start, terminated, root_subgoals=())
_rollout(self, start, terminal, limit)
_visit_path(self, root, limit, distance=None)