QDpy
Loading...
Searching...
No Matches
successor_repertoire.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Exact tabular policy evaluation and generalized policy improvement."""
7
8from dataclasses import dataclass
9
10import numpy as np
11
12__all__ = ["SuccessorFeatureRepertoire", "fit_tabular_successor_features"]
13
14
15
16@dataclass(frozen=True, eq=False)
18 """The values array is indexed by policy, state, first action, and feature.
19
20 Feature returns predict continuing with the source policy after the
21 first action. GPI chooses the action with the highest value across
22 all source policies independently at each visited state.
23 """
24
25 successor_features: np.ndarray
26
27 def __post_init__(self):
28 values = np.array(self.successor_features, dtype=float, copy=True)
29 if values.ndim != 4 or min(values.shape) < 1 or not np.isfinite(values).all():
30 raise ValueError("Provide finite successor features with shape (policies, states, actions, features).")
31 values.setflags(write=False)
32 object.__setattr__(self, "successor_features", values)
33
34
35 def action_values(self, reward_weights):
36 """Return a (policy, state, action) array."""
37 weights = np.asarray(reward_weights, dtype=float)
38 if weights.shape != self.successor_features.shape[-1:] or not np.isfinite(weights).all():
39 raise ValueError("Provide one finite weight per reward feature.")
40 values = self.successor_features @ weights
41 if not np.isfinite(values).all():
42 raise ValueError("Weighted action values must be finite.")
43 return values
44
45
46 def action_table(self, reward_weights):
47 """Break exact ties by choosing the lowest action index."""
48 return self.action_values(reward_weights).max(axis=0).argmax(axis=1)
49
50
51def _tabular_model(continuation, features, gamma):
52 dynamics = np.asarray(continuation, dtype=float)
53 features = np.asarray(features, dtype=float)
54 if dynamics.ndim != 3 or min(dynamics.shape) < 1 or dynamics.shape[0] != dynamics.shape[2]:
55 raise ValueError("continuation must have shape (states, actions, states).")
56 states, actions, _ = dynamics.shape
57 mass = dynamics.sum(axis=-1, keepdims=True)
58 if (not np.isfinite(dynamics).all() or (dynamics < 0.).any() or (mass > 1. + 1e-12).any()
59 or not 0. <= gamma < 1.):
60 raise ValueError("Use substochastic nonnegative transitions and 0 <= gamma < 1.")
61 dynamics = dynamics / np.maximum(mass, 1.)
62 if (features.ndim != 3 or features.shape[:2] != (states, actions) or not features.shape[2]
63 or not np.isfinite(features).all()):
64 raise ValueError("Provide finite expected features with shape (states, actions, features).")
65 return dynamics, features
66
67
68
74def fit_tabular_successor_features(continuation, features, policies, *, gamma=.99):
75 """Solve each source policy's Bellman system exactly up to float precision.
76
77 Missing transition mass denotes termination. Include immediate
78 features from the terminal outcomes in the expected input features.
79 Observations and actions are integer indices. All policies transfer
80 within the same dynamics and reward is linear in the features.
81 """
82 dynamics, features = _tabular_model(continuation, features, gamma)
83 states, actions, _ = dynamics.shape
84 policies = np.asarray(policies)
85 if policies.ndim == 2:
86 if (policies.dtype.kind not in "iu" or policies.shape[1] != states
87 or (policies < 0).any() or (policies >= actions).any()):
88 raise ValueError("Use a policy-by-state table of valid integer actions.")
89 transition = dynamics[np.arange(states), policies]
90 immediate = features[np.arange(states), policies]
91 else:
92 policies = np.asarray(policies, dtype=float)
93 if (policies.ndim != 3 or policies.shape[1:] != (states, actions)
94 or not np.isfinite(policies).all() or (policies < 0.).any()):
95 raise ValueError("Provide probability distributions over actions for each policy and state.")
96 totals = policies.sum(axis=-1, keepdims=True)
97 if not np.allclose(totals, 1., rtol=0., atol=1e-12):
98 raise ValueError("Each policy's action probabilities must sum to one.")
99 policies = policies / totals
100 transition = np.einsum("ksa,sat->kst", policies, dynamics)
101 immediate = np.einsum("ksa,saf->ksf", policies, features)
102 if not len(policies):
103 raise ValueError("Supply at least one source policy.")
104 state_values = np.linalg.solve(np.eye(states) - gamma * transition, immediate)
105 action_values = features + gamma * np.einsum("sat,ktf->ksaf", dynamics, state_values)
106 return SuccessorFeatureRepertoire(action_values)
Discounted feature predictions for each archived policy and first action.
action_values(self, reward_weights)
Evaluate every source policy's action-values under new reward weights.
action_table(self, reward_weights)
Return the greedy GPI action for every state.