forked from pymc-devs/pymc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompound.py
More file actions
323 lines (267 loc) · 10.8 KB
/
compound.py
File metadata and controls
323 lines (267 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# Copyright 2023 The PyMC Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Created on Mar 7, 2011
@author: johnsalvatier
"""
import warnings
from abc import ABC, abstractmethod
from enum import IntEnum, unique
from typing import Any, Dict, Iterable, List, Mapping, Sequence, Tuple, Union
import numpy as np
from pytensor.graph.basic import Variable
from pymc.blocking import PointType, StatDtype, StatsDict, StatShape, StatsType
from pymc.model import modelcontext
__all__ = ("Competence", "CompoundStep")
@unique
class Competence(IntEnum):
"""Enum for characterizing competence classes of step methods.
Values include:
0: INCOMPATIBLE
1: COMPATIBLE
2: PREFERRED
3: IDEAL
"""
INCOMPATIBLE = 0
COMPATIBLE = 1
PREFERRED = 2
IDEAL = 3
def infer_warn_stats_info(
stats_dtypes: List[Dict[str, StatDtype]],
sds: Dict[str, Tuple[StatDtype, StatShape]],
stepname: str,
) -> Tuple[List[Dict[str, StatDtype]], Dict[str, Tuple[StatDtype, StatShape]]]:
"""Helper function to get `stats_dtypes` and `stats_dtypes_shapes` from either of them."""
# Avoid side-effects on the original lists/dicts
stats_dtypes = [d.copy() for d in stats_dtypes]
sds = sds.copy()
# Disallow specification of both attributes
if stats_dtypes and sds:
raise TypeError(
"Only one of `stats_dtypes_shapes` or `stats_dtypes` must be specified."
f" `{stepname}.stats_dtypes` should be removed."
)
# Infer one from the other
if not sds and stats_dtypes:
warnings.warn(
f"`{stepname}.stats_dtypes` is deprecated."
" Please update it to specify `stats_dtypes_shapes` instead.",
DeprecationWarning,
)
if len(stats_dtypes) > 1:
raise TypeError(
f"`{stepname}.stats_dtypes` must be a list containing at most one dict."
)
for sd in stats_dtypes:
for sname, dtype in sd.items():
sds[sname] = (dtype, None)
elif sds:
stats_dtypes.append({sname: dtype for sname, (dtype, _) in sds.items()})
return stats_dtypes, sds
class BlockedStep(ABC):
stats_dtypes: List[Dict[str, type]] = []
"""A list containing <=1 dictionary that maps stat names to dtypes.
This attribute is deprecated.
Use `stats_dtypes_shapes` instead.
"""
stats_dtypes_shapes: Dict[str, Tuple[StatDtype, StatShape]] = {}
"""Maps stat names to dtypes and shapes.
Shapes are interpreted in the following ways:
- `[]` is a scalar.
- `[3,]` is a length-3 vector.
- `[4, None]` is a matrix with 4 rows and a dynamic number of columns.
- `None` is a sparse stat (i.e. not always present) or a NumPy array with varying `ndim`.
"""
vars: List[Variable] = []
"""Variables that the step method is assigned to."""
def __new__(cls, *args, **kwargs):
blocked = kwargs.get("blocked")
if blocked is None:
# Try to look up default value from class
blocked = getattr(cls, "default_blocked", True)
kwargs["blocked"] = blocked
model = modelcontext(kwargs.get("model"))
kwargs.update({"model": model})
# vars can either be first arg or a kwarg
if "vars" not in kwargs and len(args) >= 1:
vars = args[0]
args = args[1:]
elif "vars" in kwargs:
vars = kwargs.pop("vars")
else: # Assume all model variables
vars = model.value_vars
if not isinstance(vars, (tuple, list)):
vars = [vars]
if len(vars) == 0:
raise ValueError("No free random variables to sample.")
# Auto-fill stats metadata attributes from whichever was given.
stats_dtypes, stats_dtypes_shapes = infer_warn_stats_info(
cls.stats_dtypes,
cls.stats_dtypes_shapes,
cls.__name__,
)
if not blocked and len(vars) > 1:
# In this case we create a separate sampler for each var
# and append them to a CompoundStep
steps = []
for var in vars:
step = super().__new__(cls)
step.stats_dtypes = stats_dtypes
step.stats_dtypes_shapes = stats_dtypes_shapes
# If we don't return the instance we have to manually
# call __init__
step.__init__([var], *args, **kwargs)
# Hack for creating the class correctly when unpickling.
step.__newargs = ([var],) + args, kwargs
steps.append(step)
return CompoundStep(steps)
else:
step = super().__new__(cls)
step.stats_dtypes = stats_dtypes
step.stats_dtypes_shapes = stats_dtypes_shapes
# Hack for creating the class correctly when unpickling.
step.__newargs = (vars,) + args, kwargs
return step
# Hack for creating the class correctly when unpickling.
def __getnewargs_ex__(self):
return self.__newargs
@abstractmethod
def step(self, point: PointType) -> Tuple[PointType, StatsType]:
"""Perform a single step of the sampler."""
@staticmethod
def competence(var, has_grad):
return Competence.INCOMPATIBLE
@classmethod
def _competence(cls, vars, have_grad):
vars = np.atleast_1d(vars)
have_grad = np.atleast_1d(have_grad)
competences = []
for var, has_grad in zip(vars, have_grad):
try:
competences.append(cls.competence(var, has_grad))
except TypeError:
competences.append(cls.competence(var))
return competences
def stop_tuning(self):
if hasattr(self, "tune"):
self.tune = False
def flat_statname(sampler_idx: int, sname: str) -> str:
"""Get the flat-stats name for a samplers stat."""
return f"sampler_{sampler_idx}__{sname}"
def get_stats_dtypes_shapes_from_steps(
steps: Iterable[BlockedStep],
) -> Dict[str, Tuple[StatDtype, StatShape]]:
"""Combines stats dtype shape dictionaries from multiple step methods.
In the resulting stats dict, each sampler stat is prefixed by `sampler_#__`.
"""
result = {}
for s, step in enumerate(steps):
for sname, (dtype, shape) in step.stats_dtypes_shapes.items():
result[flat_statname(s, sname)] = (dtype, shape)
return result
class CompoundStep:
"""Step method composed of a list of several other step
methods applied in sequence."""
def __init__(self, methods):
self.methods = list(methods)
self.stats_dtypes = []
for method in self.methods:
self.stats_dtypes.extend(method.stats_dtypes)
self.stats_dtypes_shapes = get_stats_dtypes_shapes_from_steps(methods)
self.name = (
f"Compound[{', '.join(getattr(m, 'name', 'UNNAMED_STEP') for m in self.methods)}]"
)
self.tune = True
def step(self, point) -> Tuple[PointType, StatsType]:
stats = []
for method in self.methods:
point, sts = method.step(point)
stats.extend(sts)
# Model logp can only be the logp of the _last_ stats,
# if there is one. Pop all others.
for sts in stats[:-1]:
sts.pop("model_logp", None)
return point, stats
def stop_tuning(self):
for method in self.methods:
method.stop_tuning()
def reset_tuning(self):
for method in self.methods:
if hasattr(method, "reset_tuning"):
method.reset_tuning()
@property
def vars(self) -> List[Variable]:
return [var for method in self.methods for var in method.vars]
def flatten_steps(step: Union[BlockedStep, CompoundStep]) -> List[BlockedStep]:
"""Flatten a hierarchy of step methods to a list."""
if isinstance(step, BlockedStep):
return [step]
steps = []
if not isinstance(step, CompoundStep):
raise ValueError(f"Unexpected type of step method: {step}")
for sm in step.methods:
steps += flatten_steps(sm)
return steps
def check_step_emits_tune(step: Union[CompoundStep, BlockedStep]):
if isinstance(step, BlockedStep) and "tune" not in step.stats_dtypes_shapes:
raise TypeError(f"{type(step)} does not emit the required 'tune' stat.")
elif isinstance(step, CompoundStep):
for sstep in step.methods:
if "tune" not in sstep.stats_dtypes_shapes:
raise TypeError(f"{type(sstep)} does not emit the required 'tune' stat.")
return
class StatsBijection:
"""Map between a `list` of stats to `dict` of stats."""
def __init__(self, sampler_stats_dtypes: Sequence[Mapping[str, type]]) -> None:
# Keep a list of flat vs. original stat names
stat_groups = []
for s, names_dtypes in enumerate(sampler_stats_dtypes):
group = []
for statname, dtype in names_dtypes.items():
flatname = flat_statname(s, statname)
is_obj = np.dtype(dtype) == np.dtype(object)
group.append((flatname, statname, is_obj))
stat_groups.append(group)
self._stat_groups: List[List[Tuple[str, str, bool]]] = stat_groups
self.object_stats = {
fname: (s, sname)
for s, group in enumerate(self._stat_groups)
for fname, sname, is_obj in group
if is_obj
}
@property
def n_samplers(self) -> int:
return len(self._stat_groups)
def map(self, stats_list: Sequence[Mapping[str, Any]]) -> StatsDict:
"""Combine stats dicts of multiple samplers into one dict."""
stats_dict = {}
for s, sts in enumerate(stats_list):
for fname, sname, is_obj in self._stat_groups[s]:
if sname not in sts:
continue
stats_dict[fname] = sts[sname]
return stats_dict
def rmap(self, stats_dict: Mapping[str, Any]) -> StatsType:
"""Split a global stats dict into a list of sampler-wise stats dicts.
The ``stats_dict`` can be a subset of all sampler stats.
"""
stats_list = []
for group in self._stat_groups:
d = {}
for fname, sname, is_obj in group:
if fname not in stats_dict:
continue
d[sname] = stats_dict[fname]
stats_list.append(d)
return stats_list