QDpy
Loading...
Searching...
No Matches
sfols.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Optimistic linear support on the nonnegative reward simplex."""
7
8from dataclasses import dataclass
9from itertools import combinations
10
11import numpy as np
12from scipy.optimize import linprog
13
14from .modern import _positive_int
15from .successor_repertoire import SuccessorFeatureRepertoire, _tabular_model, fit_tabular_successor_features
16
17__all__ = ["SFOLSResult", "tabular_optimal_policy", "tabular_sfols"]
18
19
20
21@dataclass(frozen=True)
23 """Coverage and the gap refer to the supplied start-state distribution.
24
25 upper_gap is None if the budget was too small to solve every unit
26 reward. Read the finite gap with the policy and LP solver tolerances.
27 Each row of feature_returns reports one retained policy's start value.
28 """
29
30 repertoire: SuccessorFeatureRepertoire
31 policies: tuple[tuple[int, ...], ...]
32 feature_returns: tuple[tuple[float, ...], ...]
33 solved_weights: tuple[tuple[float, ...], ...]
34 upper_gap: float | None
35 converged: bool
36 bound_solves: int
37
38 @property
39 def policy_solves(self):
40 """Count supported weights sent to the scalar policy solver."""
41 return len(self.solved_weights)
42
43
44def _optimal(dynamics, reward, gamma):
45 indices = np.arange(len(reward))
46 policy = reward.argmax(axis=1)
47 identity = np.eye(len(reward))
48 precision = 64 * np.finfo(float).eps
49 while True:
50 values = np.linalg.solve(identity - gamma * dynamics[indices, policy], reward[indices, policy])
51 actions = reward + gamma * (dynamics @ values)
52 if not np.isfinite(actions).all() or not np.isfinite(values).all():
53 raise ValueError("Scalar policy evaluation produced nonfinite values.")
54 best = actions.argmax(axis=1)
55 residual = actions[indices, best] - actions[indices, policy]
56 improve = residual > precision * max(1., np.max(abs(actions)))
57 if not improve.any():
58 bellman_residual = max(0., float(np.max(actions[indices, best] - values)))
59 return policy, bellman_residual / (1. - gamma)
60 policy[improve] = best[improve]
61
62
63
64def tabular_optimal_policy(continuation, features, reward_weights, *, gamma=.99):
65 """Return the integer action table for a fixed linear reward."""
66 dynamics, features = _tabular_model(continuation, features, gamma)
67 weights = np.asarray(reward_weights, dtype=float)
68 if weights.shape != features.shape[-1:] or not np.isfinite(weights).all():
69 raise ValueError("Provide one finite scalar reward weight per feature.")
70 policy, _ = _optimal(dynamics, features @ weights, gamma)
71 return tuple(map(int, policy))
72
73
74def _corners(values):
75 """Enumerate vertices of each policy's region on the reward simplex."""
76 dimensions = values.shape[1]
77 unit = np.eye(dimensions)
78 ones = np.ones(dimensions)
79 right = unit[-1]
80 corners = {tuple(row) for row in unit}
81 for active in values:
82 deltas = active - values
83 scale = np.max(abs(deltas), axis=1)
84 directions = deltas[scale > 0.] / scale[scale > 0., None]
85 boundaries = np.vstack((unit, directions))
86 for rows in combinations(boundaries, dimensions - 1):
87 try:
88 point = np.linalg.solve(np.vstack((*rows, ones)), right)
89 except np.linalg.LinAlgError:
90 continue
91 if (point < -1e-10).any() or (directions @ point < -1e-10).any():
92 continue
93 point = point.clip(min=0.)
94 point = (point / point.sum()).round(12)
95 corners.add(tuple(map(float, point / point.sum())))
96 return tuple(sorted(corners))
97
98
99
107def tabular_sfols(continuation, features, start, *, gamma=.99, max_policy_solves=32, tolerance=1e-7):
108 """Solve the most promising corner of the current policy envelope next.
109
110 The search first solves unit reward weights. For each corner of
111 the current piecewise-linear value envelope, a linear program
112 bounds the value of any unknown policy using the solved tasks.
113 Numerical roundoff in policy evaluation is tracked through
114 a Bellman residual bound. Corner enumeration is intended for small
115 reward spaces. Auditing uses the supplied start distribution.
116 """
117 dynamics, features = _tabular_model(continuation, features, gamma)
118 budget = _positive_int(max_policy_solves, "max_policy_solves")
119 start = np.asarray(start, dtype=float)
120 if (start.shape != (len(dynamics),) or not np.isfinite(start).all() or (start < 0.).any()
121 or not np.isclose(start.sum(), 1., rtol=0., atol=1e-12) or not 0. < tolerance < np.inf):
122 raise ValueError("Supply a start distribution and positive finite tolerance.")
123 start = start / start.sum()
124 dimension = features.shape[-1]
125 states = np.arange(len(dynamics))
126 identity = np.eye(len(dynamics))
127 records, policies = {}, {}
128 bound_solves = 0
129
130 def evaluate(weights):
131 action, residual = _optimal(dynamics, features @ weights, gamma)
132 matrix = identity - gamma * dynamics[states, action]
133 value = start @ np.linalg.solve(matrix, features[states, action])
134 bound = float(value @ weights) + residual
135 if not np.isfinite(value).all() or not np.isfinite(bound):
136 raise ValueError("SFOLS produced nonfinite feature returns or bounds.")
137 records[weights] = bound
138 policies.setdefault(tuple(map(int, action)), tuple(map(float, value)))
139
140 for corner in np.eye(dimension)[:budget]:
141 evaluate(tuple(map(float, corner)))
142 gap = None
143 if len(records) == dimension:
144 while True:
145 values = np.asarray(tuple(policies.values()))
146 candidates = []
147 for corner in _corners(values):
148 lower = float((values @ corner).max())
149 if corner in records:
150 upper = records[corner]
151 else:
152 # Bounding each objective by its unit task improves numerical conditioning.
153 lin = linprog(-np.asarray(corner), A_ub=np.asarray(tuple(records)),
154 b_ub=np.asarray(tuple(records.values())), bounds=(None, None), method="highs")
155 bound_solves += 1
156 if not lin.success:
157 raise RuntimeError(f"SFOLS could not bound an unsolved reward: {lin.message}")
158 upper = -float(lin.fun)
159 candidates.append((max(0., upper - lower), corner))
160 gap = max(value for value, _ in candidates)
161 pending = [(value, corner) for value, corner in candidates if corner not in records]
162 if gap <= tolerance or not pending or len(records) == budget:
163 break
164 gain, target = max(pending)
165 if gain <= tolerance:
166 break
167 evaluate(target)
168 repertoire = fit_tabular_successor_features(dynamics, features, tuple(policies), gamma=gamma)
169 return SFOLSResult(repertoire, tuple(policies), tuple(policies.values()), tuple(records), gap,
170 gap is not None and gap <= tolerance, bound_solves)
A policy repertoire, solved reward weights, and the residual optimistic gap.
Definition sfols.py:22