telescopic 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- telescopic/__init__.py +44 -0
- telescopic/_gradient_check.py +317 -0
- telescopic/_io.py +421 -0
- telescopic/_linalg.py +64 -0
- telescopic/_parallel.py +468 -0
- telescopic/_progress.py +76 -0
- telescopic/_random.py +261 -0
- telescopic/_types.py +231 -0
- telescopic/couplings.py +451 -0
- telescopic/diagnostics.py +551 -0
- telescopic/engine.py +1030 -0
- telescopic/estimators.py +218 -0
- telescopic/examples.py +315 -0
- telescopic/initial.py +218 -0
- telescopic/kernels/__init__.py +35 -0
- telescopic/kernels/base.py +654 -0
- telescopic/kernels/gibbs.py +267 -0
- telescopic/kernels/hmc.py +294 -0
- telescopic/kernels/independence.py +214 -0
- telescopic/kernels/mala.py +102 -0
- telescopic/kernels/metropolis.py +632 -0
- telescopic/kernels/mixture.py +228 -0
- telescopic/kernels/random_walk.py +126 -0
- telescopic/measure.py +139 -0
- telescopic/plotting.py +354 -0
- telescopic/py.typed +0 -0
- telescopic/results.py +1174 -0
- telescopic/sampler.py +1285 -0
- telescopic/target.py +351 -0
- telescopic/testing.py +324 -0
- telescopic/tuning.py +454 -0
- telescopic/warnings.py +43 -0
- telescopic-0.1.0.dist-info/METADATA +129 -0
- telescopic-0.1.0.dist-info/RECORD +36 -0
- telescopic-0.1.0.dist-info/WHEEL +4 -0
- telescopic-0.1.0.dist-info/licenses/LICENSE +21 -0
telescopic/__init__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Unbiased Markov chain Monte Carlo with coupled chains and telescoping sums."""
|
|
2
|
+
|
|
3
|
+
# telescopic.plotting is left out: it needs matplotlib, which is optional.
|
|
4
|
+
from telescopic import (
|
|
5
|
+
couplings,
|
|
6
|
+
diagnostics,
|
|
7
|
+
engine,
|
|
8
|
+
estimators,
|
|
9
|
+
examples,
|
|
10
|
+
initial,
|
|
11
|
+
kernels,
|
|
12
|
+
testing,
|
|
13
|
+
tuning,
|
|
14
|
+
)
|
|
15
|
+
from telescopic.measure import SignedMeasure
|
|
16
|
+
from telescopic.results import Estimate, Result, Summary
|
|
17
|
+
from telescopic.sampler import CoupledSampler, sample
|
|
18
|
+
from telescopic.target import Target
|
|
19
|
+
from telescopic.warnings import ConvergenceWarning, InputWarning, TelescopicWarning
|
|
20
|
+
|
|
21
|
+
__version__ = "0.1.0"
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"ConvergenceWarning",
|
|
25
|
+
"CoupledSampler",
|
|
26
|
+
"Estimate",
|
|
27
|
+
"InputWarning",
|
|
28
|
+
"Result",
|
|
29
|
+
"SignedMeasure",
|
|
30
|
+
"Summary",
|
|
31
|
+
"Target",
|
|
32
|
+
"TelescopicWarning",
|
|
33
|
+
"__version__",
|
|
34
|
+
"couplings",
|
|
35
|
+
"diagnostics",
|
|
36
|
+
"engine",
|
|
37
|
+
"estimators",
|
|
38
|
+
"examples",
|
|
39
|
+
"initial",
|
|
40
|
+
"kernels",
|
|
41
|
+
"sample",
|
|
42
|
+
"testing",
|
|
43
|
+
"tuning",
|
|
44
|
+
]
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""The gradient check: a gradient against central differences of its log-density along lines."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import functools
|
|
7
|
+
from collections.abc import Callable, Mapping
|
|
8
|
+
from typing import Any, cast
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
from numpy.random import Generator, SeedSequence
|
|
12
|
+
|
|
13
|
+
from telescopic._random import GRADIENT_CHECK, replicate_generator
|
|
14
|
+
from telescopic._types import Distribution, FloatArray
|
|
15
|
+
from telescopic.diagnostics import GradientCheck
|
|
16
|
+
from telescopic.initial import draw
|
|
17
|
+
from telescopic.target import Target
|
|
18
|
+
from telescopic.warnings import InputWarning, warn
|
|
19
|
+
|
|
20
|
+
# The noise-limited design (N) of notes/experiments/x123: its registration fixed these
|
|
21
|
+
# constants, and its result and review are the evidence for them (spec section 4.4).
|
|
22
|
+
POINTS = 8 # lines, one per draw x
|
|
23
|
+
ULPS = 64.0 # units in the last place below which rounding is not resolved
|
|
24
|
+
SAFETY = 10.0 # a line disagrees above SAFETY times its estimated error
|
|
25
|
+
EPS64 = np.finfo(np.float64).eps
|
|
26
|
+
STENCIL = np.array([1.0, -1.0, 2.0, -2.0])
|
|
27
|
+
SIGNS = np.array([-1.0, 1.0])
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _Recorder:
|
|
31
|
+
# The user's function, recording the narrowest float dtype of each of its outputs since
|
|
32
|
+
# reset: of its one output, or of the two of a log_prob_and_grad (parts=2).
|
|
33
|
+
def __init__(self, function: Callable[..., Any], parts: int = 1) -> None:
|
|
34
|
+
functools.update_wrapper(self, function, updated=()) # its name, for errors
|
|
35
|
+
self.function, self.itemsizes = function, [8] * parts
|
|
36
|
+
|
|
37
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
38
|
+
out = self.function(*args, **kwargs)
|
|
39
|
+
outputs = (out,) if len(self.itemsizes) == 1 else out
|
|
40
|
+
# A log_prob_and_grad that returns no pair records nothing: the Target raises.
|
|
41
|
+
if isinstance(outputs, tuple | list) and len(outputs) == len(self.itemsizes):
|
|
42
|
+
for part, output in enumerate(outputs):
|
|
43
|
+
dtype = np.asarray(output).dtype
|
|
44
|
+
if dtype.kind in "fc": # a complex output counts as its real part, as the Target's
|
|
45
|
+
size = np.finfo(dtype).dtype.itemsize
|
|
46
|
+
self.itemsizes[part] = min(self.itemsizes[part], size)
|
|
47
|
+
return out
|
|
48
|
+
|
|
49
|
+
def reset(self) -> None:
|
|
50
|
+
self.itemsizes = [8] * len(self.itemsizes)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _itemsizes(recorders: tuple[_Recorder, ...]) -> tuple[int, int]:
|
|
54
|
+
# The narrowest itemsizes of the log-density and of the gradient since the last reset.
|
|
55
|
+
f, g = (size for recorder in recorders for size in recorder.itemsizes)
|
|
56
|
+
return f, g
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _signs(generator: Generator, d: int) -> FloatArray:
|
|
60
|
+
signs: FloatArray = generator.choice(SIGNS, size=d)
|
|
61
|
+
return signs
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _streams(
|
|
65
|
+
initial: Distribution, seed: SeedSequence
|
|
66
|
+
) -> tuple[int, FloatArray, Generator, Generator]:
|
|
67
|
+
# A first pass over the check's stream, with no evaluation: the range of the 3 POINTS
|
|
68
|
+
# draws in each coordinate, and two generators placed at the signs of the fallback
|
|
69
|
+
# directions and of the probe of a narrow gradient. One draw at a time keeps the
|
|
70
|
+
# memory a few vectors.
|
|
71
|
+
generator = replicate_generator(seed, GRADIENT_CHECK, 0)
|
|
72
|
+
first = draw(initial, generator)
|
|
73
|
+
d = len(first)
|
|
74
|
+
low, high = first, first.copy()
|
|
75
|
+
for _ in range(1, 3 * POINTS):
|
|
76
|
+
point = draw(initial, generator, d)
|
|
77
|
+
np.minimum(low, point, out=low)
|
|
78
|
+
np.maximum(high, point, out=high)
|
|
79
|
+
high -= low
|
|
80
|
+
probe = copy.deepcopy(generator)
|
|
81
|
+
for _ in range(POINTS):
|
|
82
|
+
_signs(probe, d)
|
|
83
|
+
return d, high, generator, probe
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _direction(
|
|
87
|
+
x: FloatArray, a: FloatArray, b: FloatArray, spread: FloatArray, signs: FloatArray
|
|
88
|
+
) -> FloatArray:
|
|
89
|
+
# u = a - b; where it is 0 (a point start, or a repeated empirical point), a random
|
|
90
|
+
# sign times the range of the draws, |x| where that is 0, or 1; and never below
|
|
91
|
+
# sqrt(eps) |x|, so that a step cannot round away.
|
|
92
|
+
u = a - b
|
|
93
|
+
zero = u == 0
|
|
94
|
+
if zero.any():
|
|
95
|
+
fallback = np.where(spread > 0, spread, np.where(x != 0, np.abs(x), 1.0))
|
|
96
|
+
u = np.where(zero, signs * fallback, u)
|
|
97
|
+
smallest = np.sqrt(EPS64) * np.abs(x)
|
|
98
|
+
direction: FloatArray = np.where(np.abs(u) < smallest, np.copysign(smallest, u), u)
|
|
99
|
+
return direction
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _sweep(
|
|
103
|
+
target: Target,
|
|
104
|
+
recorders: tuple[_Recorder, ...],
|
|
105
|
+
values_at: Callable[[FloatArray], FloatArray],
|
|
106
|
+
initial: Distribution,
|
|
107
|
+
seed: SeedSequence,
|
|
108
|
+
itemsizes: tuple[int, int],
|
|
109
|
+
) -> tuple[list[tuple[float, ...]], int, int, tuple[int, int], tuple[int, int], float]:
|
|
110
|
+
# One pass over the lines with the dtypes of the log-density and of the gradient
|
|
111
|
+
# assumed at most itemsizes, and values_at giving the log-densities at the stencil;
|
|
112
|
+
# returns for each compared line (draw from 1, G, gap, T, F4, L, w1, R_g), then the
|
|
113
|
+
# unusable lines, the skipped draws, the dtypes used and seen, and h.
|
|
114
|
+
itemsize_f, itemsize_g = itemsizes
|
|
115
|
+
d, spread, fallback_signs, probe_signs = _streams(initial, seed)
|
|
116
|
+
generator = replicate_generator(seed, GRADIENT_CHECK, 0)
|
|
117
|
+
rows: list[tuple[float, ...]] = []
|
|
118
|
+
unusable = skipped = 0
|
|
119
|
+
seen_f = seen_g = 8
|
|
120
|
+
h = eps_g = 0.0
|
|
121
|
+
for p in range(POINTS):
|
|
122
|
+
x = draw(initial, generator, d)
|
|
123
|
+
a = draw(initial, generator, d)
|
|
124
|
+
b = draw(initial, generator, d)
|
|
125
|
+
u = _direction(x, a, b, spread, _signs(fallback_signs, d))
|
|
126
|
+
probe_sign = _signs(probe_signs, d)
|
|
127
|
+
|
|
128
|
+
for recorder in recorders:
|
|
129
|
+
recorder.reset()
|
|
130
|
+
zeroed = target.n_grad_zeroed
|
|
131
|
+
f0, g = target.log_prob_and_grad(x[None])
|
|
132
|
+
seen_f = min(seen_f, _itemsizes(recorders)[0])
|
|
133
|
+
if p == 0:
|
|
134
|
+
itemsize_f = min(itemsize_f, seen_f)
|
|
135
|
+
dtype_f = np.dtype(f"f{itemsize_f}")
|
|
136
|
+
if itemsize_f < 8:
|
|
137
|
+
# Evaluate only at points that log_prob's dtype represents, so that the
|
|
138
|
+
# function sees the points the comparison uses.
|
|
139
|
+
x = x.astype(dtype_f).astype(np.float64)
|
|
140
|
+
zeroed = target.n_grad_zeroed
|
|
141
|
+
f0, g = target.log_prob_and_grad(x[None])
|
|
142
|
+
f0, g, zeroed = f0[0], g[0], target.n_grad_zeroed > zeroed
|
|
143
|
+
seen_g = min(seen_g, _itemsizes(recorders)[1])
|
|
144
|
+
if p == 0:
|
|
145
|
+
itemsize_g = min(itemsize_g, seen_g)
|
|
146
|
+
eps_g = float(np.finfo(np.dtype(f"f{itemsize_g}")).eps)
|
|
147
|
+
# The cube root taken in log_prob's dtype, as design (N) registered it.
|
|
148
|
+
h = float(np.finfo(dtype_f).eps ** (1 / 3))
|
|
149
|
+
|
|
150
|
+
# A narrow grad's error along the line is set by the Hessian, which |g| does not
|
|
151
|
+
# bound: its movement under a relative perturbation 8 times its cast's measures it.
|
|
152
|
+
probe = 0.0
|
|
153
|
+
if itemsize_g < 8 and np.isfinite(f0) and not zeroed:
|
|
154
|
+
moved = target.log_prob_and_grad((x * (1 + 4 * eps_g * probe_sign))[None])
|
|
155
|
+
probe = np.abs(moved[1][0] - g)
|
|
156
|
+
if f0 == -np.inf or zeroed:
|
|
157
|
+
skipped += 1
|
|
158
|
+
continue
|
|
159
|
+
|
|
160
|
+
u *= h # the step vector v
|
|
161
|
+
stencil = np.empty((4, d))
|
|
162
|
+
for row, t in zip(stencil, STENCIL, strict=True):
|
|
163
|
+
np.multiply(t, u, out=row)
|
|
164
|
+
row += x
|
|
165
|
+
if itemsize_f < 8:
|
|
166
|
+
stencil[...] = stencil.astype(dtype_f)
|
|
167
|
+
values = values_at(stencil)
|
|
168
|
+
# The displacements as rounded, m_t = fl(x + t v) - x; then m_1 - m_-1 in row 0
|
|
169
|
+
# and m_2 - m_-2 in row 2, and their widths along v, about 2 and 4.
|
|
170
|
+
stencil -= x
|
|
171
|
+
stencil[0] -= stencil[1]
|
|
172
|
+
stencil[2] -= stencil[3]
|
|
173
|
+
d1, d2 = stencil[0], stencil[2]
|
|
174
|
+
vv = u @ u
|
|
175
|
+
w1, w2 = d1 @ u / vv, d2 @ u / vv
|
|
176
|
+
if not (np.isfinite(values).all() and w1 > 0 and w2 > w1):
|
|
177
|
+
unusable += 1
|
|
178
|
+
continue
|
|
179
|
+
D, D2 = (values[0] - values[1]) / w1, (values[2] - values[3]) / w2
|
|
180
|
+
G, G2 = g @ d1 / w1, g @ d2 / w2
|
|
181
|
+
weight = np.abs(g, out=stencil[1])
|
|
182
|
+
weight *= ULPS * eps_g
|
|
183
|
+
np.maximum(weight, probe, out=weight)
|
|
184
|
+
rows.append(
|
|
185
|
+
(
|
|
186
|
+
p + 1,
|
|
187
|
+
G,
|
|
188
|
+
abs(G - D),
|
|
189
|
+
abs((D - G) - (D2 - G2)),
|
|
190
|
+
values[2] + values[3] - 4 * (values[0] + values[1]) + 6 * f0,
|
|
191
|
+
max(np.abs(values).max(), abs(f0)),
|
|
192
|
+
w1,
|
|
193
|
+
(weight @ np.abs(d1, out=stencil[2])) / w1,
|
|
194
|
+
)
|
|
195
|
+
)
|
|
196
|
+
return rows, unusable, skipped, (itemsize_f, itemsize_g), (seen_f, seen_g), h
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# Spec section 4.4.
|
|
200
|
+
def check_gradient(
|
|
201
|
+
log_prob: Callable[..., Any],
|
|
202
|
+
grad: Callable[..., Any] | None,
|
|
203
|
+
initial: Distribution,
|
|
204
|
+
seed: SeedSequence,
|
|
205
|
+
*,
|
|
206
|
+
args: tuple[Any, ...],
|
|
207
|
+
kwargs: Mapping[str, Any] | None,
|
|
208
|
+
vectorize: bool,
|
|
209
|
+
log_prob_and_grad: Callable[..., Any] | None = None,
|
|
210
|
+
) -> GradientCheck:
|
|
211
|
+
# Design (N) on the user's functions, from namespace GRADIENT_CHECK of seed, with a
|
|
212
|
+
# Target of its own so that the sampler's counters are untouched. That Target counts
|
|
213
|
+
# as having warned of a narrow dtype, which the sampler's own Target warns of in the
|
|
214
|
+
# run, so the check filters no warning. Warns when a line disagrees, and when no line
|
|
215
|
+
# could be compared. A log_prob_and_grad, which the chains then evaluate wherever they
|
|
216
|
+
# evaluate a gradient, is compared with differences of its own values, and log_prob
|
|
217
|
+
# is not called.
|
|
218
|
+
if grad is not None:
|
|
219
|
+
recorders: tuple[_Recorder, ...] = (_Recorder(log_prob), _Recorder(grad))
|
|
220
|
+
target = Target(*recorders, args=args, kwargs=kwargs, vectorize=vectorize)
|
|
221
|
+
values_at = target.log_prob
|
|
222
|
+
evaluated, gradient_name, values_name = "log_prob and grad", "grad", "log_prob"
|
|
223
|
+
else:
|
|
224
|
+
recorders = (_Recorder(cast(Callable[..., Any], log_prob_and_grad), parts=2),)
|
|
225
|
+
target = Target(
|
|
226
|
+
log_prob, log_prob_and_grad=recorders[0], args=args, kwargs=kwargs, vectorize=vectorize
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
def values_at(x: FloatArray) -> FloatArray:
|
|
230
|
+
return target.log_prob_and_grad(x)[0]
|
|
231
|
+
|
|
232
|
+
evaluated = "log_prob_and_grad"
|
|
233
|
+
gradient_name = "the gradient of log_prob_and_grad"
|
|
234
|
+
values_name = "the log-density of log_prob_and_grad"
|
|
235
|
+
target._warned_precision = True
|
|
236
|
+
assumed = (8, 8)
|
|
237
|
+
try:
|
|
238
|
+
while True:
|
|
239
|
+
# A function whose dtype narrows after the first draw restarts the sweep with
|
|
240
|
+
# the narrowest dtype; for any other function this runs once.
|
|
241
|
+
rows, unusable, skipped, used, seen, h = _sweep(
|
|
242
|
+
target, recorders, values_at, initial, seed, assumed
|
|
243
|
+
)
|
|
244
|
+
narrowest = (min(seen[0], used[0]), min(seen[1], used[1]))
|
|
245
|
+
if narrowest == used:
|
|
246
|
+
break
|
|
247
|
+
assumed = narrowest
|
|
248
|
+
except Exception as error:
|
|
249
|
+
error.add_note(
|
|
250
|
+
f"raised in the gradient check, which evaluates {evaluated} at draws of the "
|
|
251
|
+
"initial distribution when the sampler is built"
|
|
252
|
+
)
|
|
253
|
+
raise
|
|
254
|
+
number, predicted, gap, truncation, f4, largest, w1, rounding_g = np.reshape(rows, (-1, 8)).T
|
|
255
|
+
tolerance = np.empty(0)
|
|
256
|
+
if rows:
|
|
257
|
+
# The rounding of log_prob from the fourth differences F4, whose rounding part has
|
|
258
|
+
# variance 70 sigma^2: pooled in proportion to |log_prob| and in absolute size, the
|
|
259
|
+
# line's own (a kink), and a floor of ULPS units in the last place.
|
|
260
|
+
eps_f = np.finfo(np.dtype(f"f{used[0]}")).eps
|
|
261
|
+
relative = np.divide(f4, largest, out=np.zeros(len(rows)), where=largest > 0)
|
|
262
|
+
r_hat = np.sqrt(np.mean(relative**2) / 70)
|
|
263
|
+
s_hat = np.sqrt(np.mean(f4**2) / 70)
|
|
264
|
+
rounding_f = (2 / w1) * np.maximum(
|
|
265
|
+
np.maximum(r_hat * largest, s_hat),
|
|
266
|
+
np.maximum(np.abs(f4) / np.sqrt(70), ULPS * eps_f * largest),
|
|
267
|
+
)
|
|
268
|
+
tolerance = SAFETY * (truncation + rounding_f + rounding_g)
|
|
269
|
+
record = GradientCheck(
|
|
270
|
+
draw=number.astype(np.int64),
|
|
271
|
+
gap=gap / h,
|
|
272
|
+
tolerance=tolerance / h,
|
|
273
|
+
predicted=predicted / h,
|
|
274
|
+
n_skipped=skipped,
|
|
275
|
+
n_unusable=unusable,
|
|
276
|
+
)
|
|
277
|
+
message = _message(record, gradient_name, values_name)
|
|
278
|
+
if message:
|
|
279
|
+
warn(message, InputWarning)
|
|
280
|
+
return record
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _message(check: GradientCheck, grad: str, log_prob: str) -> str | None:
|
|
284
|
+
# grad and log_prob name the gradient and the log-density that the check compared.
|
|
285
|
+
if not len(check.gap):
|
|
286
|
+
return (
|
|
287
|
+
f"the gradient check compared no line, so {grad} is unchecked: of its {POINTS} "
|
|
288
|
+
f"draws of the initial distribution, {check.n_skipped} had zero density or a "
|
|
289
|
+
f"gradient that is not finite, and the lines from the other {check.n_unusable} "
|
|
290
|
+
"reached zero density, as from a start on a boundary of the support, or took "
|
|
291
|
+
f"steps that round away in the dtype of {log_prob}, as from float32 values of "
|
|
292
|
+
f"{log_prob} and a start whose spread is tiny beside its distance from 0; draw "
|
|
293
|
+
f"the initial distribution where the density is positive and {grad} is finite, "
|
|
294
|
+
f"and wide enough for the precision of {log_prob}, or return float64 values "
|
|
295
|
+
f"from {log_prob}"
|
|
296
|
+
)
|
|
297
|
+
disagree = check.gap > check.tolerance
|
|
298
|
+
if not disagree.any():
|
|
299
|
+
return None
|
|
300
|
+
ratio = check.ratio
|
|
301
|
+
line = int(np.argmax(np.where(disagree, ratio, 0.0)))
|
|
302
|
+
gap, predicted = check.gap[line], check.predicted[line]
|
|
303
|
+
relative = (
|
|
304
|
+
f"{gap / abs(predicted):.2g} times the predicted change"
|
|
305
|
+
if predicted
|
|
306
|
+
else f"where {grad} predicts no change"
|
|
307
|
+
)
|
|
308
|
+
return (
|
|
309
|
+
f"{grad} disagrees with differences of {log_prob}: on a line through draw "
|
|
310
|
+
f"{check.draw[line]} of {POINTS} of the initial distribution, the change of "
|
|
311
|
+
f"{log_prob} across the spread of the initial distribution differs from the one "
|
|
312
|
+
f"{grad} predicts by {gap:.3g} nats, {relative}, and {ratio[line]:.3g} times the "
|
|
313
|
+
f"comparison's estimated error, so {grad} is not the derivative of {log_prob} as "
|
|
314
|
+
f"computed; look for a wrong sign, a wrong factor or a missing term in {grad}; a "
|
|
315
|
+
"gradient that is approximate by design, as from a solver, numerical differences "
|
|
316
|
+
"or single precision, is expected to warn, and check_grad=False turns the check off"
|
|
317
|
+
)
|