QDpy
Loading...
Searching...
No Matches
portfolio_mcts.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Search over weighted action scripts, then illuminate the resulting planners."""
7
8from dataclasses import dataclass, field
9from math import isfinite, log, log1p, sqrt
10
11import numpy as np
12
13from ._population import _attempt_budget, _finite_vector
14from .modern import _positive_int
15from .subgoal_mcts import MCTSPlan, _Search, _backup, _return
16from .task_search import _measurement, _offer, _validate_grid
17
18__all__ = ["PortfolioMCTSResult", "PortfolioQDResult", "portfolio_mcts", "portfolio_map_elites"]
19
20
21
22@dataclass(frozen=True)
24 """The root action list is in weighted script priority order."""
25
26 plan: MCTSPlan
27 simulator_calls: int
28 simulations: int
29 root_actions: tuple
30 root_open: int
31 root_expanded: int
32
33
34
35@dataclass(frozen=True)
37 """A measurement attempt evaluates the whole scenario panel."""
38
39 archive: object
40 evaluations: int
41 plans: int
42 simulator_calls: int
43 admissions: int
44
45
46@dataclass
47class _Node:
48 state: object
49 terminated: bool = False
50 visits: int = 0
51 total: float = 0.
52 ranked: tuple | None = None
53 edges: list = field(default_factory=list)
54
55
56@dataclass
57class _Edge:
58 action: object
59 heuristic: float
60 reward: float
61 node: _Node
62
63
65 def __init__(self, scripts, weights, simulate, budget, horizon, discount, exploration,
66 fraction, rate, unprune_at, bias, seed):
67 super().__init__(self._rank, simulate, budget, horizon, discount, exploration, seed)
68 self.scripts, self.weights = scripts, weights
69 self.fraction, self.rate, self.unprune_at, self.bias = fraction, rate, unprune_at, bias
70
71 def _rank(self, state):
72 priority = {}
73 for script, weight in zip(self.scripts, self.weights):
74 for action, value in script(state):
75 value = float(value)
76 if not 0 <= value <= 1.:
77 raise ValueError("Script action scores must be finite and in [0, 1].")
78 priority[action] = max(priority.get(action, 0.), value * weight)
79 return tuple(sorted(priority.items(), key=lambda row: -row[1]))
80
81 def _allowed(self, node):
82 n = len(node.ranked or ())
83 if n == 0:
84 return 0
85 initial = max(1, int(np.ceil(self.fraction * n)))
86 if node.visits < self.unprune_at:
87 return initial
88 extra = 1 + int(log(node.visits / self.unprune_at) / log(self.rate))
89 return min(n, initial + extra)
90
91 def _tree_phase(self, root):
92 node = root
93 nodes, actions, rewards = [root], [], []
94 for _ in range(self.horizon):
95 if node.terminated:
96 break
97 if node.ranked is None:
98 node.ranked = self._rank(node.state)
99 limit = self._allowed(node)
100 if not limit:
101 break
102 new_edge = len(node.edges) < limit
103 if new_edge:
104 action, heuristic = node.ranked[len(node.edges)]
105 state, reward, terminal = self._step(node.state, action, False)
106 edge = _Edge(action, heuristic, reward, _Node(state, terminal))
107 node.edges.append(edge)
108 else:
109 edge = max(node.edges, key=lambda entry: (
110 entry.reward + self.discount * entry.node.total / entry.node.visits
111 + self.exploration * sqrt(log1p(node.visits) / entry.node.visits)
112 + self.bias * entry.heuristic / (1 + entry.node.visits)
113 ))
114 actions.append(edge.action)
115 rewards.append(edge.reward)
116 node = edge.node
117 nodes.append(node)
118 if new_edge:
119 break
120 return nodes, actions, rewards
121
122 def simulate_one(self, root):
123 nodes, actions, rewards = self._tree_phase(root)
124 state, term = nodes[-1].state, nodes[-1].terminated
125 tree_steps = len(rewards)
126 # A rollout samples only actions proposed by the scripts.
127 while tree_steps and len(actions) < self.horizon and self.calls < self.budget and not term:
128 options = self._rank(state)
129 if not options:
130 break
131 weights = np.asarray([value for _, value in options])
132 slot = self.rng.choice(len(options), p=weights / weights.sum() if weights.sum() else None)
133 action = options[slot][0]
134 state, reward, term = self._step(state, action, False)
135 actions.append(action)
136 rewards.append(reward)
137 if not actions:
138 return False
139 leaf_value = _return(rewards[tree_steps:], self.discount)
140 _backup(nodes[-1], leaf_value)
141 for i in range(tree_steps - 1, -1, -1):
142 leaf_value = rewards[i] + self.discount * leaf_value
143 _backup(nodes[i], leaf_value)
144 if not isfinite(leaf_value):
145 raise ValueError("The discounted plan return overflowed.")
146 candidate = MCTSPlan(tuple(actions), state, tuple(rewards), term)
147 key = (leaf_value, term, -len(actions))
148 if self.best is None or key > self._best_key:
149 self.best, self._best_key = candidate, key
150 self.simulations += 1
151 return True
152
153
154
170def portfolio_mcts(start, *, scripts, weights, simulate, budget, horizon, simulations=None,
171 initial_fraction=.5, unprune_at=4, unprune_rate=2., exploration=1.414,
172 progressive_bias=1., discount=1., seed=0):
173 """Rank duplicate suggestions by their strongest weighted score.
174
175 At each node, start with the most preferred fraction of actions and
176 gradually expose the rest as visits accumulate. Score visited actions
177 by UCB with a decaying script bias. Cache deterministic tree edges,
178 and charge every actual simulator call, including rollouts.
179 """
180 scripts = tuple(scripts)
181 weights = _finite_vector(weights, "Script weights", len(scripts))
182 if (not all(map(callable, scripts)) or not all(0 <= value <= 1. for value in weights)
183 or not (0 < initial_fraction <= 1 and 1 < unprune_rate < np.inf)
184 or not 0 <= progressive_bias < np.inf):
185 raise ValueError("Use callable scripts, weights in [0, 1], and finite exploration settings.")
186 budget = _attempt_budget(budget)
187 repeats = budget if simulations is None else _attempt_budget(simulations)
188 unprune_at = _positive_int(unprune_at, "unprune_at")
189 planner = _Planner(scripts, weights, simulate, budget, horizon, discount, exploration,
190 initial_fraction, unprune_rate, unprune_at, progressive_bias, seed)
191 root = _Node(start)
192 for _ in range(repeats):
193 if planner.calls >= budget or not planner.simulate_one(root):
194 break
195 plan = MCTSPlan((), start, (), False) if planner.best is None else planner.best
196 return PortfolioMCTSResult(plan, planner.calls, planner.simulations, tuple(a for a, _ in root.ranked or ()),
197 planner._allowed(root), len(root.edges))
198
199
200
213def portfolio_map_elites(archive, scenarios, *, scripts, simulate, summarize, budget, plan_budget, horizon,
214 random_initial=8, planner_options=None, seed=0):
215 """Seed with one active script at a time and then mutate one weight per proposal."""
216 _validate_grid(archive)
217 if not callable(summarize) or not callable(simulate):
218 raise TypeError("Supply callable simulator and plan summarizer.")
219 budget, random_initial = _attempt_budget(budget), _attempt_budget(random_initial)
220 plan_budget, horizon = _attempt_budget(plan_budget), _positive_int(horizon, "horizon")
221 scripts, scenarios = tuple(scripts), tuple(scenarios)
222 if not scenarios or not scripts or not all(map(callable, scripts)):
223 raise ValueError("Supply a nonempty panel and callable scripts.")
224 options = {} if planner_options is None else dict(planner_options)
225 if archive.fitness_weights is None:
226 archive._set_fitness_weights((1.,))
227 rng = np.random.default_rng(seed)
228 plan_seeds = rng.integers(2**32, size=len(scenarios))
229 calls = 0
230 before = archive.nb_added
231 for step in range(budget):
232 if step < len(scripts):
233 weights = np.zeros(len(scripts))
234 weights[step] = 1.
235 elif step < len(scripts) + random_initial or not archive:
236 weights = rng.uniform(0., .1, size=len(scripts))
237 else:
238 weights = np.asarray(archive[rng.integers(len(archive))], dtype=float).copy()
239 weights[rng.integers(len(scripts))] = rng.random()
240 payload = tuple(map(float, weights))
241 planned = tuple(portfolio_mcts(state, scripts=scripts, weights=payload, simulate=simulate,
242 budget=plan_budget, horizon=horizon, seed=int(plan_seed), **options)
243 for state, plan_seed in zip(scenarios, plan_seeds))
244 calls += sum(row.simulator_calls for row in planned)
245 _offer(archive, _measurement(archive, summarize(tuple(row.plan for row in planned)), payload))
246 return PortfolioQDResult(archive, budget, budget * len(scenarios), calls, archive.nb_added - before)
A measured path and the planner's simulation and branching counts.
A planner repertoire with separately counted outer and inner work.
A measured simulator path, with its primitive actions and rewards.
_step(self, state, action, low_level)