forked from pymc-devs/pymc-extras
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpathfinder.py
1780 lines (1504 loc) · 63.1 KB
/
pathfinder.py
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2022 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.
import collections
import logging
import time
import warnings as _warnings
from collections import Counter
from collections.abc import Callable, Iterator
from dataclasses import asdict, dataclass, field, replace
from enum import Enum, auto
from typing import Literal, TypeAlias
import arviz as az
import filelock
import jax
import numpy as np
import pymc as pm
import pytensor
import pytensor.tensor as pt
from numpy.typing import NDArray
from packaging import version
from pymc import Model
from pymc.backends.arviz import coords_and_dims_for_inferencedata
from pymc.blocking import DictToArrayBijection, RaveledVars
from pymc.initial_point import make_initial_point_fn
from pymc.model import modelcontext
from pymc.model.core import Point
from pymc.pytensorf import (
compile_pymc,
find_rng_nodes,
reseed_rngs,
)
from pymc.sampling.jax import get_jaxified_graph
from pymc.util import (
CustomProgress,
RandomSeed,
_get_seeds_per_chain,
default_progress_theme,
get_default_varnames,
)
from pytensor.compile.function.types import Function
from pytensor.compile.mode import FAST_COMPILE, Mode
from pytensor.graph import Apply, Op, vectorize_graph
from pytensor.tensor import TensorConstant, TensorVariable
from rich.console import Console, Group
from rich.padding import Padding
from rich.progress import BarColumn, TextColumn, TimeElapsedColumn, TimeRemainingColumn
from rich.table import Table
from rich.text import Text
# TODO: change to typing.Self after Python versions greater than 3.10
from typing_extensions import Self
from pymc_extras.inference.pathfinder.importance_sampling import (
importance_sampling as _importance_sampling,
)
from pymc_extras.inference.pathfinder.lbfgs import (
LBFGS,
LBFGSException,
LBFGSInitFailed,
LBFGSStatus,
)
logger = logging.getLogger(__name__)
_warnings.filterwarnings(
"ignore", category=FutureWarning, message="compile_pymc was renamed to compile"
)
REGULARISATION_TERM = 1e-8
DEFAULT_LINKER = "cvm_nogc"
SinglePathfinderFn: TypeAlias = Callable[[int], "PathfinderResult"]
def get_jaxified_logp_of_ravel_inputs(model: Model, jacobian: bool = True) -> Callable:
"""
Get a JAX function that computes the log-probability of a PyMC model with ravelled inputs.
Parameters
----------
model : Model
PyMC model to compute log-probability and gradient.
jacobian : bool, optional
Whether to include the Jacobian in the log-probability computation, by default True. Setting to False (not recommended) may result in very high values for pareto k.
Returns
-------
Function
A JAX function that computes the log-probability of a PyMC model with ravelled inputs.
"""
# TODO: JAX: test if we should get jaxified graph of dlogp as well
new_logprob, new_input = pm.pytensorf.join_nonshared_inputs(
model.initial_point(), (model.logp(jacobian=jacobian),), model.value_vars, ()
)
logp_func_list = get_jaxified_graph([new_input], new_logprob)
def logp_func(x):
return logp_func_list(x)[0]
return logp_func
def get_logp_dlogp_of_ravel_inputs(
model: Model, jacobian: bool = True, **compile_kwargs
) -> Function:
"""
Get the log-probability and its gradient for a PyMC model with ravelled inputs.
Parameters
----------
model : Model
PyMC model to compute log-probability and gradient.
jacobian : bool, optional
Whether to include the Jacobian in the log-probability computation, by default True. Setting to False (not recommended) may result in very high values for pareto k.
**compile_kwargs : dict
Additional keyword arguments to pass to the compile function.
Returns
-------
Function
A compiled PyTensor function that computes the log-probability and its gradient given ravelled inputs.
"""
(logP, dlogP), inputs = pm.pytensorf.join_nonshared_inputs(
model.initial_point(),
[model.logp(jacobian=jacobian), model.dlogp(jacobian=jacobian)],
model.value_vars,
)
logp_dlogp_fn = compile_pymc([inputs], (logP, dlogP), **compile_kwargs)
logp_dlogp_fn.trust_input = True
return logp_dlogp_fn
def convert_flat_trace_to_idata(
samples: NDArray,
include_transformed: bool = False,
postprocessing_backend: Literal["cpu", "gpu"] = "cpu",
inference_backend: Literal["pymc", "blackjax"] = "pymc",
model: Model | None = None,
importance_sampling: Literal["psis", "psir", "identity"] | None = "psis",
) -> az.InferenceData:
"""convert flattened samples to arviz InferenceData format.
Parameters
----------
samples : NDArray
flattened samples
include_transformed : bool
whether to include transformed variables
postprocessing_backend : str
backend for postprocessing transformations, either "cpu" or "gpu"
inference_backend : str
backend for inference, either "pymc" or "blackjax"
model : Model | None
pymc model for variable transformations
importance_sampling : str
importance sampling method used, affects input samples shape
Returns
-------
InferenceData
arviz inference data object
"""
if importance_sampling is None:
# samples.ndim == 3 in this case, otherwise ndim == 2
num_paths, num_pdraws, N = samples.shape
samples = samples.reshape(-1, N)
model = modelcontext(model)
ip = model.initial_point()
ip_point_map_info = DictToArrayBijection.map(ip).point_map_info
trace = collections.defaultdict(list)
for sample in samples:
raveld_vars = RaveledVars(sample, ip_point_map_info)
point = DictToArrayBijection.rmap(raveld_vars, ip)
for p, v in point.items():
trace[p].append(v.tolist())
trace = {k: np.asarray(v)[None, ...] for k, v in trace.items()}
var_names = model.unobserved_value_vars
vars_to_sample = list(get_default_varnames(var_names, include_transformed=include_transformed))
logger.info("Transforming variables...")
if inference_backend == "pymc":
new_shapes = [v.ndim * (None,) for v in trace.values()]
replace = {
var: pt.tensor(dtype="float64", shape=new_shapes[i])
for i, var in enumerate(model.value_vars)
}
outputs = vectorize_graph(vars_to_sample, replace=replace)
fn = pytensor.function(
inputs=[*list(replace.values())],
outputs=outputs,
mode=FAST_COMPILE,
on_unused_input="ignore",
)
fn.trust_input = True
result = fn(*list(trace.values()))
if importance_sampling is None:
result = [res.reshape(num_paths, num_pdraws, *res.shape[2:]) for res in result]
elif inference_backend == "blackjax":
jax_fn = get_jaxified_graph(inputs=model.value_vars, outputs=vars_to_sample)
result = jax.vmap(jax.vmap(jax_fn))(
*jax.device_put(list(trace.values()), jax.devices(postprocessing_backend)[0])
)
trace = {v.name: r for v, r in zip(vars_to_sample, result)}
coords, dims = coords_and_dims_for_inferencedata(model)
idata = az.from_dict(trace, dims=dims, coords=coords)
return idata
def alpha_recover(
x: TensorVariable, g: TensorVariable, epsilon: TensorVariable
) -> tuple[TensorVariable, TensorVariable, TensorVariable, TensorVariable]:
"""compute the diagonal elements of the inverse Hessian at each iterations of L-BFGS and filter updates.
Parameters
----------
x : TensorVariable
position array, shape (L+1, N)
g : TensorVariable
gradient array, shape (L+1, N)
epsilon : float
threshold for filtering updates based on inner product of position
and gradient differences
Returns
-------
alpha : TensorVariable
diagonal elements of the inverse Hessian at each iteration of L-BFGS, shape (L, N)
s : TensorVariable
position differences, shape (L, N)
z : TensorVariable
gradient differences, shape (L, N)
update_mask : TensorVariable
mask for filtering updates, shape (L,)
Notes
-----
shapes: L=batch_size, N=num_params
"""
def compute_alpha_l(alpha_lm1, s_l, z_l) -> TensorVariable:
# alpha_lm1: (N,)
# s_l: (N,)
# z_l: (N,)
a = z_l.T @ pt.diag(alpha_lm1) @ z_l
b = z_l.T @ s_l
c = s_l.T @ pt.diag(1.0 / alpha_lm1) @ s_l
inv_alpha_l = (
a / (b * alpha_lm1)
+ z_l ** 2 / b
- (a * s_l ** 2) / (b * c * alpha_lm1**2)
) # fmt:off
return 1.0 / inv_alpha_l
def return_alpha_lm1(alpha_lm1, s_l, z_l) -> TensorVariable:
return alpha_lm1[-1]
def scan_body(update_mask_l, s_l, z_l, alpha_lm1) -> TensorVariable:
return pt.switch(
update_mask_l,
compute_alpha_l(alpha_lm1, s_l, z_l),
return_alpha_lm1(alpha_lm1, s_l, z_l),
)
Lp1, N = x.shape
s = pt.diff(x, axis=0)
z = pt.diff(g, axis=0)
alpha_l_init = pt.ones(N)
sz = (s * z).sum(axis=-1)
# update_mask = sz > epsilon * pt.linalg.norm(z, axis=-1)
# pt.linalg.norm does not work with JAX!!
update_mask = sz > epsilon * pt.sqrt(pt.sum(z**2, axis=-1))
alpha, _ = pytensor.scan(
fn=scan_body,
outputs_info=alpha_l_init,
sequences=[update_mask, s, z],
n_steps=Lp1 - 1,
allow_gc=False,
)
# assert np.all(alpha.eval() > 0), "alpha cannot be negative"
# alpha: (L, N), update_mask: (L, N)
return alpha, s, z, update_mask
def inverse_hessian_factors(
alpha: TensorVariable,
s: TensorVariable,
z: TensorVariable,
update_mask: TensorVariable,
J: TensorConstant,
) -> tuple[TensorVariable, TensorVariable]:
"""compute the inverse hessian factors for the BFGS approximation.
Parameters
----------
alpha : TensorVariable
diagonal scaling matrix, shape (L, N)
s : TensorVariable
position differences, shape (L, N)
z : TensorVariable
gradient differences, shape (L, N)
update_mask : TensorVariable
mask for filtering updates, shape (L,)
J : TensorConstant
history size for L-BFGS
Returns
-------
beta : TensorVariable
low-rank update matrix, shape (L, N, 2J)
gamma : TensorVariable
low-rank update matrix, shape (L, 2J, 2J)
Notes
-----
shapes: L=batch_size, N=num_params, J=history_size
"""
# NOTE: get_chi_matrix_1 is a modified version of get_chi_matrix_2 to closely follow Zhang et al., (2022)
# NOTE: get_chi_matrix_2 is from blackjax which MAYBE incorrectly implemented
def get_chi_matrix_1(
diff: TensorVariable, update_mask: TensorVariable, J: TensorConstant
) -> TensorVariable:
L, N = diff.shape
j_last = pt.as_tensor(J - 1) # since indexing starts at 0
def chi_update(chi_lm1, diff_l) -> TensorVariable:
chi_l = pt.roll(chi_lm1, -1, axis=0)
return pt.set_subtensor(chi_l[j_last], diff_l)
def no_op(chi_lm1, diff_l) -> TensorVariable:
return chi_lm1
def scan_body(update_mask_l, diff_l, chi_lm1) -> TensorVariable:
return pt.switch(update_mask_l, chi_update(chi_lm1, diff_l), no_op(chi_lm1, diff_l))
chi_init = pt.zeros((J, N))
chi_mat, _ = pytensor.scan(
fn=scan_body,
outputs_info=chi_init,
sequences=[
update_mask,
diff,
],
allow_gc=False,
)
chi_mat = pt.matrix_transpose(chi_mat)
# (L, N, J)
return chi_mat
def get_chi_matrix_2(
diff: TensorVariable, update_mask: TensorVariable, J: TensorConstant
) -> TensorVariable:
L, N = diff.shape
diff_masked = update_mask[:, None] * diff
# diff_padded: (L+J, N)
pad_width = pt.zeros(shape=(2, 2), dtype="int32")
pad_width = pt.set_subtensor(pad_width[0, 0], J)
diff_padded = pt.pad(diff_masked, pad_width, mode="constant")
index = pt.arange(L)[:, None] + pt.arange(J)[None, :]
index = index.reshape((L, J))
chi_mat = pt.matrix_transpose(diff_padded[index])
# (L, N, J)
return chi_mat
L, N = alpha.shape
S = get_chi_matrix_1(s, update_mask, J)
Z = get_chi_matrix_1(z, update_mask, J)
# E: (L, J, J)
Ij = pt.eye(J)[None, ...]
E = pt.triu(pt.matrix_transpose(S) @ Z)
E += Ij * REGULARISATION_TERM
# eta: (L, J)
eta = pt.diagonal(E, axis1=-2, axis2=-1)
# beta: (L, N, 2J)
alpha_diag, _ = pytensor.scan(lambda a: pt.diag(a), sequences=[alpha])
beta = pt.concatenate([alpha_diag @ Z, S], axis=-1)
# more performant and numerically precise to use solve than inverse: https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.linalg.inv.html
# E_inv: (L, J, J)
E_inv = pt.slinalg.solve_triangular(E, Ij, check_finite=False)
eta_diag, _ = pytensor.scan(pt.diag, sequences=[eta])
# block_dd: (L, J, J)
block_dd = (
pt.matrix_transpose(E_inv) @ (eta_diag + pt.matrix_transpose(Z) @ alpha_diag @ Z) @ E_inv
)
# (L, J, 2J)
gamma_top = pt.concatenate([pt.zeros((L, J, J)), -E_inv], axis=-1)
# (L, J, 2J)
gamma_bottom = pt.concatenate([-pt.matrix_transpose(E_inv), block_dd], axis=-1)
# (L, 2J, 2J)
gamma = pt.concatenate([gamma_top, gamma_bottom], axis=1)
return beta, gamma
def bfgs_sample_dense(
x: TensorVariable,
g: TensorVariable,
alpha: TensorVariable,
beta: TensorVariable,
gamma: TensorVariable,
alpha_diag: TensorVariable,
inv_sqrt_alpha_diag: TensorVariable,
sqrt_alpha_diag: TensorVariable,
u: TensorVariable,
) -> tuple[TensorVariable, TensorVariable]:
"""sample from the BFGS approximation using dense matrix operations.
Parameters
----------
x : TensorVariable
position array, shape (L, N)
g : TensorVariable
gradient array, shape (L, N)
alpha : TensorVariable
diagonal scaling matrix, shape (L, N)
beta : TensorVariable
low-rank update matrix, shape (L, N, 2J)
gamma : TensorVariable
low-rank update matrix, shape (L, 2J, 2J)
alpha_diag : TensorVariable
diagonal matrix of alpha, shape (L, N, N)
inv_sqrt_alpha_diag : TensorVariable
inverse sqrt of alpha diagonal, shape (L, N, N)
sqrt_alpha_diag : TensorVariable
sqrt of alpha diagonal, shape (L, N, N)
u : TensorVariable
random normal samples, shape (L, M, N)
Returns
-------
phi : TensorVariable
samples from the approximation, shape (L, M, N)
logdet : TensorVariable
log determinant of covariance, shape (L,)
Notes
-----
shapes: L=batch_size, N=num_params, J=history_size, M=num_samples
"""
N = x.shape[-1]
IdN = pt.eye(N)[None, ...]
# inverse Hessian
H_inv = (
sqrt_alpha_diag
@ (
IdN
+ inv_sqrt_alpha_diag @ beta @ gamma @ pt.matrix_transpose(beta) @ inv_sqrt_alpha_diag
)
@ sqrt_alpha_diag
)
Lchol = pt.linalg.cholesky(H_inv, lower=False, check_finite=False, on_error="nan")
logdet = 2.0 * pt.sum(pt.log(pt.abs(pt.diagonal(Lchol, axis1=-2, axis2=-1))), axis=-1)
with _warnings.catch_warnings():
_warnings.simplefilter("ignore", category=FutureWarning)
mu = x - pt.batched_dot(H_inv, g)
phi = pt.matrix_transpose(
# (L, N, 1)
mu[..., None]
# (L, N, M)
+ Lchol @ pt.matrix_transpose(u)
) # fmt: off
return phi, logdet
def bfgs_sample_sparse(
x: TensorVariable,
g: TensorVariable,
alpha: TensorVariable,
beta: TensorVariable,
gamma: TensorVariable,
alpha_diag: TensorVariable,
inv_sqrt_alpha_diag: TensorVariable,
sqrt_alpha_diag: TensorVariable,
u: TensorVariable,
) -> tuple[TensorVariable, TensorVariable]:
"""sample from the BFGS approximation using sparse matrix operations.
Parameters
----------
x : TensorVariable
position array, shape (L, N)
g : TensorVariable
gradient array, shape (L, N)
alpha : TensorVariable
diagonal scaling matrix, shape (L, N)
beta : TensorVariable
low-rank update matrix, shape (L, N, 2J)
gamma : TensorVariable
low-rank update matrix, shape (L, 2J, 2J)
alpha_diag : TensorVariable
diagonal matrix of alpha, shape (L, N, N)
inv_sqrt_alpha_diag : TensorVariable
inverse sqrt of alpha diagonal, shape (L, N, N)
sqrt_alpha_diag : TensorVariable
sqrt of alpha diagonal, shape (L, N, N)
u : TensorVariable
random normal samples, shape (L, M, N)
Returns
-------
phi : TensorVariable
samples from the approximation, shape (L, M, N)
logdet : TensorVariable
log determinant of covariance, shape (L,)
Notes
-----
shapes: L=batch_size, N=num_params, J=history_size, M=num_samples
"""
# qr_input: (L, N, 2J)
qr_input = inv_sqrt_alpha_diag @ beta
(Q, R), _ = pytensor.scan(fn=pt.nlinalg.qr, sequences=[qr_input], allow_gc=False)
IdN = pt.eye(R.shape[1])[None, ...]
Lchol_input = IdN + R @ gamma @ pt.matrix_transpose(R)
Lchol = pt.linalg.cholesky(Lchol_input, lower=False, check_finite=False, on_error="nan")
logdet = 2.0 * pt.sum(pt.log(pt.abs(pt.diagonal(Lchol, axis1=-2, axis2=-1))), axis=-1)
logdet += pt.sum(pt.log(alpha), axis=-1)
# NOTE: changed the sign from "x + " to "x -" of the expression to match Stan which differs from Zhang et al., (2022). same for dense version.
with _warnings.catch_warnings():
_warnings.simplefilter("ignore", category=FutureWarning)
mu = x - (
# (L, N), (L, N) -> (L, N)
pt.batched_dot(alpha_diag, g)
# beta @ gamma @ beta.T
# (L, N, 2J), (L, 2J, 2J), (L, 2J, N) -> (L, N, N)
# (L, N, N), (L, N) -> (L, N)
+ pt.batched_dot((beta @ gamma @ pt.matrix_transpose(beta)), g)
)
phi = pt.matrix_transpose(
# (L, N, 1)
mu[..., None]
# (L, N, N), (L, N, M) -> (L, N, M)
+ sqrt_alpha_diag
@ (
# (L, N, 2J), (L, 2J, M) -> (L, N, M)
# intermediate calcs below
# (L, N, 2J), (L, 2J, 2J) -> (L, N, 2J)
(Q @ (Lchol - IdN))
# (L, 2J, N), (L, N, M) -> (L, 2J, M)
@ (pt.matrix_transpose(Q) @ pt.matrix_transpose(u))
# (L, N, M)
+ pt.matrix_transpose(u)
)
) # fmt: off
return phi, logdet
def bfgs_sample(
num_samples: TensorConstant,
x: TensorVariable, # position
g: TensorVariable, # grad
alpha: TensorVariable,
beta: TensorVariable,
gamma: TensorVariable,
index: TensorVariable | None = None,
) -> tuple[TensorVariable, TensorVariable]:
"""sample from the BFGS approximation using the inverse hessian factors.
Parameters
----------
num_samples : TensorConstant
number of samples to draw
x : TensorVariable
position array, shape (L, N)
g : TensorVariable
gradient array, shape (L, N)
alpha : TensorVariable
diagonal scaling matrix, shape (L, N)
beta : TensorVariable
low-rank update matrix, shape (L, N, 2J)
gamma : TensorVariable
low-rank update matrix, shape (L, 2J, 2J)
index : TensorVariable | None
optional index for selecting a single path
Returns
-------
if index is None:
phi: samples from local approximations over L (L, M, N)
logQ_phi: log density of samples of phi (L, M)
else:
psi: samples from local approximations where ELBO is maximized (1, M, N)
logQ_psi: log density of samples of psi (1, M)
Notes
-----
shapes: L=batch_size, N=num_params, J=history_size, M=num_samples
"""
if index is not None:
x = x[index][None, ...]
g = g[index][None, ...]
alpha = alpha[index][None, ...]
beta = beta[index][None, ...]
gamma = gamma[index][None, ...]
L, N, JJ = beta.shape
(alpha_diag, inv_sqrt_alpha_diag, sqrt_alpha_diag), _ = pytensor.scan(
lambda a: [pt.diag(a), pt.diag(pt.sqrt(1.0 / a)), pt.diag(pt.sqrt(a))],
sequences=[alpha],
allow_gc=False,
)
u = pt.random.normal(size=(L, num_samples, N))
sample_inputs = (
x,
g,
alpha,
beta,
gamma,
alpha_diag,
inv_sqrt_alpha_diag,
sqrt_alpha_diag,
u,
)
phi, logdet = pytensor.ifelse(
JJ >= N,
bfgs_sample_dense(*sample_inputs),
bfgs_sample_sparse(*sample_inputs),
)
logQ_phi = -0.5 * (
logdet[..., None]
+ pt.sum(u * u, axis=-1)
+ N * pt.log(2.0 * pt.pi)
) # fmt: off
mask = pt.isnan(logQ_phi) | pt.isinf(logQ_phi)
logQ_phi = pt.set_subtensor(logQ_phi[mask], pt.inf)
return phi, logQ_phi
class LogLike(Op):
"""
Op that computes the densities using vectorised operations.
"""
__props__ = ("logp_func",)
def __init__(self, logp_func: Callable):
self.logp_func = logp_func
super().__init__()
def make_node(self, inputs):
inputs = pt.as_tensor(inputs)
outputs = pt.tensor(dtype="float64", shape=(None, None))
return Apply(self, [inputs], [outputs])
def perform(self, node: Apply, inputs, outputs) -> None:
phi = inputs[0]
logP = np.apply_along_axis(self.logp_func, axis=-1, arr=phi)
# replace nan with -inf since np.argmax will return the first index at nan
mask = np.isnan(logP) | np.isinf(logP)
if np.all(mask):
raise PathInvalidLogP()
outputs[0][0] = np.where(mask, -np.inf, logP)
class PathStatus(Enum):
"""
Statuses of a single-path pathfinder.
"""
SUCCESS = auto()
ELBO_ARGMAX_AT_ZERO = auto()
# Statuses that lead to Exceptions:
INVALID_LOGP = auto()
INVALID_LOGQ = auto()
LBFGS_FAILED = auto()
PATH_FAILED = auto()
FAILED_PATH_STATUS = [
PathStatus.INVALID_LOGP,
PathStatus.INVALID_LOGQ,
PathStatus.LBFGS_FAILED,
PathStatus.PATH_FAILED,
]
class PathException(Exception):
"""
raises a PathException if the path failed.
"""
DEFAULT_MESSAGE = "Path failed."
def __init__(self, message=None, status: PathStatus = PathStatus.PATH_FAILED) -> None:
super().__init__(message or self.DEFAULT_MESSAGE)
self.status = status
class PathInvalidLogP(PathException):
"""
raises a PathException if all the logP values in a path are not finite.
"""
DEFAULT_MESSAGE = "Path failed because all the logP values in a path are not finite."
def __init__(self, message=None) -> None:
super().__init__(message or self.DEFAULT_MESSAGE, PathStatus.INVALID_LOGP)
class PathInvalidLogQ(PathException):
"""
raises a PathException if all the logQ values in a path are not finite.
"""
DEFAULT_MESSAGE = "Path failed because all the logQ values in a path are not finite."
def __init__(self, message=None) -> None:
super().__init__(message or self.DEFAULT_MESSAGE, PathStatus.INVALID_LOGQ)
def make_pathfinder_body(
logp_func: Callable,
num_draws: int,
maxcor: int,
num_elbo_draws: int,
epsilon: float,
**compile_kwargs: dict,
) -> Function:
"""
computes the inner components of the Pathfinder algorithm (post-LBFGS) using PyTensor variables and returns a compiled pytensor.function.
Parameters
----------
logp_func : Callable
The target density function.
num_draws : int
Number of samples to draw from the single-path approximation.
maxcor : int
The maximum number of iterations for the L-BFGS algorithm.
num_elbo_draws : int
The number of draws for the Evidence Lower Bound (ELBO) estimation.
epsilon : float
The value used to filter out large changes in the direction of the update gradient at each iteration l in L. Iteration l is only accepted if delta_theta[l] * delta_grad[l] > epsilon * L2_norm(delta_grad[l]) for each l in L.
compile_kwargs : dict
Additional keyword arguments for the PyTensor compiler.
Returns
-------
pathfinder_body_fn : Function
A compiled pytensor.function that performs the inner components of the Pathfinder algorithm (post-LBFGS).
pathfinder_body_fn inputs:
x_full: (L+1, N),
g_full: (L+1, N)
pathfinder_body_fn outputs:
psi: (1, M, N),
logP_psi: (1, M),
logQ_psi: (1, M),
elbo_argmax: (1,)
"""
# x_full, g_full: (L+1, N)
x_full = pt.matrix("x", dtype="float64")
g_full = pt.matrix("g", dtype="float64")
num_draws = pt.constant(num_draws, "num_draws", dtype="int32")
num_elbo_draws = pt.constant(num_elbo_draws, "num_elbo_draws", dtype="int32")
epsilon = pt.constant(epsilon, "epsilon", dtype="float64")
maxcor = pt.constant(maxcor, "maxcor", dtype="int32")
alpha, s, z, update_mask = alpha_recover(x_full, g_full, epsilon=epsilon)
beta, gamma = inverse_hessian_factors(alpha, s, z, update_mask, J=maxcor)
# ignore initial point - x, g: (L, N)
x = x_full[1:]
g = g_full[1:]
phi, logQ_phi = bfgs_sample(
num_samples=num_elbo_draws, x=x, g=g, alpha=alpha, beta=beta, gamma=gamma
)
loglike = LogLike(logp_func)
logP_phi = loglike(phi)
elbo = pt.mean(logP_phi - logQ_phi, axis=-1)
elbo_argmax = pt.argmax(elbo, axis=0)
# TODO: move the raise PathInvalidLogQ from single_pathfinder_fn to here to avoid computing logP_psi if logQ_psi is invalid. Possible setup: logQ_phi = PathCheck()(logQ_phi, ~pt.all(mask)), where PathCheck uses pytensor raise.
# sample from the single-path approximation
psi, logQ_psi = bfgs_sample(
num_samples=num_draws,
x=x,
g=g,
alpha=alpha,
beta=beta,
gamma=gamma,
index=elbo_argmax,
)
logP_psi = loglike(psi)
# return psi, logP_psi, logQ_psi, elbo_argmax
pathfinder_body_fn = compile_pymc(
[x_full, g_full],
[psi, logP_psi, logQ_psi, elbo_argmax],
**compile_kwargs,
)
pathfinder_body_fn.trust_input = True
return pathfinder_body_fn
def make_single_pathfinder_fn(
model,
num_draws: int,
maxcor: int | None,
maxiter: int,
ftol: float,
gtol: float,
maxls: int,
num_elbo_draws: int,
jitter: float,
epsilon: float,
pathfinder_kwargs: dict = {},
compile_kwargs: dict = {},
) -> SinglePathfinderFn:
"""
returns a seedable single-path pathfinder function, where it executes a compiled function that performs the local approximation and sampling part of the Pathfinder algorithm.
Parameters
----------
model : pymc.Model
The PyMC model to fit the Pathfinder algorithm to.
num_draws : int
Number of samples to draw from the single-path approximation.
maxcor : int | None
Maximum number of iterations for the L-BFGS optimisation.
maxiter : int
Maximum number of iterations for the L-BFGS optimisation.
ftol : float
Tolerance for the decrease in the objective function.
gtol : float
Tolerance for the norm of the gradient.
maxls : int
Maximum number of line search steps for the L-BFGS algorithm.
num_elbo_draws : int
Number of draws for the Evidence Lower Bound (ELBO) estimation.
jitter : float
Amount of jitter to apply to initial points. Note that Pathfinder may be highly sensitive to the jitter value. It is recommended to increase num_paths when increasing the jitter value.
epsilon : float
value used to filter out large changes in the direction of the update gradient at each iteration l in L. Iteration l is only accepted if delta_theta[l] * delta_grad[l] > epsilon * L2_norm(delta_grad[l]) for each l in L.
pathfinder_kwargs : dict
Additional keyword arguments for the Pathfinder algorithm.
compile_kwargs : dict
Additional keyword arguments for the PyTensor compiler. If not provided, the default linker is "cvm_nogc".
Returns
-------
single_pathfinder_fn : Callable
A seedable single-path pathfinder function.
"""
compile_kwargs = {"mode": Mode(linker=DEFAULT_LINKER), **compile_kwargs}
logp_dlogp_kwargs = {"jacobian": pathfinder_kwargs.get("jacobian", True), **compile_kwargs}
logp_dlogp_func = get_logp_dlogp_of_ravel_inputs(model, **logp_dlogp_kwargs)
def logp_func(x):
logp, _ = logp_dlogp_func(x)
return logp
def neg_logp_dlogp_func(x):
logp, dlogp = logp_dlogp_func(x)
return -logp, -dlogp
# initial point
# TODO: remove make_initial_points function when feature request is implemented: https://github.com/pymc-devs/pymc/issues/7555
ipfn = make_initial_point_fn(model=model)
ip = Point(ipfn(None), model=model)
x_base = DictToArrayBijection.map(ip).data
# lbfgs
lbfgs = LBFGS(neg_logp_dlogp_func, maxcor, maxiter, ftol, gtol, maxls)
# pathfinder body
pathfinder_body_fn = make_pathfinder_body(
logp_func, num_draws, maxcor, num_elbo_draws, epsilon, **compile_kwargs
)
rngs = find_rng_nodes(pathfinder_body_fn.maker.fgraph.outputs)
def single_pathfinder_fn(random_seed: int) -> PathfinderResult:
try:
init_seed, *bfgs_seeds = _get_seeds_per_chain(random_seed, 3)
rng = np.random.default_rng(init_seed)
jitter_value = rng.uniform(-jitter, jitter, size=x_base.shape)
x0 = x_base + jitter_value
x, g, lbfgs_niter, lbfgs_status = lbfgs.minimize(x0)
if lbfgs_status == LBFGSStatus.INIT_FAILED:
raise LBFGSInitFailed()
elif lbfgs_status == LBFGSStatus.LBFGS_FAILED:
raise LBFGSException()
reseed_rngs(rngs, bfgs_seeds)
psi, logP_psi, logQ_psi, elbo_argmax = pathfinder_body_fn(x, g)
if np.all(~np.isfinite(logQ_psi)):
raise PathInvalidLogQ()
if elbo_argmax == 0:
path_status = PathStatus.ELBO_ARGMAX_AT_ZERO
else:
path_status = PathStatus.SUCCESS
return PathfinderResult(
samples=psi,
logP=logP_psi,
logQ=logQ_psi,
lbfgs_niter=lbfgs_niter,
elbo_argmax=elbo_argmax,
lbfgs_status=lbfgs_status,
path_status=path_status,
)
except LBFGSException as e:
return PathfinderResult(
lbfgs_status=e.status,
path_status=PathStatus.LBFGS_FAILED,
)
except PathException as e:
return PathfinderResult(
lbfgs_status=lbfgs_status,
path_status=e.status,
)
return single_pathfinder_fn
def _calculate_max_workers() -> int:
"""
calculate the default number of workers to use for concurrent pathfinder runs.
"""
# from limited testing, setting values higher than 0.3 makes multiprocessing a lot slower.
import multiprocessing