|
| 1 | +# Copyright 2025 - present The PyMC Developers |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import warnings |
| 15 | + |
| 16 | +from arviz import InferenceData, dict_to_dataset |
| 17 | +from pytensor.scalar import discrete_dtypes |
| 18 | + |
| 19 | +from pymc.backends.arviz import coords_and_dims_for_inferencedata, find_constants, find_observations |
| 20 | +from pymc.sampling.external.base import ExternalSampler |
| 21 | +from pymc.stats.convergence import log_warnings, run_convergence_checks |
| 22 | +from pymc.util import _get_seeds_per_chain |
| 23 | + |
| 24 | + |
| 25 | +class Nutpie(ExternalSampler): |
| 26 | + def __init__( |
| 27 | + self, |
| 28 | + vars=None, |
| 29 | + model=None, |
| 30 | + backend="numba", |
| 31 | + gradient_backend="pytensor", |
| 32 | + compile_kwargs=None, |
| 33 | + sample_kwargs=None, |
| 34 | + ): |
| 35 | + super().__init__(vars, model) |
| 36 | + if any(var.dtype in discrete_dtypes for var in self.vars): |
| 37 | + raise ValueError("Nutpie can only sample continuous variables") |
| 38 | + self.backend = backend |
| 39 | + self.gradient_backend = gradient_backend |
| 40 | + self.compile_kwargs = compile_kwargs or {} |
| 41 | + self.sample_kwargs = sample_kwargs or {} |
| 42 | + |
| 43 | + def sample( |
| 44 | + self, |
| 45 | + *, |
| 46 | + tune, |
| 47 | + draws, |
| 48 | + chains, |
| 49 | + initvals, |
| 50 | + random_seed, |
| 51 | + progressbar, |
| 52 | + var_names, |
| 53 | + idata_kwargs, |
| 54 | + compute_convergence_checks, |
| 55 | + **kwargs, |
| 56 | + ): |
| 57 | + try: |
| 58 | + import nutpie |
| 59 | + except ImportError as err: |
| 60 | + raise ImportError( |
| 61 | + "nutpie not found. Install it with conda install -c conda-forge nutpie" |
| 62 | + ) from err |
| 63 | + |
| 64 | + from nutpie.sample import _BackgroundSampler |
| 65 | + |
| 66 | + if initvals: |
| 67 | + warnings.warn( |
| 68 | + "initvals are currently ignored by the nutpie sampler.", |
| 69 | + UserWarning, |
| 70 | + ) |
| 71 | + if idata_kwargs: |
| 72 | + warnings.warn( |
| 73 | + "idata_kwargs are currently ignored by the nutpie sampler.", |
| 74 | + UserWarning, |
| 75 | + ) |
| 76 | + |
| 77 | + compiled_model = nutpie.compile_pymc_model( |
| 78 | + self.model, |
| 79 | + var_names=var_names, |
| 80 | + backend=self.backend, |
| 81 | + gradient_backend=self.gradient_backend, |
| 82 | + **self.compile_kwargs, |
| 83 | + ) |
| 84 | + |
| 85 | + result = nutpie.sample( |
| 86 | + compiled_model, |
| 87 | + tune=tune, |
| 88 | + draws=draws, |
| 89 | + chains=chains, |
| 90 | + seed=_get_seeds_per_chain(random_seed, 1)[0], |
| 91 | + progress_bar=progressbar, |
| 92 | + **self.sample_kwargs, |
| 93 | + **kwargs, |
| 94 | + ) |
| 95 | + if isinstance(result, _BackgroundSampler): |
| 96 | + # Wrap _BackgroundSampler so that when sampling is finished we run post_process_sampler |
| 97 | + class NutpieBackgroundSamplerWrapper(_BackgroundSampler): |
| 98 | + def __init__(self, *args, pymc_model, compute_convergence_checks, **kwargs): |
| 99 | + self.pymc_model = pymc_model |
| 100 | + self.compute_convergence_checks = compute_convergence_checks |
| 101 | + super().__init__(*args, **kwargs, return_raw_trace=False) |
| 102 | + |
| 103 | + def _extract(self, *args, **kwargs): |
| 104 | + idata = super()._extract(*args, **kwargs) |
| 105 | + return Nutpie._post_process_sample( |
| 106 | + model=self.pymc_model, |
| 107 | + idata=idata, |
| 108 | + compute_convergence_checks=self.compute_convergence_checks, |
| 109 | + ) |
| 110 | + |
| 111 | + # non-blocked sampling |
| 112 | + return NutpieBackgroundSamplerWrapper( |
| 113 | + result, |
| 114 | + pymc_model=self.model, |
| 115 | + compute_convergence_checks=compute_convergence_checks, |
| 116 | + ) |
| 117 | + else: |
| 118 | + return self._post_process_sample(self.model, result, compute_convergence_checks) |
| 119 | + |
| 120 | + @staticmethod |
| 121 | + def _post_process_sample( |
| 122 | + model, idata: InferenceData, compute_convergence_checks |
| 123 | + ) -> InferenceData: |
| 124 | + # Temporary work-around. Revert once https://github.com/pymc-devs/nutpie/issues/74 is fixed |
| 125 | + # gather observed and constant data as nutpie.sample() has no access to the PyMC model |
| 126 | + if compute_convergence_checks: |
| 127 | + log_warnings(run_convergence_checks(idata, model)) |
| 128 | + |
| 129 | + coords, dims = coords_and_dims_for_inferencedata(model) |
| 130 | + constant_data = dict_to_dataset( |
| 131 | + find_constants(model), |
| 132 | + library=idata.attrs.get("library", None), |
| 133 | + coords=coords, |
| 134 | + dims=dims, |
| 135 | + default_dims=[], |
| 136 | + ) |
| 137 | + observed_data = dict_to_dataset( |
| 138 | + find_observations(model), |
| 139 | + library=idata.attrs.get("library", None), |
| 140 | + coords=coords, |
| 141 | + dims=dims, |
| 142 | + default_dims=[], |
| 143 | + ) |
| 144 | + idata.add_groups( |
| 145 | + {"constant_data": constant_data, "observed_data": observed_data}, |
| 146 | + coords=coords, |
| 147 | + dims=dims, |
| 148 | + ) |
| 149 | + return idata |
0 commit comments