-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathmcmc.py
1429 lines (1267 loc) · 49.3 KB
/
mcmc.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 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.
"""Functions for MCMC sampling."""
import logging
import pickle
import sys
import time
import warnings
from collections import defaultdict
from typing import (
Any,
Dict,
Iterator,
List,
Literal,
Optional,
Sequence,
Tuple,
Union,
overload,
)
import numpy as np
import pytensor.gradient as tg
from arviz import InferenceData
from fastprogress.fastprogress import progress_bar
from typing_extensions import Protocol, TypeAlias
import pymc as pm
from pymc.backends import RunType, TraceOrBackend, init_traces
from pymc.backends.base import IBaseTrace, MultiTrace, _choose_chains
from pymc.blocking import DictToArrayBijection
from pymc.exceptions import SamplingError
from pymc.initial_point import PointType, StartDict, make_initial_point_fns_per_chain
from pymc.model import Model, modelcontext
from pymc.sampling.parallel import Draw, _cpu_count
from pymc.sampling.population import _sample_population
from pymc.stats.convergence import (
log_warning_stats,
log_warnings,
run_convergence_checks,
)
from pymc.step_methods import NUTS, CompoundStep
from pymc.step_methods.arraystep import BlockedStep, PopulationArrayStepShared
from pymc.step_methods.hmc import quadpotential
from pymc.util import (
RandomSeed,
RandomState,
_get_seeds_per_chain,
drop_warning_stat,
get_untransformed_name,
is_transformed_name,
)
from pymc.vartypes import discrete_types
sys.setrecursionlimit(10000)
__all__ = [
"sample",
"init_nuts",
]
Step: TypeAlias = Union[BlockedStep, CompoundStep]
class SamplingIteratorCallback(Protocol):
"""Signature of the callable that may be passed to `pm.sample(callable=...)`."""
def __call__(self, trace: IBaseTrace, draw: Draw):
pass
_log = logging.getLogger(__name__)
def instantiate_steppers(
model, steps: List[Step], selected_steps, step_kwargs=None
) -> Union[Step, List[Step]]:
"""Instantiate steppers assigned to the model variables.
This function is intended to be called automatically from ``sample()``, but
may be called manually.
Parameters
----------
model : Model object
A fully-specified model object.
steps : list, array_like of shape (selected_steps, )
A list of zero or more step function instances that have been assigned to some subset of
the model's parameters.
selected_steps : dict
A dictionary that maps a step method class to a list of zero or more model variables.
step_kwargs : dict, default=None
Parameters for the samplers. Keys are the lower case names of
the step method, values a dict of arguments. Defaults to None.
Returns
-------
methods : list or step
List of step methods associated with the model's variables, or step method
if there is only one.
"""
if step_kwargs is None:
step_kwargs = {}
used_keys = set()
for step_class, vars in selected_steps.items():
if vars:
args = step_kwargs.get(step_class.name, {})
used_keys.add(step_class.name)
step = step_class(vars=vars, model=model, **args)
steps.append(step)
unused_args = set(step_kwargs).difference(used_keys)
if unused_args:
raise ValueError("Unused step method arguments: %s" % unused_args)
if len(steps) == 1:
return steps[0]
return steps
def assign_step_methods(model, step=None, methods=None, step_kwargs=None):
"""Assign model variables to appropriate step methods.
Passing a specified model will auto-assign its constituent stochastic
variables to step methods based on the characteristics of the variables.
This function is intended to be called automatically from ``sample()``, but
may be called manually. Each step method passed should have a
``competence()`` method that returns an ordinal competence value
corresponding to the variable passed to it. This value quantifies the
appropriateness of the step method for sampling the variable.
Parameters
----------
model : Model object
A fully-specified model object.
step : step function or iterable of step functions, optional
One or more step functions that have been assigned to some subset of
the model's parameters. Defaults to ``None`` (no assigned variables).
methods : iterable of step method classes, optional
The set of step methods from which the function may choose. Defaults
to the main step methods provided by PyMC.
step_kwargs : dict, optional
Parameters for the samplers. Keys are the lower case names of
the step method, values a dict of arguments.
Returns
-------
methods : list
List of step methods associated with the model's variables.
"""
steps = []
assigned_vars = set()
if methods is None:
methods = pm.STEP_METHODS
if step is not None:
try:
steps += list(step)
except TypeError:
steps.append(step)
for step in steps:
for var in step.vars:
if var not in model.value_vars:
raise ValueError(
f"{var} assigned to {step} sampler is not a value variable in the model. You can use `util.get_value_vars_from_user_vars` to parse user provided variables."
)
assigned_vars = assigned_vars.union(set(step.vars))
# Use competence classmethods to select step methods for remaining
# variables
selected_steps = defaultdict(list)
model_logp = model.logp()
for var in model.value_vars:
if var not in assigned_vars:
# determine if a gradient can be computed
has_gradient = var.dtype not in discrete_types
if has_gradient:
try:
tg.grad(model_logp, var)
except (NotImplementedError, tg.NullTypeGradError):
has_gradient = False
# select the best method
rv_var = model.values_to_rvs[var]
selected = max(
methods,
key=lambda method, var=rv_var, has_gradient=has_gradient: method._competence(
var, has_gradient
),
)
selected_steps[selected].append(var)
return instantiate_steppers(model, steps, selected_steps, step_kwargs)
def _print_step_hierarchy(s: Step, level: int = 0) -> None:
if isinstance(s, CompoundStep):
_log.info(">" * level + "CompoundStep")
for i in s.methods:
_print_step_hierarchy(i, level + 1)
else:
varnames = ", ".join(
[
get_untransformed_name(v.name) if is_transformed_name(v.name) else v.name
for v in s.vars
]
)
_log.info(">" * level + f"{s.__class__.__name__}: [{varnames}]")
def all_continuous(vars):
"""Check that vars not include discrete variables"""
if any([(var.dtype in discrete_types) for var in vars]):
return False
else:
return True
def _sample_external_nuts(
sampler: str,
draws: int,
tune: int,
chains: int,
target_accept: float,
random_seed: Union[RandomState, None],
initvals: Union[StartDict, Sequence[Optional[StartDict]], None],
model: Model,
progressbar: bool,
idata_kwargs: Optional[Dict],
nuts_sampler_kwargs: Optional[Dict],
**kwargs,
):
warnings.warn("Use of external NUTS sampler is still experimental", UserWarning)
if nuts_sampler_kwargs is None:
nuts_sampler_kwargs = {}
if sampler == "nutpie":
try:
import nutpie
except ImportError as err:
raise ImportError(
"nutpie not found. Install it with conda install -c conda-forge nutpie"
) from err
if initvals is not None:
warnings.warn(
"`initvals` are currently not passed to nutpie sampler. "
"Use `init_mean` kwarg following nutpie specification instead.",
UserWarning,
)
if idata_kwargs is not None:
warnings.warn(
"`idata_kwargs` are currently ignored by the nutpie sampler",
UserWarning,
)
compiled_model = nutpie.compile_pymc_model(model)
idata = nutpie.sample(
compiled_model,
draws=draws,
tune=tune,
chains=chains,
target_accept=target_accept,
seed=_get_seeds_per_chain(random_seed, 1)[0],
progress_bar=progressbar,
**nuts_sampler_kwargs,
)
return idata
elif sampler == "numpyro":
import pymc.sampling.jax as pymc_jax
idata = pymc_jax.sample_numpyro_nuts(
draws=draws,
tune=tune,
chains=chains,
target_accept=target_accept,
random_seed=random_seed,
initvals=initvals,
model=model,
progressbar=progressbar,
idata_kwargs=idata_kwargs,
**nuts_sampler_kwargs,
)
return idata
elif sampler == "blackjax":
import pymc.sampling.jax as pymc_jax
idata = pymc_jax.sample_blackjax_nuts(
draws=draws,
tune=tune,
chains=chains,
target_accept=target_accept,
random_seed=random_seed,
initvals=initvals,
model=model,
idata_kwargs=idata_kwargs,
**nuts_sampler_kwargs,
)
return idata
else:
raise ValueError(
f"Sampler {sampler} not found. Choose one of ['nutpie', 'numpyro', 'blackjax', 'pymc']."
)
@overload
def sample(
draws: int = 1000,
*,
tune: int = 1000,
chains: Optional[int] = None,
cores: Optional[int] = None,
random_seed: RandomState = None,
progressbar: bool = True,
step=None,
nuts_sampler: str = "pymc",
initvals: Optional[Union[StartDict, Sequence[Optional[StartDict]]]] = None,
init: str = "auto",
jitter_max_retries: int = 10,
n_init: int = 200_000,
trace: Optional[TraceOrBackend] = None,
discard_tuned_samples: bool = True,
compute_convergence_checks: bool = True,
keep_warning_stat: bool = False,
return_inferencedata: Literal[True] = True,
idata_kwargs: Optional[Dict[str, Any]] = None,
nuts_sampler_kwargs: Optional[Dict[str, Any]] = None,
callback=None,
mp_ctx=None,
**kwargs,
) -> InferenceData:
...
@overload
def sample(
draws: int = 1000,
*,
tune: int = 1000,
chains: Optional[int] = None,
cores: Optional[int] = None,
random_seed: RandomState = None,
progressbar: bool = True,
step=None,
nuts_sampler: str = "pymc",
initvals: Optional[Union[StartDict, Sequence[Optional[StartDict]]]] = None,
init: str = "auto",
jitter_max_retries: int = 10,
n_init: int = 200_000,
trace: Optional[TraceOrBackend] = None,
discard_tuned_samples: bool = True,
compute_convergence_checks: bool = True,
keep_warning_stat: bool = False,
return_inferencedata: Literal[False],
idata_kwargs: Optional[Dict[str, Any]] = None,
nuts_sampler_kwargs: Optional[Dict[str, Any]] = None,
callback=None,
mp_ctx=None,
model: Optional[Model] = None,
**kwargs,
) -> MultiTrace:
...
def sample(
draws: int = 1000,
*,
tune: int = 1000,
chains: Optional[int] = None,
cores: Optional[int] = None,
random_seed: RandomState = None,
progressbar: bool = True,
step=None,
nuts_sampler: str = "pymc",
initvals: Optional[Union[StartDict, Sequence[Optional[StartDict]]]] = None,
init: str = "auto",
jitter_max_retries: int = 10,
n_init: int = 200_000,
trace: Optional[TraceOrBackend] = None,
discard_tuned_samples: bool = True,
compute_convergence_checks: bool = True,
keep_warning_stat: bool = False,
return_inferencedata: bool = True,
idata_kwargs: Optional[Dict[str, Any]] = None,
nuts_sampler_kwargs: Optional[Dict[str, Any]] = None,
callback=None,
mp_ctx=None,
model: Optional[Model] = None,
**kwargs,
) -> Union[InferenceData, MultiTrace]:
r"""Draw samples from the posterior using the given step methods.
Multiple step methods are supported via compound step methods.
Parameters
----------
draws : int
The number of samples to draw. Defaults to 1000. The number of tuned samples are discarded
by default. See ``discard_tuned_samples``.
tune : int
Number of iterations to tune, defaults to 1000. Samplers adjust the step sizes, scalings or
similar during tuning. Tuning samples will be drawn in addition to the number specified in
the ``draws`` argument, and will be discarded unless ``discard_tuned_samples`` is set to
False.
chains : int
The number of chains to sample. Running independent chains is important for some
convergence statistics and can also reveal multiple modes in the posterior. If ``None``,
then set to either ``cores`` or 2, whichever is larger.
cores : int
The number of chains to run in parallel. If ``None``, set to the number of CPUs in the
system, but at most 4.
random_seed : int, array-like of int, RandomState or Generator, optional
Random seed(s) used by the sampling steps. If a list, tuple or array of ints
is passed, each entry will be used to seed each chain. A ValueError will be
raised if the length does not match the number of chains.
progressbar : bool, optional default=True
Whether or not to display a progress bar in the command line. The bar shows the percentage
of completion, the sampling speed in samples per second (SPS), and the estimated remaining
time until completion ("expected time of arrival"; ETA).
Only applicable to the pymc nuts sampler.
step : function or iterable of functions
A step function or collection of functions. If there are variables without step methods,
step methods for those variables will be assigned automatically. By default the NUTS step
method will be used, if appropriate to the model.
nuts_sampler : str
Which NUTS implementation to run. One of ["pymc", "nutpie", "blackjax", "numpyro"].
This requires the chosen sampler to be installed.
All samplers, except "pymc", require the full model to be continuous.
initvals : optional, dict, array of dict
Dict or list of dicts with initial value strategies to use instead of the defaults from
`Model.initial_values`. The keys should be names of transformed random variables.
Initialization methods for NUTS (see ``init`` keyword) can overwrite the default.
init : str
Initialization method to use for auto-assigned NUTS samplers. See `pm.init_nuts` for a list
of all options. This argument is ignored when manually passing the NUTS step method.
Only applicable to the pymc nuts sampler.
jitter_max_retries : int
Maximum number of repeated attempts (per chain) at creating an initial matrix with uniform
jitter that yields a finite probability. This applies to ``jitter+adapt_diag`` and
``jitter+adapt_full`` init methods.
n_init : int
Number of iterations of initializer. Only works for 'ADVI' init methods.
trace : backend, optional
A backend instance or None.
If None, the NDArray backend is used.
discard_tuned_samples : bool
Whether to discard posterior samples of the tune interval.
compute_convergence_checks : bool, default=True
Whether to compute sampler statistics like Gelman-Rubin and ``effective_n``.
keep_warning_stat : bool
If ``True`` the "warning" stat emitted by, for example, HMC samplers will be kept
in the returned ``idata.sample_stat`` group.
This leads to the ``idata`` not supporting ``.to_netcdf()`` or ``.to_zarr()`` and
should only be set to ``True`` if you intend to use the "warning" objects right away.
Defaults to ``False`` such that ``pm.drop_warning_stat`` is applied automatically,
making the ``InferenceData`` compatible with saving.
return_inferencedata : bool
Whether to return the trace as an :class:`arviz:arviz.InferenceData` (True) object or a
`MultiTrace` (False). Defaults to `True`.
idata_kwargs : dict, optional
Keyword arguments for :func:`pymc.to_inference_data`
nuts_sampler_kwargs : dict, optional
Keyword arguments for the sampling library that implements nuts.
Only used when an external sampler is specified via the `nuts_sampler` kwarg.
callback : function, default=None
A function which gets called for every sample from the trace of a chain. The function is
called with the trace and the current draw and will contain all samples for a single trace.
the ``draw.chain`` argument can be used to determine which of the active chains the sample
is drawn from.
Sampling can be interrupted by throwing a ``KeyboardInterrupt`` in the callback.
mp_ctx : multiprocessing.context.BaseContent
A multiprocessing context for parallel sampling.
See multiprocessing documentation for details.
model : Model (optional if in ``with`` context)
Model to sample from. The model needs to have free random variables.
Returns
-------
trace : pymc.backends.base.MultiTrace or arviz.InferenceData
A ``MultiTrace`` or ArviZ ``InferenceData`` object that contains the samples.
Notes
-----
Optional keyword arguments can be passed to ``sample`` to be delivered to the
``step_method``\ s used during sampling.
For example:
1. ``target_accept`` to NUTS: nuts={'target_accept':0.9}
2. ``transit_p`` to BinaryGibbsMetropolis: binary_gibbs_metropolis={'transit_p':.7}
Note that available step names are:
``nuts``, ``hmc``, ``metropolis``, ``binary_metropolis``,
``binary_gibbs_metropolis``, ``categorical_gibbs_metropolis``,
``DEMetropolis``, ``DEMetropolisZ``, ``slice``
The NUTS step method has several options including:
* target_accept : float in [0, 1]. The step size is tuned such that we
approximate this acceptance rate. Higher values like 0.9 or 0.95 often
work better for problematic posteriors. This argument can be passed directly to sample.
* max_treedepth : The maximum depth of the trajectory tree
* step_scale : float, default 0.25
The initial guess for the step size scaled down by :math:`1/n**(1/4)`,
where n is the dimensionality of the parameter space
Alternatively, if you manually declare the ``step_method``\ s, within the ``step``
kwarg, then you can address the ``step_method`` kwargs directly.
e.g. for a CompoundStep comprising NUTS and BinaryGibbsMetropolis,
you could send ::
step=[pm.NUTS([freeRV1, freeRV2], target_accept=0.9),
pm.BinaryGibbsMetropolis([freeRV3], transit_p=.7)]
You can find a full list of arguments in the docstring of the step methods.
Examples
--------
.. code:: ipython
In [1]: import pymc as pm
...: n = 100
...: h = 61
...: alpha = 2
...: beta = 2
In [2]: with pm.Model() as model: # context management
...: p = pm.Beta("p", alpha=alpha, beta=beta)
...: y = pm.Binomial("y", n=n, p=p, observed=h)
...: idata = pm.sample()
In [3]: az.summary(idata, kind="stats")
Out[3]:
mean sd hdi_3% hdi_97%
p 0.609 0.047 0.528 0.699
"""
if "start" in kwargs:
if initvals is not None:
raise ValueError("Passing both `start` and `initvals` is not supported.")
warnings.warn(
"The `start` kwarg was renamed to `initvals` and can now do more. Please check the docstring.",
FutureWarning,
stacklevel=2,
)
initvals = kwargs.pop("start")
if nuts_sampler_kwargs is None:
nuts_sampler_kwargs = {}
if "target_accept" in kwargs:
if "nuts" in kwargs and "target_accept" in kwargs["nuts"]:
raise ValueError(
"`target_accept` was defined twice. Please specify it either as a direct keyword argument or in the `nuts` kwarg."
)
if "nuts" in kwargs:
kwargs["nuts"]["target_accept"] = kwargs.pop("target_accept")
else:
kwargs["nuts"] = {"target_accept": kwargs.pop("target_accept")}
if isinstance(trace, list):
raise DeprecationWarning(
"We have removed support for partial traces because it simplified things."
" Please open an issue if & why this is a problem for you."
)
model = modelcontext(model)
if not model.free_RVs:
raise SamplingError(
"Cannot sample from the model, since the model does not contain any free variables."
)
if cores is None:
cores = min(4, _cpu_count())
if chains is None:
chains = max(2, cores)
if random_seed == -1:
random_seed = None
random_seed_list = _get_seeds_per_chain(random_seed, chains)
if not discard_tuned_samples and not return_inferencedata:
warnings.warn(
"Tuning samples will be included in the returned `MultiTrace` object, which can lead to"
" complications in your downstream analysis. Please consider to switch to `InferenceData`:\n"
"`pm.sample(..., return_inferencedata=True)`",
UserWarning,
stacklevel=2,
)
# small trace warning
if draws == 0:
msg = "Tuning was enabled throughout the whole trace."
_log.warning(msg)
elif draws < 500:
msg = "Only %s samples in chain." % draws
_log.warning(msg)
auto_nuts_init = True
if step is not None:
if isinstance(step, CompoundStep):
for method in step.methods:
if isinstance(method, NUTS):
auto_nuts_init = False
elif isinstance(step, NUTS):
auto_nuts_init = False
initial_points = None
step = assign_step_methods(model, step, methods=pm.STEP_METHODS, step_kwargs=kwargs)
if nuts_sampler != "pymc":
if not isinstance(step, NUTS):
raise ValueError(
"Model can not be sampled with NUTS alone. Your model is probably not continuous."
)
return _sample_external_nuts(
sampler=nuts_sampler,
draws=draws,
tune=tune,
chains=chains,
target_accept=kwargs.pop("nuts", {}).get("target_accept", 0.8),
random_seed=random_seed,
initvals=initvals,
model=model,
progressbar=progressbar,
idata_kwargs=idata_kwargs,
nuts_sampler_kwargs=nuts_sampler_kwargs,
**kwargs,
)
if isinstance(step, list):
step = CompoundStep(step)
elif isinstance(step, NUTS) and auto_nuts_init:
if "nuts" in kwargs:
nuts_kwargs = kwargs.pop("nuts")
[kwargs.setdefault(k, v) for k, v in nuts_kwargs.items()]
_log.info("Auto-assigning NUTS sampler...")
initial_points, step = init_nuts(
init=init,
chains=chains,
n_init=n_init,
model=model,
random_seed=random_seed_list,
progressbar=progressbar,
jitter_max_retries=jitter_max_retries,
tune=tune,
initvals=initvals,
**kwargs,
)
if initial_points is None:
# Time to draw/evaluate numeric start points for each chain.
ipfns = make_initial_point_fns_per_chain(
model=model,
overrides=initvals,
jitter_rvs=set(),
chains=chains,
)
initial_points = [ipfn(seed) for ipfn, seed in zip(ipfns, random_seed_list)]
# One final check that shapes and logps at the starting points are okay.
ip: Dict[str, np.ndarray]
for ip in initial_points:
model.check_start_vals(ip)
_check_start_shape(model, ip)
# Create trace backends for each chain
run, traces = init_traces(
backend=trace,
chains=chains,
expected_length=draws + tune,
step=step,
initial_point=ip,
model=model,
)
sample_args = {
"draws": draws + tune, # FIXME: Why is tune added to draws?
"step": step,
"start": initial_points,
"traces": traces,
"chains": chains,
"tune": tune,
"progressbar": progressbar,
"model": model,
"cores": cores,
"callback": callback,
"discard_tuned_samples": discard_tuned_samples,
}
parallel_args = {
"mp_ctx": mp_ctx,
}
sample_args.update(kwargs)
has_population_samplers = np.any(
[
isinstance(m, PopulationArrayStepShared)
for m in (step.methods if isinstance(step, CompoundStep) else [step])
]
)
parallel = cores > 1 and chains > 1 and not has_population_samplers
# At some point it was decided that PyMC should not set a global seed by default,
# unless the user specified a seed. This is a symptom of the fact that PyMC samplers
# are built around global seeding. This branch makes sure we maintain this unspoken
# rule. See https://github.com/pymc-devs/pymc/pull/1395.
if parallel:
# For parallel sampling we can pass the list of random seeds directly, as
# global seeding will only be called inside each process
sample_args["random_seed"] = random_seed_list
else:
# We pass None if the original random seed was None. The single core sampler
# methods will only set a global seed when it is not None.
sample_args["random_seed"] = random_seed if random_seed is None else random_seed_list
t_start = time.time()
if parallel:
_log.info(f"Multiprocess sampling ({chains} chains in {cores} jobs)")
_print_step_hierarchy(step)
try:
_mp_sample(**sample_args, **parallel_args)
except pickle.PickleError:
_log.warning("Could not pickle model, sampling singlethreaded.")
_log.debug("Pickling error:", exc_info=True)
parallel = False
except AttributeError as e:
if not str(e).startswith("AttributeError: Can't pickle"):
raise
_log.warning("Could not pickle model, sampling singlethreaded.")
_log.debug("Pickling error:", exc_info=True)
parallel = False
if not parallel:
if has_population_samplers:
_log.info(f"Population sampling ({chains} chains)")
_print_step_hierarchy(step)
_sample_population(initial_points=initial_points, parallelize=cores > 1, **sample_args)
else:
_log.info(f"Sequential sampling ({chains} chains in 1 job)")
_print_step_hierarchy(step)
_sample_many(**sample_args)
t_sampling = time.time() - t_start
# Packaging, validating and returning the result was extracted
# into a function to make it easier to test and refactor.
return _sample_return(
run=run,
traces=traces,
tune=tune,
t_sampling=t_sampling,
discard_tuned_samples=discard_tuned_samples,
compute_convergence_checks=compute_convergence_checks,
return_inferencedata=return_inferencedata,
keep_warning_stat=keep_warning_stat,
idata_kwargs=idata_kwargs or {},
model=model,
)
def _sample_return(
*,
run: Optional[RunType],
traces: Sequence[IBaseTrace],
tune: int,
t_sampling: float,
discard_tuned_samples: bool,
compute_convergence_checks: bool,
return_inferencedata: bool,
keep_warning_stat: bool,
idata_kwargs: Dict[str, Any],
model: Model,
) -> Union[InferenceData, MultiTrace]:
"""Final step of `pm.sampler` that picks/slices chains,
runs diagnostics and converts to the desired return type."""
# Pick and slice chains to keep the maximum number of samples
if discard_tuned_samples:
traces, length = _choose_chains(traces, tune)
else:
traces, length = _choose_chains(traces, 0)
mtrace = MultiTrace(traces)[:length]
# count the number of tune/draw iterations that happened
# ideally via the "tune" statistic, but not all samplers record it!
if "tune" in mtrace.stat_names:
# Get the tune stat directly from chain 0, sampler 0
stat = mtrace._straces[0].get_sampler_stats("tune", sampler_idx=0)
stat = tuple(stat)
n_tune = stat.count(True)
n_draws = stat.count(False)
else:
# these may be wrong when KeyboardInterrupt happened, but they're better than nothing
n_tune = min(tune, len(mtrace))
n_draws = max(0, len(mtrace) - n_tune)
if discard_tuned_samples:
mtrace = mtrace[n_tune:]
# save metadata in SamplerReport
mtrace.report._n_tune = n_tune
mtrace.report._n_draws = n_draws
mtrace.report._t_sampling = t_sampling
n_chains = len(mtrace.chains)
_log.info(
f'Sampling {n_chains} chain{"s" if n_chains > 1 else ""} for {n_tune:_d} tune and {n_draws:_d} draw iterations '
f"({n_tune*n_chains:_d} + {n_draws*n_chains:_d} draws total) "
f"took {t_sampling:.0f} seconds."
)
idata = None
if compute_convergence_checks or return_inferencedata:
ikwargs: Dict[str, Any] = dict(model=model, save_warmup=not discard_tuned_samples)
ikwargs.update(idata_kwargs)
idata = pm.to_inference_data(mtrace, **ikwargs)
if compute_convergence_checks:
warns = run_convergence_checks(idata, model)
mtrace.report._add_warnings(warns)
log_warnings(warns)
if return_inferencedata:
# By default we drop the "warning" stat which contains `SamplerWarning`
# objects that can not be stored with `.to_netcdf()`.
if not keep_warning_stat:
return drop_warning_stat(idata)
return idata
return mtrace
def _check_start_shape(model, start: PointType):
"""Checks that the prior evaluations and initial points have identical shapes.
Parameters
----------
model : pm.Model
The current model on context.
start : dict
The complete dictionary mapping (transformed) variable names to numeric initial values.
"""
e = ""
try:
actual_shapes = model.eval_rv_shapes()
except NotImplementedError as ex:
warnings.warn(f"Unable to validate shapes: {ex.args[0]}", UserWarning)
return
for name, sval in start.items():
ashape = actual_shapes.get(name)
sshape = np.shape(sval)
if ashape != tuple(sshape):
e += f"\nExpected shape {ashape} for var '{name}', got: {sshape}"
if e != "":
raise ValueError(f"Bad shape in start point:{e}")
def _sample_many(
*,
draws: int,
chains: int,
traces: Sequence[IBaseTrace],
start: Sequence[PointType],
random_seed: Optional[Sequence[RandomSeed]],
step: Step,
callback: Optional[SamplingIteratorCallback] = None,
**kwargs,
):
"""Samples all chains sequentially.
Parameters
----------
draws: int
The number of samples to draw
chains: int
Total number of chains to sample.
start: list
Starting points for each chain
random_seed: list of random seeds, optional
A list of seeds, one for each chain
step: function
Step function
"""
for i in range(chains):
_sample(
draws=draws,
chain=i,
start=start[i],
step=step,
trace=traces[i],
random_seed=None if random_seed is None else random_seed[i],
callback=callback,
**kwargs,
)
return
def _sample(
*,
chain: int,
progressbar: bool,
random_seed: RandomSeed,
start: PointType,
draws: int,
step: Step,
trace: IBaseTrace,
tune: int,
model: Optional[Model] = None,
callback=None,
**kwargs,
) -> None:
"""Main iteration for singleprocess sampling.
Multiple step methods are supported via compound step methods.
Parameters
----------
chain : int
Number of the chain that the samples will belong to.
progressbar : bool
Whether or not to display a progress bar in the command line. The bar shows the percentage
of completion, the sampling speed in samples per second (SPS), and the estimated remaining
time until completion ("expected time of arrival"; ETA).
random_seed : single random seed
start : dict
Starting point in parameter space (or partial point)
draws : int
The number of samples to draw
step : function
Step function
trace
A chain backend to record draws and stats.
tune : int
Number of iterations to tune.
model : Model (optional if in ``with`` context)
"""
skip_first = kwargs.get("skip_first", 0)
sampling_gen = _iter_sample(
draws=draws,
step=step,
start=start,
trace=trace,
chain=chain,
tune=tune,
model=model,
random_seed=random_seed,
callback=callback,
)
_pbar_data = {"chain": chain, "divergences": 0}
_desc = "Sampling chain {chain:d}, {divergences:,d} divergences"
if progressbar:
sampling = progress_bar(sampling_gen, total=draws, display=progressbar)
sampling.comment = _desc.format(**_pbar_data)
else:
sampling = sampling_gen
try:
for it, diverging in enumerate(sampling):
if it >= skip_first and diverging:
_pbar_data["divergences"] += 1
if progressbar:
sampling.comment = _desc.format(**_pbar_data)
except KeyboardInterrupt:
pass
def _iter_sample(
*,
draws: int,
step: Step,
start: PointType,
trace: IBaseTrace,
chain: int = 0,
tune: int = 0,
model: Optional[Model] = None,
random_seed: RandomSeed = None,
callback: Optional[SamplingIteratorCallback] = None,