Coverage for src/bartz/_interface.py: 98%
1096 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-30 12:50 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-30 12:50 +0000
1# bartz/src/bartz/_interface.py
2#
3# Copyright (c) 2025-2026, The Bartz Contributors
4#
5# This file is part of bartz.
6#
7# Permission is hereby granted, free of charge, to any person obtaining a copy
8# of this software and associated documentation files (the "Software"), to deal
9# in the Software without restriction, including without limitation the rights
10# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11# copies of the Software, and to permit persons to whom the Software is
12# furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice shall be included in all
15# copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23# SOFTWARE.
25"""Main high-level interface of the package."""
27import pickle
28from collections.abc import Collection, Hashable, Mapping, Sequence
29from contextlib import AbstractContextManager, nullcontext
30from dataclasses import replace
31from enum import Enum
32from functools import cached_property
33from os import PathLike
34from pathlib import Path
36# WORKAROUND(python<3.15): use frozendict instead of MappingProxyType
37from types import MappingProxyType
38from typing import Any, Literal, Protocol, TypedDict, cast, runtime_checkable
39from warnings import warn
41import jax
42import jax.numpy as jnp
43from equinox import Module, error_if, field, tree_at
44from jax import Device, debug_nans, device_put, lax, make_mesh, random, tree, vmap
45from jax.nn import logmeanexp, softmax
46from jax.scipy.special import log_ndtr, ndtr, ndtri
47from jax.scipy.stats import norm
48from jax.sharding import AxisType, Mesh, NamedSharding, PartitionSpec
49from jax.typing import DTypeLike
50from jaxtyping import Array, Bool, Float, Float32, Int32, Key, Real, Shaped, UInt
51from numpy import ndarray
53from bartz._jaxext import (
54 equal_shards,
55 forbid_x64,
56 get_available_cpu_count,
57 is_key,
58 jit,
59 jit_active,
60 project,
61 solve_triangular,
62 split,
63)
64from bartz.grove import (
65 TreesTrace,
66 check_trace,
67 evaluate_forest,
68 format_tree,
69 points_per_node_distr,
70)
71from bartz.mcmcloop import (
72 BurninTrace,
73 Callback,
74 CallbackTuple,
75 CheckPlatformCallback,
76 MainTrace,
77 MainTraceWithTrainPred,
78 PrintCallback,
79 RunMCMCResult,
80 TqdmCallback,
81 VarprobInState,
82 compute_varcount,
83 evaluate_trace,
84 run_mcmc,
85)
86from bartz.mcmcstep import DiagWishart, Forest, OutcomeType, Wishart, make_p_nonterminal
87from bartz.mcmcstep._axes import chain_vmap_axes, trace_sample_axes
88from bartz.mcmcstep._state import (
89 ArrayLike,
90 FloatLike,
91 State,
92 chol_with_gersh,
93 init,
94 inv_via_chol_with_gersh,
95 leaf_partition_spec,
96 outcome_target,
97)
98from bartz.mcmcstep._step import _logdet_from_chol, count_selectable
99from bartz.npz import serializable
100from bartz.npz._npz import check_class, load_npz, save_npz
101from bartz.prepcovars import Binner, BinnerFactory, UniqueQuantileBinner
104class PredictKind(Enum):
105 R"""Kind of output of `Bart.predict`.
107 The shapes are for multivariate outcomes with ``k`` components, at ``m``
108 test points, with ``ndpost = num_chains * n_save`` posterior samples. For
109 univariate outcomes, drop the ``k`` axes. The kinds ending in
110 ``_samples`` have a value for each posterior sample, the others summarize
111 the posterior. The covariances are across the outcome components, at each
112 test point. The intervals have the lower and upper bounds along the first
113 axis.
115 In the formulas, :math:`s = 1, \ldots, S` indexes the posterior samples,
116 :math:`f_s` is the latent sum of trees at a test point, :math:`\mu_s` and
117 :math:`\Sigma_s` are the mean and covariance of the outcome given the
118 parameters in sample :math:`s`, and a bar denotes the average over the
119 samples, e.g., :math:`\bar f = \frac1S \sum_{s=1}^S f_s`.
120 """
122 latent_samples = 'latent_samples'
123 R"""Shape ``(ndpost, k, m)``.
125 The latent sum of trees :math:`f_s`. On continuous components, it's the
126 conditional mean of the outcome; on binary components, it's the probit of
127 the probability of 1, times the error scale.
128 """
130 latent_mean = 'latent_mean'
131 R"""Shape ``(k, m)``.
133 Posterior mean of `PredictKind.latent_samples`.
135 .. math::
136 \bar f
137 """
139 latent_cov = 'latent_cov'
140 R"""Shape ``(k, k, m)``.
142 Posterior covariance of `PredictKind.latent_samples`, i.e., the
143 covariance of their empirical distribution.
145 .. math::
146 \frac1S \sum_{s=1}^S (f_s - \bar f) (f_s - \bar f)^T
147 """
149 latent_var = 'latent_var'
150 """Shape ``(k, m)``.
152 The diagonal of `PredictKind.latent_cov`.
153 """
155 latent_sdev = 'latent_sdev'
156 """Shape ``(k, m)``.
158 The square root of `PredictKind.latent_var`.
159 """
161 latent_interval = 'latent_interval'
162 """Shape ``(2, k, m)``.
164 Equal-tailed interval with probability `level` of
165 `PredictKind.latent_samples`, i.e., their quantiles at ``(1 - level) / 2``
166 and ``(1 + level) / 2`` as computed by
167 ``numpy.quantile(..., method='hazen')``. ``Bart.score(..., kind='coverage',
168 target='latent')`` is the fraction of truths inside the interval.
169 """
171 mean_samples = 'mean_samples'
172 R"""Shape ``(ndpost, k, m)``.
174 The conditional mean of the outcome :math:`\mu_s`. On continuous
175 components, it's `PredictKind.latent_samples`; on binary components, it's
176 the probability of 1, :math:`\Phi(f_s / w)` with :math:`w` the error
177 scale.
178 """
180 mean = 'mean'
181 R"""Shape ``(k, m)``.
183 Posterior mean of `PredictKind.mean_samples`, which is also the mean of
184 the posterior predictive distribution of the outcome.
186 .. math::
187 \bar \mu
188 """
190 mean_cov = 'mean_cov'
191 R"""Shape ``(k, k, m)``.
193 Posterior covariance of `PredictKind.mean_samples`, see
194 `PredictKind.latent_cov`.
196 .. math::
197 \frac1S \sum_{s=1}^S (\mu_s - \bar \mu) (\mu_s - \bar \mu)^T
198 """
200 mean_var = 'mean_var'
201 """Shape ``(k, m)``.
203 The diagonal of `PredictKind.mean_cov`.
204 """
206 mean_sdev = 'mean_sdev'
207 """Shape ``(k, m)``.
209 The square root of `PredictKind.mean_var`.
210 """
212 mean_interval = 'mean_interval'
213 """Shape ``(2, k, m)``.
215 `PredictKind.latent_interval` of `PredictKind.mean_samples`.
216 ``Bart.score(..., kind='coverage', target='mean')`` is the fraction of
217 truths inside the interval.
218 """
220 cond_cov_samples = 'cond_cov_samples'
221 R"""Shape ``(ndpost, k, k, m)``.
223 The conditional covariance of the outcome :math:`\Sigma_s`. On continuous
224 components, it's the covariance of the error, scaled by the error scales;
225 binary components are independent of the others, with variance
226 :math:`\mu_s (1 - \mu_s)`.
227 """
229 cond_var_samples = 'cond_var_samples'
230 """Shape ``(ndpost, k, m)``.
232 The diagonal of `PredictKind.cond_cov_samples`.
233 """
235 cond_sdev_samples = 'cond_sdev_samples'
236 """Shape ``(ndpost, k, m)``.
238 The square root of `PredictKind.cond_var_samples`.
239 """
241 cond_cov = 'cond_cov'
242 R"""Shape ``(k, k, m)``.
244 Posterior mean of `PredictKind.cond_cov_samples`.
246 .. math::
247 \bar \Sigma
248 """
250 cond_var = 'cond_var'
251 """Shape ``(k, m)``.
253 The diagonal of `PredictKind.cond_cov`.
254 """
256 cond_sdev = 'cond_sdev'
257 """Shape ``(k, m)``.
259 The square root of `PredictKind.cond_var`, which differs from the
260 posterior mean of `PredictKind.cond_sdev_samples`.
261 """
263 outcome_samples = 'outcome_samples'
264 """Shape ``(ndpost, k, m)``.
266 Draws of the outcome from its conditional distribution in each posterior
267 sample, i.e., a sample of the posterior predictive distribution. Requires
268 `key`.
269 """
271 outcome_cov = 'outcome_cov'
272 R"""Shape ``(k, k, m)``.
274 Covariance of the posterior predictive distribution of the outcome, the
275 sum of `PredictKind.cond_cov` and `PredictKind.mean_cov` by the law of
276 total covariance.
278 .. math::
279 \bar \Sigma
280 + \frac1S \sum_{s=1}^S (\mu_s - \bar \mu) (\mu_s - \bar \mu)^T
281 """
283 outcome_var = 'outcome_var'
284 R"""Shape ``(k, m)``.
286 The diagonal of `PredictKind.outcome_cov`. On binary components, it's
287 :math:`\bar \mu (1 - \bar \mu)`.
288 """
290 outcome_sdev = 'outcome_sdev'
291 """Shape ``(k, m)``.
293 The square root of `PredictKind.outcome_var`.
294 """
296 outcome_interval = 'outcome_interval'
297 R"""Shape ``(2, k, m)``, NaN on binary components.
299 Equal-tailed interval with probability `level` of the posterior
300 predictive distribution of the outcome, i.e., of the mixture of the
301 conditional distributions in the posterior samples. The bounds are its
302 exact quantiles, computed by root finding rather than from
303 `PredictKind.outcome_samples`. ``Bart.score(..., kind='coverage')`` is the
304 fraction of truths inside the interval.
306 .. math::
307 \left[F^{-1}\left(\frac{1 - \mathtt{level}}2\right),
308 F^{-1}\left(\frac{1 + \mathtt{level}}2\right)\right], \qquad
309 F(t) = \frac1S \sum_{s=1}^S \Phi\left(\frac{t - f_s}{\sigma_s}\right)
311 where :math:`\sigma_s^2` is the diagonal entry of :math:`\Sigma_s`.
312 """
315# groups of predict kinds
316LATENT_PREDICTIONS = (
317 PredictKind.latent_samples,
318 PredictKind.latent_mean,
319 PredictKind.latent_cov,
320 PredictKind.latent_var,
321 PredictKind.latent_sdev,
322 PredictKind.latent_interval,
323)
324MEAN_PREDICTIONS = (
325 PredictKind.mean_samples,
326 PredictKind.mean,
327 PredictKind.mean_cov,
328 PredictKind.mean_var,
329 PredictKind.mean_sdev,
330 PredictKind.mean_interval,
331)
332COV_PREDICTIONS = (
333 PredictKind.latent_cov,
334 PredictKind.mean_cov,
335 PredictKind.cond_cov_samples,
336 PredictKind.cond_cov,
337 PredictKind.outcome_cov,
338)
339INTERVAL_PREDICTIONS = (
340 PredictKind.latent_interval,
341 PredictKind.mean_interval,
342 PredictKind.outcome_interval,
343)
345# shapes of the outputs of `Bart.predict`, and of the multivariate layout with
346# k = 1 used internally for univariate outcomes
347MultivariatePrediction = (
348 Float32[Array, 'k m']
349 | Float32[Array, 'k k m']
350 | Float32[Array, 'ndpost k m']
351 | Float32[Array, 'ndpost k k m']
352 | Float32[Array, '2 k m']
353)
354Prediction = (
355 Float32[Array, ' m']
356 | Float32[Array, 'ndpost m']
357 | Float32[Array, '2 m']
358 | MultivariatePrediction
359)
362class ScoreKind(Enum):
363 R"""Kind of score computed by `Bart.score`.
365 The shapes are for multivariate outcomes with ``k`` components, at ``m``
366 test points, with ``ndpost = num_chains * n_save`` posterior samples. For
367 univariate outcomes, drop the ``k`` axis. The kinds ``loglik``, ``lpd``,
368 ``mlpd``, and ``logloss`` are available only for univariate outcomes, use
369 their ``_joint`` or ``_marginal`` variants for multivariate outcomes. The
370 kinds based on the density of the outcome (``loglik*``, ``lpd*``,
371 ``mlpd*``, ``logloss``) and ``brier`` require ``target='outcome'``.
373 In the formulas, :math:`s = 1, \ldots, S` indexes the posterior samples,
374 :math:`i = 1, \ldots, m` the test points, and :math:`j = 1, \ldots, k` the
375 outcome components (dropped if univariate). :math:`y_{ji}` is `truth`,
376 :math:`p_s` the density of the outcome given the parameters in sample
377 :math:`s` (the probability for binary components), :math:`F_{ji}` the
378 cumulative distribution function (cdf) of the posterior of the `target`,
379 and :math:`[\cdot]` is 1 if the condition holds and 0 otherwise. The
380 expectations over the posterior are exact averages over the samples.
382 For the outcome, :math:`F_{ji}` is the posterior predictive, the mixture of
383 the distributions of the outcome given the parameters in the samples. For
384 the mean and the latent, it's the empirical cdf interpolation defined as the
385 inverse of ``numpy.quantile(..., method='hazen')``.
386 """
388 loglik = 'loglik'
389 R"""Range (-∞, ∞), or (-∞, 0] for a binary outcome, higher is better, shape
390 ``(ndpost, m)``. Univariate only.
392 Log likelihood of each test point under each posterior sample.
394 .. math::
395 \log p_s(y_i)
396 """
398 loglik_joint = 'loglik_joint'
399 R"""Range (-∞, ∞), or (-∞, 0] if all outcome components are binary, higher
400 is better, shape
401 ``(ndpost, m)``.
403 `ScoreKind.loglik` with the density joint across the outcome components.
405 .. math::
406 \log p_s(y_{1i}, \ldots, y_{ki})
407 """
409 loglik_marginal = 'loglik_marginal'
410 R"""Range (-∞, ∞), or (-∞, 0] on binary components, higher is better,
411 shape ``(ndpost, k, m)``.
413 `ScoreKind.loglik` with the marginal density of each outcome component.
414 The marginalization is over the other components, given the parameters,
415 so this is not the marginal likelihood of Bayesian model comparison.
417 .. math::
418 \log p_s(y_{ji})
419 """
421 lpd = 'lpd'
422 R"""Range (-∞, ∞), or (-∞, 0] for a binary outcome, higher is better, shape
423 ``(m,)``. Univariate only.
425 Log predictive density of each test point, i.e., the log of the posterior
426 mean of the likelihood.
428 .. math::
429 \log \frac1S \sum_{s=1}^S p_s(y_i)
430 """
432 lpd_joint = 'lpd_joint'
433 R"""Range (-∞, ∞), or (-∞, 0] if all outcome components are binary, higher
434 is better, shape
435 ``(m,)``.
437 `ScoreKind.lpd` with the density joint across the outcome components.
439 .. math::
440 \log \frac1S \sum_{s=1}^S p_s(y_{1i}, \ldots, y_{ki})
441 """
443 lpd_marginal = 'lpd_marginal'
444 R"""Range (-∞, ∞), or (-∞, 0] on binary components, higher is better,
445 shape ``(k, m)``.
447 `ScoreKind.lpd` with the marginal density of each outcome component, see
448 `ScoreKind.loglik_marginal`.
450 .. math::
451 \log \frac1S \sum_{s=1}^S p_s(y_{ji})
452 """
454 mlpd = 'mlpd'
455 R"""Range (-∞, ∞), or (-∞, 0] for a binary outcome, higher is better,
456 scalar. Univariate only.
458 Mean log predictive density, the average of `ScoreKind.lpd` over the test
459 points.
461 .. math::
462 \frac1m \sum_{i=1}^m \log \frac1S \sum_{s=1}^S p_s(y_i)
463 """
465 mlpd_joint = 'mlpd_joint'
466 R"""Range (-∞, ∞), or (-∞, 0] if all outcome components are binary, higher
467 is better, scalar.
469 Average of `ScoreKind.lpd_joint` over the test points.
471 .. math::
472 \frac1m \sum_{i=1}^m \log \frac1S \sum_{s=1}^S
473 p_s(y_{1i}, \ldots, y_{ki})
474 """
476 mlpd_marginal = 'mlpd_marginal'
477 R"""Range (-∞, ∞), or (-∞, 0] on binary components, higher is better,
478 shape ``(k,)``.
480 Average of `ScoreKind.lpd_marginal` over the test points.
482 .. math::
483 \frac1m \sum_{i=1}^m \log \frac1S \sum_{s=1}^S p_s(y_{ji})
484 """
486 logloss = 'logloss'
487 R"""Range [0, ∞), lower is better, scalar. Univariate binary only.
489 Log loss, or cross-entropy, of the predicted probabilities
490 ``predict(kind='mean')``. It's the negative of `ScoreKind.mlpd`.
492 .. math::
493 -\frac1m \sum_{i=1}^m
494 \left(y_i \log \hat p_i + (1 - y_i) \log(1 - \hat p_i)\right),
495 \qquad \hat p_i = \frac1S \sum_{s=1}^S p_s(y_i = 1)
496 """
498 mse = 'mse'
499 R"""Range [0, ∞), lower is better, shape ``(k,)``.
501 Mean squared error of the posterior mean of the `target`, which is
502 ``predict(kind='mean')`` with ``target='outcome'`` or ``'mean'``.
504 .. math::
505 \frac1m \sum_{i=1}^m \left(y_{ji} - \hat y_{ji}\right)^2,
506 \qquad \hat y_{ji} = \int t \,\mathrm dF_{ji}(t)
507 """
509 rmse = 'rmse'
510 R"""Range [0, ∞), lower is better, shape ``(k,)``.
512 Square root of `ScoreKind.mse`.
514 .. math::
515 \sqrt{\frac1m \sum_{i=1}^m \left(y_{ji} - \hat y_{ji}\right)^2}
516 """
518 r2 = 'r2'
519 R"""Range (-∞, 1], higher is better, shape ``(k,)``.
521 Coefficient of determination, the fraction of the variance of `truth`
522 across the test points explained by the posterior mean of the `target`,
523 with :math:`\hat y_{ji}` as in `ScoreKind.mse`.
525 .. math::
526 1 - \frac{\sum_{i=1}^m (y_{ji} - \hat y_{ji})^2}
527 {\sum_{i=1}^m (y_{ji} - \bar y_j)^2},
528 \qquad \bar y_j = \frac1m \sum_{i=1}^m y_{ji}
529 """
531 brier = 'brier'
532 R"""Range [0, 1], lower is better, shape ``(k,)``, NaN on continuous
533 components.
535 Brier score, the `ScoreKind.mse` of the predicted probabilities of the
536 binary components.
538 .. math::
539 \frac1m \sum_{i=1}^m \left(y_{ji} - \hat p_{ji}\right)^2,
540 \qquad \hat p_{ji} = \frac1S \sum_{s=1}^S p_s(y_{ji} = 1)
541 """
543 crps = 'crps'
544 R"""Range [0, ∞), lower is better, shape ``(k,)``.
546 Continuous ranked probability score, the integrated squared difference
547 between the cumulative distribution function of the posterior of the
548 `target` and a step at `truth`, averaged over the test points. With
549 ``target='outcome'``, it equals `ScoreKind.brier` on binary components,
550 and its cost is quadratic in the number of posterior samples. With
551 ``target='mean'`` or ``'latent'``, :math:`F_{ji}` is the plain empirical
552 distribution of the samples, without interpolation.
554 .. math::
555 \frac1m \sum_{i=1}^m \int_{-\infty}^\infty \mathrm dt
556 \left(F_{ji}(t) - [t \ge y_{ji}]\right)^2
557 """
559 pit = 'pit'
560 R"""Range [0, 1], ideally uniform across the test points, shape ``(k, m)``,
561 NaN on binary components with ``target='outcome'``.
563 Probability integral transform, the cumulative distribution function of
564 the posterior of the `target` evaluated at `truth`. If the posterior is
565 calibrated, it's uniformly distributed across the test points.
567 .. math::
568 F_{ji}(y_{ji})
569 """
571 coverage = 'coverage'
572 R"""Range [0, 1], ideally equal to `level`, shape ``(k,)``, NaN on binary
573 components with ``target='outcome'``.
575 Fraction of test points where `truth` lies in the equal-tailed interval
576 of the posterior of the `target` with probability `level`, i.e., between
577 its quantiles at ``(1 - level) / 2`` and ``(1 + level) / 2``.
579 .. math::
580 \frac1m \sum_{i=1}^m \left[
581 F_{ji}^{-1}\left(\frac{1 - \mathtt{level}}2\right) \le y_{ji} \le
582 F_{ji}^{-1}\left(\frac{1 + \mathtt{level}}2\right) \right]
583 """
586class ScoreTarget(Enum):
587 """Quantity scored by `Bart.score`, of which `truth` is the true value."""
589 outcome = 'outcome'
590 """The outcome, with its posterior predictive distribution, the
591 distribution of `PredictKind.outcome_samples`. On binary components,
592 `truth` is cast to boolean like `y_train`."""
594 mean = 'mean'
595 """The conditional mean of the outcome, which is the probability of 1 on
596 binary components, with the distribution of the samples
597 `PredictKind.mean_samples` defined in `ScoreKind`."""
599 latent = 'latent'
600 """The latent sum of trees, with the distribution of the samples
601 `PredictKind.latent_samples` defined in `ScoreKind`."""
604# groups of score kinds
605DENSITY_KINDS = (
606 ScoreKind.loglik,
607 ScoreKind.loglik_joint,
608 ScoreKind.loglik_marginal,
609 ScoreKind.lpd,
610 ScoreKind.lpd_joint,
611 ScoreKind.lpd_marginal,
612 ScoreKind.mlpd,
613 ScoreKind.mlpd_joint,
614 ScoreKind.mlpd_marginal,
615 ScoreKind.logloss,
616)
617JOINT_KINDS = (ScoreKind.loglik_joint, ScoreKind.lpd_joint, ScoreKind.mlpd_joint)
618UNIVARIATE_KINDS = (ScoreKind.loglik, ScoreKind.lpd, ScoreKind.mlpd, ScoreKind.logloss)
621@runtime_checkable
622class DataFrame(Protocol):
623 """DataFrame duck-type for `Bart`."""
625 @property
626 def columns(self) -> Collection[str]:
627 """The names of the columns."""
628 ...
630 def to_numpy(self) -> Shaped[ndarray, '*shape']:
631 """Convert the dataframe to a 2d numpy array with columns on the second axis."""
632 ...
635@runtime_checkable
636class Series(Protocol):
637 """Series duck-type for `Bart`."""
639 @property
640 def name(self) -> Hashable:
641 """The name of the series."""
642 ...
644 def to_numpy(self) -> Shaped[ndarray, '*shape']:
645 """Convert the series to a 1d numpy array."""
646 ...
649class SparseConfig(Module):
650 R"""
651 Configuration of a sparsity-inducing variable selection prior.
653 This is the prior of [1]_. Pass an instance to the `sparse` argument of
654 `Bart` to activate variable selection on the predictors. The prior on the
655 choice of predictor for each decision rule is
657 .. math::
658 (s_1, \ldots, s_p) \sim
659 \operatorname{Dirichlet}(\mathtt{theta}/p, \ldots, \mathtt{theta}/p),
661 where p counts only the predictors with decision rules, as the others are
662 ignored (see the `rm_const` argument of `Bart`). If `theta` is not
663 specified, it's a priori distributed according to
665 .. math::
666 \frac{\mathtt{theta}}{\mathtt{theta} + \mathtt{rho}} \sim
667 \operatorname{Beta}(\mathtt{a}, \mathtt{b}).
669 References
670 ----------
671 .. [1] Linero, Antonio R. (2018). “Bayesian Regression Trees for
672 High-Dimensional Prediction and Variable Selection”. In: Journal of the
673 American Statistical Association 113.522, pp. 626-636.
674 """
676 theta: FloatLike | None = None
677 """Concentration of the Dirichlet prior. If not specified, it is sampled
678 from a Beta prior parametrized by `a`, `b` and `rho`. If set directly, it
679 should be in the ballpark of the predictor count p or lower."""
681 a: FloatLike = 0.5
682 """Shape parameter of the Beta prior on ``theta / (theta + rho)``."""
684 b: FloatLike = 1.0
685 """Shape parameter of the Beta prior on ``theta / (theta + rho)``."""
687 rho: FloatLike | None = None
688 """Scale of the Beta prior on `theta`. If not specified, set to the number
689 of predictors p. Lower values prefer more sparsity."""
691 augment: bool = field(static=True, default=True)
692 """Whether to account exactly for the decision rules forbidden by the
693 ancestors of each node when updating the variable selection probabilities,
694 using data augmentation. On by default. Setting it to `False` ignores the
695 forbidden rules, which is faster but only approximate. This matters most
696 with few predictors with few cutpoints each, where the same predictor
697 cannot be re-used down a branch."""
699 enabled: bool = field(static=True, default=True)
700 """Whether variable selection is active."""
703@serializable
704class Bart(Module):
705 R"""
706 Nonparametric regression with Bayesian Additive Regression Trees (BART).
708 Regress `y_train` on `x_train` with a latent mean function represented as
709 a sum of decision trees [2]_. The inference is carried out by sampling the
710 posterior distribution of the tree ensemble with an MCMC.
712 Parameters
713 ----------
714 x_train
715 The training predictors. Missing values are not supported: NaN raises
716 an error.
717 y_train
718 The training responses. For univariate regression, a 1D array of shape
719 `(n,)`. For multivariate regression, a 2D array of shape `(k, n)` where
720 `k` is the number of response components, as introduced in [3]_. For
721 binary regression, the convention is that non-zero values mean 1, zero
722 mean 0, like booleans.
723 outcome_type
724 The type of regression. ``'continuous'`` for continuous regression,
725 ``'binary'`` for binary regression with probit link. For multivariate
726 regression, a scalar value applies to all components; alternatively, a
727 sequence of per-component types (e.g., ``['binary', 'continuous']``)
728 specifies mixed outcome types. Binary components in multivariate
729 outcomes follow the multivariate probit BART formulation of [4]_.
730 sparse
731 A `SparseConfig` for the sparsity-inducing variable selection prior of
732 [1]_. Disabled by default; pass a `SparseConfig` to enable it.
733 varprob
734 The probability distribution over the `p` predictors for choosing a
735 predictor to split on in a decision node a priori. It does not need to
736 be normalized to sum to 1. A zero excludes a predictor. If not
737 specified, use a uniform distribution. If `sparse` is enabled, this is
738 only the initial value for the MCMC, and must be > 0.
739 binner
740 A callable that, given the training predictors and a random key,
741 returns a `~bartz.prepcovars.Binner` instance. The default is
742 `~bartz.prepcovars.UniqueQuantileBinner`, which places cutpoints at
743 the quantiles of each predictor. Other built-in options are
744 `~bartz.prepcovars.RangeEvenBinner` (evenly-spaced cutpoints over the
745 observed range) and `~bartz.prepcovars.GivenSplitsBinner` (R BART
746 ``xinfo`` format). To pass options, use `functools.partial`, e.g.
747 ``binner=partial(UniqueQuantileBinner, max_bins=128)``.
748 rm_const
749 How to treat predictors with no associated decision rules (i.e., there
750 are no available cutpoints for that predictor). If `True` (default),
751 they are ignored. If `False`, an error is raised if there are any,
752 apart from those excluded by `varprob`.
753 sigma_df
754 The degrees of freedom of the prior on the error precision. For
755 multivariate regression with `k` components, the Wishart degrees of
756 freedom are set to ``sigma_df + k - 1``, such that each marginal error
757 variance keeps ``sigma_df`` degrees of freedom; the same holds when the
758 error covariance is restricted to diagonal.
759 sigma_scale
760 Sets the scale of the prior on the error precision. If 'auto'
761 (default), the prior is scaled so that the prior harmonic mean of the
762 error variance is ``var(y_train)``, where with `error_scale` the
763 variance is a precision-weighted one that estimates the error variance
764 at unit error scale. Otherwise, ``square(sigma_scale)`` is the prior
765 harmonic mean of the error variance. For multivariate regression this
766 applies to the marginal variance of each component, whatever `k`, and
767 a scalar is broadcast to all components. For mixed outcome types,
768 binary components are ignored.
769 sigma_init
770 The initial value of the error standard deviation in the MCMC. If
771 'auto' (default), the initial error precision is set to ``diag(1 /
772 var(y_train))``, with the same precision-weighted variance as
773 `sigma_scale` when `error_scale` is given. Otherwise, the initial
774 precision is ``diag(1 / square(sigma_init))``; for multivariate
775 regression a scalar is broadcast to all components. For mixed outcome
776 types, binary components are ignored.
777 k
778 The inverse scale of the prior standard deviation on the latent mean
779 function, relative to half the observed range of `y_train`. If `y_train`
780 has less than two elements, `k` is ignored and the scale is set to 1.
781 power
782 base
783 Parameters of the prior on tree node generation. The probability that a
784 node at depth `d` (0-based) is non-terminal is ``base / (1 + d) **
785 power``.
786 tau_num
787 The numerator in the expression that determines the prior standard
788 deviation of leaves. If not specified, default to ``(max(y_train) -
789 min(y_train)) / 2`` (or 1 if `y_train` has less than two elements) for
790 continuous regression, and 3 for binary regression. For multivariate
791 regression, the range is computed per component. For mixed outcome
792 types, each component uses the default for its type.
793 sigma_mu_df
794 If specified, the prior precision of the leaves is sampled in the MCMC
795 instead of being held fixed. The prior is Wishart (Gamma in the
796 univariate case) with ``sigma_mu_df + k - 1`` degrees of freedom for
797 `k` outcome components, such that each marginal leaf variance keeps
798 ``sigma_mu_df`` degrees of freedom, like `sigma_df`. The prior harmonic
799 mean of each marginal leaf variance, which is also its initial value,
800 is the fixed value otherwise set by `tau_num` and the `k` argument (the
801 leaf scale, not the number of components).
802 offset
803 The prior mean of the latent mean function. If not specified, it is set
804 to the mean of `y_train` for continuous regression, and to
805 ``Phi^-1(mean(y_train != 0))`` for binary regression. If `y_train` is
806 empty, `offset` is set to 0. With binary regression, if `y_train` is
807 all zero or all non-zero, it is set to ``Phi^-1(1/(n+1))`` or
808 ``Phi^-1(n/(n+1))``, respectively. For multivariate regression, can be
809 a scalar (broadcast to all components) or a `(k,)` vector. If not
810 specified, it is set to the per-component mean of `y_train`. For mixed
811 outcome types, each component uses the default for its type.
812 error_scale
813 Coefficients that rescale the error standard deviation on each
814 datapoint ("w" in BART3). Not specifying `error_scale` is equivalent to
815 setting it to 1 for all datapoints. Shape ``(n,)`` applies the same
816 scalar scale to every outcome component; for multivariate regression,
817 ``(k, n)`` instead supplies a per-component scale per datapoint.
818 Supported with binary (probit) outcomes, where it scales the latent
819 error so the success probability is ``Phi(latent / error_scale)``,
820 including the binary components of a mixed regression.
821 missing
822 Boolean mask with the same shape as `y_train`; `True` marks entries
823 to be ignored by the MCMC. The values of `y_train` at masked
824 positions are ignored and may be anything, even non-finite. If 2-D,
825 the error covariance must be diagonal.
826 num_trees
827 The number of trees used to represent the latent mean function.
828 n_save
829 The number of MCMC samples to save, after burn-in, per chain. The
830 total trace length across all chains is ``num_chains * n_save``.
831 n_burn
832 The number of initial MCMC samples to discard as burn-in. This number
833 of samples is discarded from each chain.
834 n_skip
835 The thinning factor for the MCMC samples, after burn-in.
836 printevery
837 The number of iterations (including thinned-away ones) between each log
838 line. Set to `None` to disable progress reporting entirely (this ignores
839 `pbar`). ^C interrupts the MCMC only every `printevery` iterations, so
840 with reporting disabled it's impossible to kill the MCMC conveniently.
841 pbar
842 If `True`, show a `tqdm` progress bar instead of printing log lines. The
843 bar advances every iteration and refreshes the acceptance statistics
844 every `printevery` iterations. Ignored if `printevery` is `None`.
845 num_chains
846 The number of independent Markov chains to run.
848 The difference between ``num_chains=None`` and ``num_chains=1`` is that
849 in the latter case in the object attributes and some methods there will
850 be an explicit chain axis of size 1.
851 num_chain_devices
852 The number of devices to spread the chains across. Must be a divisor of
853 `num_chains`. Each device will run a fraction of the chains. If 'auto'
854 (default), use as many of the available devices (all the devices of
855 the platform, or the `devices` list if set) as possible, leaving room
856 for `num_data_devices`. On cpu, where jax devices are virtual, the
857 number of available cores is the limit, and a warning suggests
858 creating more devices if there are not enough.
859 num_data_devices
860 The number of devices to split datapoints across. Must be a divisor of
861 `n`. This is useful only with very high `n`, about > 1000_000. `predict`
862 parallelizes across the same devices, splitting the test points; the
863 number of test points must be a multiple of `num_data_devices` as well.
865 If both num_chain_devices and num_data_devices are specified, the total
866 number of devices used is the product of the two.
867 devices
868 One or more devices used to run the MCMC on. If not specified, the
869 computation will follow the placement of the input arrays. If a list of
870 devices, this argument can be longer than the number of devices needed.
871 seed
872 The seed for the random number generator.
873 maxdepth
874 The maximum depth of the trees, with the root at depth 0: a tree has at
875 most ``2 ** maxdepth`` leaves.
876 precompute_predict_train
877 If `True`, compute the predictions at the training points during the
878 MCMC. Off by default; makes ``predict('train', ...)`` faster at the cost
879 of more memory.
880 init_kw
881 Additional arguments passed to `bartz.mcmcstep.init`.
882 run_mcmc_kw
883 Additional arguments passed to `bartz.mcmcloop.run_mcmc`.
885 Notes
886 -----
887 On gpu, the leaves of the trees are stored in float16 (see the
888 ``leaf_dtype`` argument of `bartz.mcmcstep.init`), which limits the
889 signal-to-noise ratio of the fit to less than about 1000, a limit that
890 should always hold in realistic usage.
892 bartz computes in 32 bit, and raises an error if ``jax_enable_x64`` is set
893 or if passed 64-bit jax arrays. numpy arrays are converted to 32 bit.
895 References
896 ----------
897 .. [1] Linero, Antonio R. (2018). “Bayesian Regression Trees for
898 High-Dimensional Prediction and Variable Selection”. In: Journal of the
899 American Statistical Association 113.522, pp. 626-636.
900 .. [2] Hugh A. Chipman, Edward I. George, Robert E. McCulloch "BART:
901 Bayesian additive regression trees," The Annals of Applied Statistics,
902 Ann. Appl. Stat. 4(1), 266-298, (March 2010).
903 .. [3] Um, Seungha, Antonio R. Linero, Debajyoti Sinha, and Dipankar
904 Bandyopadhyay (2023). "Bayesian additive regression trees for
905 multivariate skewed responses". In: Statistics in Medicine 42.3,
906 pp. 246-263.
907 .. [4] Goh, Yong Chen, Wuu Kuang Soh, Andrew C. Parnell, and Keefe
908 Murphy (2024). "Joint Models for Handling Non-Ignorable Missing
909 Data using Bayesian Additive Regression Trees: Application to
910 Leaf Photosynthetic Traits Data". arXiv:2412.14946 [stat.ME].
912 """
914 _main_trace: MainTrace
915 _burnin_trace: BurninTrace
916 _mcmc_state: State
917 _mcmc_callback: Callback | None
918 _binner: Binner
919 # WORKAROUND(jax<0.9.1): use `jax.tree.static` instead of `field(static=True)`
920 _x_train_fmt: Any = field(static=True)
921 _device: Device | None = field(static=True)
923 @forbid_x64
924 def __init__(
925 self,
926 x_train: Real[ArrayLike, 'p n'] | DataFrame,
927 y_train: Float32[ArrayLike, ' n']
928 | Float32[ArrayLike, 'k n']
929 | Series
930 | DataFrame,
931 *,
932 outcome_type: OutcomeType | str | Sequence[OutcomeType | str] = 'continuous',
933 sparse: SparseConfig = SparseConfig(enabled=False),
934 varprob: Float[ArrayLike, ' p'] | None = None,
935 binner: BinnerFactory = UniqueQuantileBinner,
936 rm_const: bool = True,
937 sigma_df: FloatLike = 3.0,
938 sigma_scale: FloatLike | Float[ArrayLike, ' k'] | Literal['auto'] = 'auto',
939 sigma_init: FloatLike | Float[ArrayLike, ' k'] | Literal['auto'] = 'auto',
940 k: FloatLike = 2.0,
941 power: FloatLike = 2.0,
942 base: FloatLike = 0.95,
943 tau_num: FloatLike | None = None,
944 sigma_mu_df: FloatLike | None = None,
945 offset: FloatLike | Float[ArrayLike, ' k'] | None = None,
946 error_scale: Float[ArrayLike, ' n']
947 | Float[ArrayLike, 'k n']
948 | Series
949 | DataFrame
950 | None = None,
951 missing: Bool[ArrayLike, ' n']
952 | Bool[ArrayLike, 'k n']
953 | Series
954 | DataFrame
955 | None = None,
956 num_trees: int = 200,
957 n_save: int = 1000,
958 n_burn: int = 1000,
959 n_skip: int = 1,
960 printevery: int | None = 100,
961 pbar: bool = True,
962 num_chains: int | None = 4,
963 num_chain_devices: int | None | Literal['auto'] = 'auto',
964 num_data_devices: int | None = None,
965 devices: Literal['cpu', 'gpu'] | Device | Sequence[Device] | None = None,
966 seed: int | Key[Array, ''] = 0,
967 maxdepth: int = 5,
968 precompute_predict_train: bool = False,
969 init_kw: Mapping = MappingProxyType({}),
970 run_mcmc_kw: Mapping = MappingProxyType({}),
971 ) -> None:
972 # check data and put it in the right format
973 x_train, x_train_fmt = _process_predictor_input(x_train)
974 raise_if_nan(start_nan_check(x_train))
975 y_train = _process_response_input(y_train)
976 check_length(y_train, 'y_train', x_train, 'x_train')
978 if error_scale is not None:
979 # `error_scale` is donated downstream as `init`'s `error_scale`, which
980 # keeps it (sharded) as `State.error_scale` for prediction
981 error_scale = _process_response_input(error_scale)
982 check_length(error_scale, 'error_scale', x_train, 'x_train')
984 if missing is not None:
985 missing = _process_response_input(missing, dtype=jnp.bool_)
986 check_length(missing, 'missing', x_train, 'x_train')
988 # check data types are correct for continuous/binary/multivariate regression
989 outcome_type, binary_mask = _check_type_settings(
990 y_train, outcome_type, error_scale
991 )
993 # process "standardization" settings
994 offset = _process_offset_settings(
995 y_train,
996 binary_mask,
997 missing,
998 None if offset is None else jnp.asarray(offset, jnp.float32),
999 )
1000 sum_trees_prior_cov_inv = _process_leaf_variance_settings(
1001 y_train,
1002 binary_mask,
1003 missing,
1004 k=jnp.asarray(k, jnp.float32),
1005 tau_num=None if tau_num is None else jnp.asarray(tau_num, jnp.float32),
1006 sigma_mu_df=None
1007 if sigma_mu_df is None
1008 else jnp.asarray(sigma_mu_df, jnp.float32),
1009 )
1010 error_cov_inv = _process_error_variance_settings(
1011 y_train,
1012 binary_mask,
1013 missing,
1014 outcome_type=outcome_type,
1015 sigma_df=sigma_df,
1016 sigma_scale=sigma_scale,
1017 sigma_init=sigma_init,
1018 error_scale=error_scale,
1019 )
1021 check_augment_depth(sparse, maxdepth, x_train.shape[0])
1023 # split the user-provided seed into an mcmc key and a binner key
1024 if not is_key(seed):
1025 seed = random.key(seed)
1026 keys = split(seed)
1028 # construct the binner and bin x_train
1029 binner_obj = binner(x_train, key=keys.pop())
1030 x_train = binner_obj.bin(x_train)
1031 # copy max_split because `mcmcstep.init` donates it
1032 max_split = jnp.array(binner_obj.max_split)
1034 warn_byte_boundaries(x_train, max_split, maxdepth)
1036 # setup and run mcmc
1037 initial_state, mcmc_key, device, check_platform = _setup_mcmc(
1038 keys.pop(),
1039 x_train,
1040 y_train,
1041 outcome_type=outcome_type,
1042 offset=offset,
1043 error_scale=error_scale,
1044 missing=missing,
1045 max_split=max_split,
1046 sum_trees_prior_cov_inv=sum_trees_prior_cov_inv,
1047 error_cov_inv=error_cov_inv,
1048 power=power,
1049 base=base,
1050 maxdepth=maxdepth,
1051 num_trees=num_trees,
1052 init_kw=init_kw,
1053 rm_const=rm_const,
1054 sparse=sparse,
1055 varprob=varprob,
1056 num_chains=num_chains,
1057 num_chain_devices=num_chain_devices,
1058 num_data_devices=num_data_devices,
1059 devices=devices,
1060 n_burn=n_burn,
1061 )
1062 result = _run_mcmc(
1063 mcmc_key,
1064 initial_state,
1065 n_save,
1066 n_burn=n_burn,
1067 n_skip=n_skip,
1068 printevery=printevery,
1069 pbar=pbar,
1070 precompute_predict_train=precompute_predict_train,
1071 run_mcmc_kw=run_mcmc_kw,
1072 check_platform=check_platform,
1073 )
1075 # set private attributes
1076 self._main_trace = result.main_trace
1077 self._burnin_trace = result.burnin_trace
1078 self._mcmc_state = result.final_state
1079 self._mcmc_callback = result.final_callback
1080 self._binner = binner_obj
1081 self._x_train_fmt = x_train_fmt
1082 self._device = device
1084 @forbid_x64
1085 def predict(
1086 self,
1087 x_test: Real[ArrayLike, 'p m'] | DataFrame | Literal['train'],
1088 *,
1089 kind: PredictKind | str = 'mean',
1090 key: Key[Array, ''] | None = None,
1091 level: FloatLike | None = None,
1092 error_scale: Float[ArrayLike, ' m']
1093 | Float[ArrayLike, 'k m']
1094 | Series
1095 | DataFrame
1096 | None = None,
1097 ) -> Prediction:
1098 """
1099 Compute predictions at `x_test`.
1101 Parameters
1102 ----------
1103 x_test
1104 The test predictors, or the string ``'train'`` to compute
1105 predictions on the training data. Missing values are not supported:
1106 NaN raises an error.
1107 kind
1108 The kind of output. See `PredictKind` for details.
1109 key
1110 Jax random key, required when ``kind='outcome_samples'``.
1111 level
1112 The probability of the intervals with the ``*_interval`` kinds, in
1113 (0, 1). Required with them, and must be `None` with the other kinds.
1114 error_scale
1115 Per-observation error scale. Used with the ``cond_*`` and
1116 ``outcome_*`` kinds, and with the ``mean*`` kinds if some outcome
1117 component is binary (since the success probability is
1118 ``Phi(latent / error_scale)``). Required when used, if the model
1119 was fit with `error_scale` and ``x_test`` is new data, otherwise
1120 must be `None`. Shape matches the shape used at fitting: ``(m,)``
1121 for scalar scales, ``(k, m)`` for multivariate per-component
1122 scales.
1124 Returns
1125 -------
1126 Predictions at `x_test` in the requested format.
1128 Raises
1129 ------
1130 ValueError
1131 If `x_test` contains NaN or has a different format than `x_train`,
1132 or if `level` or `error_scale` are specified when they should be
1133 `None` or vice versa, or if `error_scale` does not match the
1134 datapoints of `x_test`, or if the model splits datapoints across
1135 devices (`num_data_devices`) and the number of test points is not a
1136 multiple of the number of data devices.
1138 Notes
1139 -----
1140 If the model splits datapoints across devices (`num_data_devices`),
1141 the test points and the returned predictions are split the same way.
1142 """
1143 # parse arguments
1144 kind = PredictKind(kind)
1145 if kind is PredictKind.outcome_samples and key is None: 1145 ↛ 1146line 1145 didn't jump to line 1146 because the condition on line 1145 was never true
1146 msg = '`key` not specified'
1147 raise ValueError(msg)
1148 setting = f'kind={kind.value!r}'
1149 level = check_level(level, used=kind in INTERVAL_PREDICTIONS, setting=setting)
1150 error_scale = self._process_error_scale_test(
1151 x_test, error_scale, basis=kind, setting=setting
1152 )
1153 x_test_is_train = isinstance(x_test, str) and x_test == 'train'
1154 has_binary = self._mcmc_state.z is not None
1155 nan_filled = kind is PredictKind.outcome_interval and has_binary
1157 # use the predictions precomputed during the MCMC, if available
1158 if x_test_is_train and isinstance(self._main_trace, MainTraceWithTrainPred):
1159 with allow_nans(nan_filled):
1160 return predict_train(
1161 key,
1162 self._main_trace,
1163 error_scale=error_scale,
1164 binary_indices=self._mcmc_state.binary_indices,
1165 has_binary=has_binary,
1166 kind=kind,
1167 level=level,
1168 )
1170 # new test set, or no precomputed train set predictions
1171 else:
1172 x_test, x_test_has_nan = self._process_x_test(x_test, error_scale)
1174 # place new test data on the devices of the model; the training data
1175 # is already in place
1176 if not x_test_is_train:
1177 x_test, error_scale = self._device_put_test(x_test, error_scale)
1179 # invoke jitted implementation
1180 with allow_nans(nan_filled):
1181 out = predict(
1182 key,
1183 self._main_trace,
1184 x_test,
1185 error_scale=error_scale,
1186 binary_indices=self._mcmc_state.binary_indices,
1187 has_binary=has_binary,
1188 kind=kind,
1189 level=level,
1190 # the test points are sharded over the mesh 'data' axis (when
1191 # there is one): the training data at `init`, new test data by
1192 # `_device_put_test`. `evaluate_trace` can't detect this on its
1193 # own at trace time, so declare it.
1194 test_points='shard_and_autobatch',
1195 )
1197 # wait for the NaN check only now, to overlap it with dispatching
1198 raise_if_nan(x_test_has_nan)
1200 return out
1202 @forbid_x64
1203 def score(
1204 self,
1205 x_test: Real[ArrayLike, 'p m'] | DataFrame | Literal['train'],
1206 truth: Float32[ArrayLike, ' m']
1207 | Float32[ArrayLike, 'k m']
1208 | Series
1209 | DataFrame,
1210 *,
1211 kind: ScoreKind | str,
1212 target: ScoreTarget | str = 'outcome',
1213 level: FloatLike | None = None,
1214 error_scale: Float[ArrayLike, ' m']
1215 | Float[ArrayLike, 'k m']
1216 | Series
1217 | DataFrame
1218 | None = None,
1219 ) -> (
1220 Float32[Array, '']
1221 | Float32[Array, ' k']
1222 | Float32[Array, ' m']
1223 | Float32[Array, 'k m']
1224 | Float32[Array, 'ndpost m']
1225 | Float32[Array, 'ndpost k m']
1226 ):
1227 """
1228 Score the predictions at `x_test` against `truth`.
1230 Parameters
1231 ----------
1232 x_test
1233 The test predictors, or the string ``'train'`` to score on the
1234 training data.
1235 truth
1236 The true values of `target` at the test points, in the same format
1237 as `y_train`. Missing values are not supported.
1238 kind
1239 The score to compute. See `ScoreKind` for details.
1240 target
1241 The quantity to score. See `ScoreTarget` for details.
1242 level
1243 The probability of the intervals with ``kind='coverage'``, in
1244 (0, 1). Required with it, and must be `None` with the other kinds.
1245 error_scale
1246 Per-observation error scale, in the same format as in `predict`.
1247 Used with ``target='outcome'``, except by ``'mse'``, ``'rmse'``,
1248 and ``'r2'`` if no outcome component is binary, and with
1249 ``target='mean'`` if some outcome component is binary. Required
1250 when used, if the model was fit with `error_scale` and ``x_test``
1251 is new data, otherwise must be `None`.
1253 Returns
1254 -------
1255 The score in the format of `kind`.
1257 Raises
1258 ------
1259 ValueError
1260 If `kind` does not apply to the outcome types of the model or to
1261 `target`, if `truth` or `error_scale` do not match the test points
1262 or the outcome components, or if `level` or `error_scale` are
1263 specified when they should be `None` or vice versa. Also, in the
1264 cases listed in `predict`.
1265 """
1266 kind = ScoreKind(kind)
1267 target = ScoreTarget(target)
1268 level = self._check_score_args(kind, target, level)
1270 error_scale = self._process_error_scale_test(
1271 x_test,
1272 error_scale,
1273 basis=score_basis(kind, target),
1274 setting=f'kind={kind.value!r} and target={target.value!r}',
1275 )
1277 # `predict` processes and validates x_test
1278 latent = self.predict(x_test, kind=PredictKind.latent_samples)
1279 _, *test_shape = latent.shape
1280 if error_scale is not None:
1281 check_length(error_scale, 'error_scale', latent, 'x_test')
1283 # parse `truth`
1284 truth = _process_response_input(truth)
1285 if truth.shape != tuple(test_shape):
1286 msg = f'`truth` has shape {truth.shape}, expected {tuple(test_shape)}.'
1287 raise ValueError(msg)
1289 # place the new test data on the devices of the model. With 'train',
1290 # `error_scale` is the array of the model, already in place, which
1291 # must not be donated.
1292 truth = self._device_put_test_array(truth)
1293 x_test_is_train = isinstance(x_test, str) and x_test == 'train'
1294 if error_scale is not None and not x_test_is_train:
1295 error_scale = self._device_put_test_array(error_scale)
1297 nan_filled = kind is ScoreKind.brier or (
1298 target is ScoreTarget.outcome
1299 and kind in (ScoreKind.pit, ScoreKind.coverage)
1300 )
1301 with allow_nans(nan_filled):
1302 return score(
1303 latent,
1304 self._main_trace.error_cov_inv,
1305 truth,
1306 error_scale=error_scale,
1307 binary_indices=self._mcmc_state.binary_indices,
1308 has_binary=self._mcmc_state.z is not None,
1309 kind=kind,
1310 target=target,
1311 level=level,
1312 )
1314 def _check_score_args(
1315 self, kind: ScoreKind, target: ScoreTarget, level: FloatLike | None
1316 ) -> Float[Array, ''] | None:
1317 """Raise if `kind` does not apply to the model or `target`, and check `level`."""
1318 has_binary = self._mcmc_state.z is not None
1319 all_binary = has_binary and self._mcmc_state.binary_indices is None
1320 univariate = self._mcmc_state.y.ndim == 1
1321 outcome = target is ScoreTarget.outcome
1323 if kind in UNIVARIATE_KINDS and not univariate:
1324 if kind is ScoreKind.logloss:
1325 alternatives = "the negative of kind='mlpd_joint' or 'mlpd_marginal'"
1326 else:
1327 alternatives = f"kind='{kind.value}_joint' or '{kind.value}_marginal'"
1328 msg = (
1329 f'kind={kind.value!r} is ambiguous with multivariate outcomes,'
1330 f' use {alternatives}'
1331 )
1332 raise ValueError(msg)
1333 if kind is ScoreKind.logloss and not all_binary:
1334 msg = "kind='logloss' requires a binary outcome"
1335 raise ValueError(msg)
1336 if kind is ScoreKind.brier and not has_binary:
1337 msg = "kind='brier' requires binary outcome components"
1338 raise ValueError(msg)
1339 if (kind in DENSITY_KINDS or kind is ScoreKind.brier) and not outcome:
1340 msg = f"kind={kind.value!r} requires target='outcome'"
1341 raise ValueError(msg)
1342 if kind in (ScoreKind.pit, ScoreKind.coverage) and outcome and all_binary:
1343 msg = (
1344 f"kind={kind.value!r} with target='outcome' requires continuous"
1345 ' outcome components'
1346 )
1347 raise ValueError(msg)
1349 used = kind is ScoreKind.coverage
1350 return check_level(level, used=used, setting=f'kind={kind.value!r}')
1352 def _drop_device_info(self) -> 'Bart':
1353 """Return a copy of the model without device placement metadata.
1355 Clear the meshes in the MCMC state config and in the traces, and the
1356 explicitly requested device. Only this static metadata is dropped: the
1357 arrays keep their actual placement.
1358 """
1359 config = replace(self._mcmc_state.config, mesh=None)
1360 main_trace = replace(self._main_trace, mesh=None)
1361 burnin_trace = replace(self._burnin_trace, mesh=None)
1362 obj = tree_at(
1363 lambda b: (b._mcmc_state.config, b._main_trace, b._burnin_trace), # noqa: SLF001
1364 self,
1365 (config, main_trace, burnin_trace),
1366 )
1367 # `_device` is a static field, out of `tree_at`'s reach, so modify the
1368 # fresh copy in place
1369 object.__setattr__(obj, '_device', None)
1370 return obj
1372 def save_npz(self, path: str | PathLike) -> None:
1373 """Save the fitted model to a compressed npz archive.
1375 Parameters
1376 ----------
1377 path
1378 The file to write to.
1380 Notes
1381 -----
1382 The archive holds the whole model, readable without pickle. The arrays
1383 are copied to host memory and all device/sharding placement is
1384 dropped; `load_npz` reconstructs a single-device model. The model may
1385 contain instances of custom classes, e.g., a callback passed through
1386 ``run_mcmc_kw``; register their classes with `bartz.npz.serializable`.
1388 Files written by a bartz release can be loaded by later releases, but
1389 not by earlier ones; files written by development versions may not be.
1390 """
1391 save_npz(path, self._drop_device_info())
1393 @classmethod
1394 def load_npz(cls, path: str | PathLike) -> 'Bart':
1395 """Load a model saved with `save_npz`.
1397 Parameters
1398 ----------
1399 path
1400 The file to read from.
1402 Returns
1403 -------
1404 The loaded model, on the default device.
1405 """
1406 return check_class(load_npz(path), cls, path)
1408 def dump(self, path: str | PathLike) -> None:
1409 """Serialize the fitted model to a file with `pickle`.
1411 .. deprecated:: 0.14.0
1412 Use `save_npz` instead.
1414 Parameters
1415 ----------
1416 path
1417 The file to write to.
1419 Notes
1420 -----
1421 Intended for short-term storage (e.g. caching across processes), not
1422 long-term archival: the format depends on the versions of bartz, jax and
1423 equinox. The arrays are copied to host memory and all device/sharding
1424 placement is dropped; `load` reconstructs a single-device model.
1425 """
1426 warn(
1427 '`Bart.dump` is deprecated, use `Bart.save_npz`',
1428 DeprecationWarning,
1429 stacklevel=2,
1430 )
1431 # drop all device info (`Device` objects are not picklable), then
1432 # gather any sharded arrays to host (dropping their sharding); the
1433 # reload is single-device
1434 obj = self._drop_device_info()
1435 obj = jax.device_get(obj)
1436 with Path(path).open('wb') as file:
1437 pickle.dump(obj, file, protocol=pickle.HIGHEST_PROTOCOL)
1439 @classmethod
1440 def load(cls, path: str | PathLike) -> 'Bart':
1441 """Load a model saved with `dump`.
1443 .. deprecated:: 0.14.0
1444 Use `load_npz` instead.
1446 Parameters
1447 ----------
1448 path
1449 The file to read from.
1451 Returns
1452 -------
1453 The deserialized model, on host memory with no device placement.
1455 Raises
1456 ------
1457 TypeError
1458 If the file does not contain a `Bart` instance.
1459 """
1460 warn(
1461 '`Bart.load` is deprecated, use `Bart.load_npz`',
1462 DeprecationWarning,
1463 stacklevel=2,
1464 )
1465 with Path(path).open('rb') as file:
1466 obj = pickle.load(file) # noqa: S301, the user owns the file
1467 if not isinstance(obj, cls):
1468 msg = f'unpickled a {type(obj).__name__}, not a {cls.__name__}'
1469 raise TypeError(msg)
1470 return obj
1472 @property
1473 def offset(self) -> Float32[Array, ''] | Float32[Array, ' k']:
1474 """The prior mean of the latent mean function."""
1475 return self._mcmc_state.forest.offset
1477 @property
1478 def n_save(self) -> int:
1479 """The number of posterior samples after burn-in saved per chain."""
1480 *_, n_save = self._main_trace.grow_prop_count.shape
1481 return n_save
1483 @property
1484 def num_chains(self) -> int | None:
1485 """The number of chains, `None` if scalar."""
1486 return self._mcmc_state.num_chains()
1488 @property
1489 def ndpost(self) -> int:
1490 """The total number of posterior samples after burn-in across all chains."""
1491 return self._main_trace.grow_prop_count.size
1493 @property
1494 def num_trees(self) -> int:
1495 """Return the number of trees used in the model."""
1496 *_, num_trees, _ = self._mcmc_state.forest.split_tree.shape
1497 return num_trees
1499 @forbid_x64
1500 def get_latent_prec(
1501 self, only_continuous: bool = False
1502 ) -> (
1503 Float32[Array, ' n_burn_plus_n_save']
1504 | Float32[Array, 'n_burn_plus_n_save k k']
1505 | Float32[Array, 'num_chains n_burn_plus_n_save']
1506 | Float32[Array, 'num_chains n_burn_plus_n_save k k']
1507 ):
1508 """Return the posterior samples of the latent error precision matrix.
1510 Parameters
1511 ----------
1512 only_continuous
1513 If `True` and the model has mixed binary-continuous outcomes,
1514 return only the submatrix for the continuous components.
1516 Returns
1517 -------
1518 MCMC samples of the error precision matrix.
1520 Raises
1521 ------
1522 ValueError
1523 If `only_continuous` is `True` but the model has only binary
1524 outcomes, so there is no continuous submatrix to return.
1526 Notes
1527 -----
1528 This method is meant to check for convergence, so it returns the full
1529 MCMC trace and does not concatenate chains together. For probit
1530 regression, this returns the precision of the latent error term, not
1531 the Bernoulli precision for the binary outcome. For heteroskedastic
1532 regression, the returned precision is the global precision parameter,
1533 that would have to be divided by a squared error scale to get the
1534 precision on a given datapoint.
1535 """
1536 binary_indices = self._mcmc_state.binary_indices
1537 if (
1538 only_continuous
1539 and binary_indices is None
1540 and self._mcmc_state.z is not None
1541 ):
1542 msg = 'Model has only binary outcomes, so there is no continuous submatrix to return.'
1543 raise ValueError(msg)
1545 return get_latent_prec(
1546 self._burnin_trace,
1547 self._main_trace,
1548 binary_indices,
1549 only_continuous=only_continuous,
1550 )
1552 @forbid_x64
1553 def get_error_sdev(
1554 self, mean: bool = False
1555 ) -> (
1556 Float32[Array, ' ndpost']
1557 | Float32[Array, 'ndpost k']
1558 | Float32[Array, '']
1559 | Float32[Array, ' k']
1560 ):
1561 """Return the error standard deviation, post-burnin, chains concatenated.
1563 Parameters
1564 ----------
1565 mean
1566 If `True`, average the error covariance matrix across samples before
1567 taking the square root, returning a single scalar or vector instead
1568 of posterior samples.
1570 Returns
1571 -------
1572 Posterior samples (or single estimate) of the error standard deviation; NaN for binary outcomes.
1574 Notes
1575 -----
1576 Binary outcomes do have a standard deviation of course, but it's not
1577 returned by this method because that would require to evaluate
1578 predictions on a given X, since the Bernoulli variance is p(1-p).
1579 """
1580 # binary outcomes are filled with NaN, so disable the NaN check
1581 with debug_nans(False):
1582 return get_error_sdev(
1583 self._main_trace,
1584 self._mcmc_state.binary_indices,
1585 has_binary=self._mcmc_state.z is not None,
1586 mean=mean,
1587 )
1589 @cached_property
1590 @forbid_x64
1591 def accept(
1592 self,
1593 ) -> (
1594 Float32[Array, ' n_burn_plus_n_save']
1595 | Float32[Array, 'num_chains n_burn_plus_n_save']
1596 ):
1597 """Fraction of trees with an accepted grow or prune move at each iteration.
1599 Includes the burn-in iterations and does not concatenate the chains, to
1600 allow checking convergence. The iterations thinned away by `n_skip` are
1601 not recorded.
1602 """
1603 return get_accept(self._burnin_trace, self._main_trace)
1605 @cached_property
1606 @forbid_x64
1607 def varcount(self) -> Int32[Array, 'ndpost p']:
1608 """Histogram of predictor usage for decision rules in the trees."""
1609 p = self._mcmc_state.forest.max_split.size
1610 return varcount(p, self._main_trace)
1612 @cached_property
1613 @forbid_x64
1614 def varcount_mean(self) -> Float32[Array, ' p']:
1615 """Average of `varcount` across MCMC iterations."""
1616 return self.varcount.mean(axis=0)
1618 @cached_property
1619 @forbid_x64
1620 def varprob(self) -> Float32[Array, 'ndpost p']:
1621 """Posterior samples of the probability of choosing each predictor for a decision rule."""
1622 return varprob(self._mcmc_state.forest, self._main_trace)
1624 @cached_property
1625 @forbid_x64
1626 def varprob_mean(self) -> Float32[Array, ' p']:
1627 """The marginal posterior probability of each predictor being chosen for a decision rule."""
1628 return self.varprob.mean(axis=0)
1630 def _process_error_scale_test(
1631 self,
1632 x_test: Real[ArrayLike, 'p m'] | DataFrame | Literal['train'],
1633 error_scale: Float[ArrayLike, ' m']
1634 | Float[ArrayLike, 'k m']
1635 | Series
1636 | DataFrame
1637 | None,
1638 *,
1639 basis: PredictKind,
1640 setting: str,
1641 ) -> Float32[Array, ' m'] | Float32[Array, 'k m'] | None:
1642 """Validate and resolve the error scales for prediction or scoring.
1644 Parameters
1645 ----------
1646 x_test
1647 The raw (not yet processed) test predictors, or ``'train'``.
1648 error_scale
1649 User-provided per-observation error scale, or `None`.
1650 basis
1651 The kind of predictions the computation is based on.
1652 setting
1653 Description of the arguments that determine `basis`, for error
1654 messages.
1656 Returns
1657 -------
1658 The resolved error scale as a float32 array, or `None` if not applicable.
1660 Raises
1661 ------
1662 ValueError
1663 If `error_scale` is specified when it should be `None`, or missing
1664 when required.
1665 """
1666 x_test_is_train = isinstance(x_test, str) and x_test == 'train'
1667 train_error_scale = self._mcmc_state.error_scale
1668 has_train_error_scale = train_error_scale is not None
1669 # the error scales enter the distribution of the outcome given the
1670 # parameters, and so the mean of binary outcomes, since P(y=1) =
1671 # Phi(latent / scale), but not the latent
1672 uses_error_scale = basis not in LATENT_PREDICTIONS and (
1673 self._mcmc_state.z is not None or basis not in MEAN_PREDICTIONS
1674 )
1676 if not has_train_error_scale or not uses_error_scale:
1677 if error_scale is not None:
1678 if has_train_error_scale:
1679 msg = (
1680 f'`error_scale` must be `None` with {setting}, because'
1681 ' the result does not depend on it (the error scales'
1682 ' enter the distribution of the outcome, and the mean'
1683 ' of binary outcomes)'
1684 )
1685 else:
1686 msg = (
1687 '`error_scale` must be `None` because the model was fit'
1688 ' without `error_scale`'
1689 )
1690 raise ValueError(msg)
1691 return None
1693 if x_test_is_train:
1694 if error_scale is not None:
1695 msg = (
1696 "`error_scale` must be `None` when x_test='train'"
1697 ' (the training error scales are used automatically)'
1698 )
1699 raise ValueError(msg)
1700 return train_error_scale
1702 # new test data, model was fit with error scales
1703 if error_scale is None:
1704 msg = (
1705 '`error_scale` is required because the model was fit with'
1706 ' `error_scale` and x_test is new data'
1707 )
1708 raise ValueError(msg)
1709 error_scale_test = _process_response_input(error_scale)
1710 assert train_error_scale is not None # checked above
1711 # the per-observation axis is checked separately, against x_test
1712 if error_scale_test.shape[:-1] != train_error_scale.shape[:-1]:
1713 msg = (
1714 f'`error_scale` shape mismatch with the training error scales: '
1715 f'got {error_scale_test.shape=}, but the leading dimensions must '
1716 f'match the training {train_error_scale.shape=} (only the '
1717 f'per-observation axis may differ).'
1718 )
1719 raise ValueError(msg)
1720 return error_scale_test
1722 def _process_x_test(
1723 self,
1724 x_test: Real[ArrayLike, 'p m'] | DataFrame | Literal['train'],
1725 error_scale: Float32[Array, ' m'] | Float32[Array, 'k m'] | None,
1726 ) -> tuple[UInt[Array, 'p m'], Bool[Array, ''] | None]:
1727 """Convert x_test to binned format suitable for prediction.
1729 Also return the pending NaN check on x_test, see `start_nan_check`.
1730 """
1731 if isinstance(x_test, str):
1732 if x_test != 'train': 1732 ↛ 1733line 1732 didn't jump to line 1733 because the condition on line 1732 was never true
1733 msg = (
1734 f"x_test must be an array, a DataFrame, or 'train', got {x_test!r}"
1735 )
1736 raise ValueError(msg)
1737 return self._mcmc_state.X, None
1739 else:
1740 x_test, x_test_fmt = _process_predictor_input(x_test)
1741 has_nan = start_nan_check(x_test)
1742 if x_test_fmt != self._x_train_fmt:
1743 msg = f'Input format mismatch: {x_test_fmt=} != x_train_fmt={self._x_train_fmt!r}'
1744 raise ValueError(msg)
1745 if error_scale is not None:
1746 check_length(error_scale, 'error_scale', x_test, 'x_test')
1747 return self._binner.bin(x_test), has_nan
1749 def _device_put_test(
1750 self,
1751 x_test: UInt[Array, 'p m'],
1752 error_scale: Float32[Array, ' m'] | Float32[Array, 'k m'] | None,
1753 ) -> tuple[UInt[Array, 'p m'], Float32[Array, ' m'] | Float32[Array, 'k m'] | None]:
1754 """Place new test data on the devices of the model, see `_device_put_test_array`."""
1755 put = self._device_put_test_array
1756 return put(x_test), None if error_scale is None else put(error_scale)
1758 def _device_put_test_array(
1759 self, a: Shaped[Array, '*shape m']
1760 ) -> Shaped[Array, '*shape m']:
1761 """Place a new test array, with the observations on the last axis, on the devices of the model.
1763 Mirror the placement of the training data done at fit time: shard over
1764 the mesh if there is one (the observation axis over 'data'), else move
1765 to the device requested explicitly at construction, if any. The input
1766 is donated, so it must not be used elsewhere.
1767 """
1768 mesh = self._mcmc_state.config.mesh
1769 if mesh is not None:
1770 return device_put(
1771 a,
1772 NamedSharding(mesh, leaf_partition_spec(a.ndim, None, -1, mesh)),
1773 donate=True,
1774 )
1775 elif self._device is not None:
1776 return device_put(a, self._device, donate=True)
1777 else:
1778 return a
1780 def _check_trees(
1781 self, error: bool = False
1782 ) -> UInt[Array, 'num_chains n_save num_trees']:
1783 """Apply `bartz.grove.check_trace` to all the tree draws.
1785 Parameters
1786 ----------
1787 error
1788 If `True`, throw an error if any invalid trees are found.
1790 Returns
1791 -------
1792 An array where non-zero entries indicate invalid trees.
1794 Raises
1795 ------
1796 RuntimeError
1797 If `error` is `True` and any invalid trees are found.
1798 """
1799 out = check_trees(self._main_trace, self._mcmc_state.forest.max_split)
1800 if error:
1801 bad_count = jnp.count_nonzero(out).item()
1802 if bad_count > 0:
1803 msg = f'Found {bad_count} invalid trees in the MCMC trace.'
1804 raise RuntimeError(msg)
1805 return out
1807 def _tree_goes_bad(self) -> Bool[Array, 'num_chains n_save num_trees']:
1808 """Find iterations where a tree becomes invalid.
1810 Returns
1811 -------
1812 An array where ``(i, j, k)`` is `True` if tree `k` is invalid at iteration `j` in chain `i` but not at iteration ``j - 1``.
1813 """
1814 return tree_goes_bad(self._main_trace, self._mcmc_state.forest.max_split)
1816 def _check_replicated_trees(self) -> None:
1817 """Check that the trees are equal across data-sharded devices.
1819 If the data is sharded across devices, verify that the trees (which
1820 should be replicated) are identical on all shards.
1822 Raises
1823 ------
1824 RuntimeError
1825 If the trees differ across devices.
1826 """
1827 state = self._mcmc_state
1828 mesh = state.config.mesh
1829 if mesh is not None and 'data' in mesh.axis_names:
1830 # drop the data-sharded `leaf_indices` (not replicated) before the
1831 # cross-shard equality check; `None` is a deliberately off-type
1832 # placeholder, so use `tree_at`, which (unlike `dataclasses.replace`)
1833 # bypasses the `__init__` type checks
1834 replicated_forest = tree_at(lambda f: f.leaf_indices, state.forest, None)
1835 equal = equal_shards(
1836 replicated_forest, 'data', in_specs=PartitionSpec(), mesh=mesh
1837 )
1838 equal_array = jnp.stack(tree.leaves(equal))
1839 all_equal = jnp.all(equal_array)
1840 if not all_equal.item(): 1840 ↛ 1841line 1840 didn't jump to line 1841 because the condition on line 1840 was never true
1841 msg = 'The trees differ across data-sharded devices.'
1842 raise RuntimeError(msg)
1844 def _compare_resid(
1845 self,
1846 ) -> tuple[
1847 Float32[Array, '*num_chains n'] | Float32[Array, '*num_chains k n'],
1848 Float32[Array, '*num_chains n'] | Float32[Array, '*num_chains k n'],
1849 ]:
1850 """Re-compute residuals to compare them with the updated ones.
1852 Returns
1853 -------
1854 resid1
1855 The final state of the residuals updated during the MCMC.
1856 resid2
1857 The residuals computed from the final state of the trees.
1858 """
1859 return compare_resid(self._mcmc_state)
1861 def _points_per_node_distr(
1862 self, node_type: Literal['leaf', 'leaf-parent']
1863 ) -> Int32[Array, '*num_chains n_save n_plus_1']:
1864 return points_per_node_distr_trace(
1865 self._mcmc_state.X, self._main_trace, node_type
1866 )
1868 def _points_per_decision_node_distr(
1869 self,
1870 ) -> Int32[Array, '*num_chains n_save n_plus_1']:
1871 """Histogram of number of points belonging to parent-of-leaf nodes.
1873 Returns
1874 -------
1875 For each chain, a matrix where each row contains a histogram of number of points.
1876 """
1877 return self._points_per_node_distr('leaf-parent')
1879 def _points_per_leaf_distr(self) -> Int32[Array, '*num_chains n_save n_plus_1']:
1880 """Histogram of number of points belonging to leaves.
1882 Returns
1883 -------
1884 A matrix where each row contains a histogram of number of points.
1885 """
1886 return self._points_per_node_distr('leaf')
1888 def _print_tree(
1889 self, i_chain: int, i_sample: int, i_tree: int, print_all: bool = False
1890 ) -> None:
1891 """Print a single tree in human-readable format.
1893 Parameters
1894 ----------
1895 i_chain
1896 The index of the MCMC chain.
1897 i_sample
1898 The index of the (post-burnin) sample in the chain.
1899 i_tree
1900 The index of the tree in the sample.
1901 print_all
1902 If `True`, also print the content of unused node slots.
1903 """
1904 trace = self._main_trace
1905 trees = project(TreesTrace, trace)
1906 index = (i_chain, i_sample, i_tree) if trace.has_chains else (i_sample, i_tree)
1907 # index the tree arrays, leaving the (unbatched) leaf scale alone; the
1908 # trailing ellipsis covers the extra `k` axis of multivariate leaves
1909 trees = tree_at(
1910 lambda t: (t.var_tree, t.split_tree, t.leaf_tree),
1911 trees,
1912 replace_fn=lambda x: x[(*index, ...)],
1913 )
1914 s = format_tree(trees, print_all=print_all)
1915 print(s) # noqa: T201, this method is intended for debug
1918def _process_predictor_input(
1919 x: Real[ArrayLike, 'p n'] | DataFrame,
1920) -> tuple[Shaped[Array, 'p n'], Any]:
1921 if isinstance(x, DataFrame):
1922 fmt = dict(kind='dataframe', columns=list(x.columns))
1923 x = x.to_numpy().T
1924 else:
1925 fmt = dict(kind='array', num_covar=x.shape[0])
1926 x = jnp.asarray(x)
1927 assert x.ndim == 2
1928 return x, fmt
1931def start_nan_check(x: Shaped[Array, 'p n']) -> Bool[Array, ''] | None:
1932 """Dispatch checking predictors for NaN, without waiting for the result.
1934 Returns `None` if the check does not apply, i.e., under jit or with
1935 non-floating predictors.
1936 """
1937 if jnp.issubdtype(x.dtype, jnp.floating) and not jit_active():
1938 return any_nan(x)
1939 else:
1940 return None
1943def raise_if_nan(has_nan: Bool[Array, ''] | None) -> None:
1944 """Wait for the result of `start_nan_check` and raise if it found NaN."""
1945 if has_nan is not None and has_nan.item():
1946 msg = 'predictors contain NaN; missing predictor values are not supported'
1947 raise ValueError(msg)
1950@jit
1951def any_nan(x: Float[Array, '*shape']) -> Bool[Array, '']:
1952 # A sum of non-negative terms is nan iff a term is nan, provided the
1953 # accumulator has inf to overflow to, hence float32 (some float8 types lack
1954 # inf). Unlike isnan or min/max, this fuses with the reduction and reliably
1955 # propagates nan on cpu.
1956 return jnp.isnan(jnp.sum(jnp.abs(x), dtype=jnp.float32))
1959def _process_response_input(
1960 arr: Shaped[ArrayLike, ' n'] | Shaped[ArrayLike, 'k n'] | Series | DataFrame,
1961 /,
1962 *,
1963 dtype: DTypeLike = jnp.float32,
1964) -> Shaped[Array, ' n'] | Shaped[Array, 'k n']:
1965 if isinstance(arr, DataFrame):
1966 arr = arr.to_numpy().T
1967 elif isinstance(arr, Series):
1968 arr = arr.to_numpy()
1969 # one unconditional copy, safe to donate downstream
1970 arr = jnp.array(arr, dtype, copy=True)
1971 if arr.ndim < 1 or arr.ndim > 2: 1971 ↛ 1972line 1971 didn't jump to line 1972 because the condition on line 1971 was never true
1972 msg = f'response-like input must be 1D (n,) or 2D (k, n). Got {arr.ndim=}.'
1973 raise ValueError(msg)
1974 return arr
1977def check_length(
1978 a: Shaped[Array, '*k n'], a_name: str, x: Shaped[Array, '*p m'], x_name: str
1979) -> None:
1980 """Check that `a` and `x`, named `a_name` and `x_name`, have as many datapoints on the last axis."""
1981 *_, n = a.shape
1982 *_, m = x.shape
1983 if n != m:
1984 msg = f'`{a_name}` has {n} datapoints, but `{x_name}` has {m}.'
1985 raise ValueError(msg)
1988def check_augment_depth(sparse: SparseConfig, maxdepth: int, p: int) -> None:
1989 # the augmentation tracks min(2 maxdepth, p) variables as bits of a uint32
1990 if sparse.enabled and sparse.augment and min(2 * maxdepth, p) > 32:
1991 msg = (
1992 f'maxdepth={maxdepth} > 16 with p={p} > 32 predictors is not '
1993 'supported with `SparseConfig(augment=True)`, set `augment=False`'
1994 )
1995 raise ValueError(msg)
1998def warn_byte_boundaries(
1999 x_train: UInt[Array, 'p n'], max_split: UInt[Array, ' p'], maxdepth: int
2000) -> None:
2001 """Warn if settings make arrays wider than one byte per element."""
2002 itemsize = max(x_train.dtype.itemsize, max_split.dtype.itemsize)
2003 if itemsize > 1:
2004 msg = (
2005 'More than 255 cutpoints per predictor make the binned predictors '
2006 f'and split points {8 * itemsize}-bit instead of 8-bit, increasing '
2007 'memory usage and running time. Consider using at most 255 cutpoints.'
2008 )
2009 warn(msg)
2010 if maxdepth > 8:
2011 msg = (
2012 f'maxdepth={maxdepth} > 8 makes the leaf indices 16-bit instead of '
2013 '8-bit, increasing memory usage and running time. Consider using '
2014 'maxdepth <= 8. Through bartz.stochtree.BARTModel, the equivalent '
2015 'is mean_forest_params=dict(max_depth=8) in sample().'
2016 )
2017 warn(msg)
2020def _check_type_settings(
2021 y_train: Float32[Array, ' n'] | Float32[Array, 'k n'],
2022 outcome_type: OutcomeType | str | Sequence[OutcomeType | str],
2023 error_scale: Float[Array, ' n'] | Float[Array, 'k n'] | None,
2024) -> tuple[OutcomeType | tuple[OutcomeType, ...], Bool[Array, ''] | Bool[Array, ' k']]:
2025 # standardize outcome_type to OutcomeType or tuple[OutcomeType, ...]
2026 if isinstance(outcome_type, Sequence) and not isinstance(outcome_type, str):
2027 outcome_type = tuple(OutcomeType(t) for t in outcome_type)
2028 num_types = len(outcome_type)
2029 if len(set(outcome_type)) == 1:
2030 outcome_type = outcome_type[0]
2031 else:
2032 num_types = None
2033 outcome_type = OutcomeType(outcome_type)
2035 # validation
2036 if num_types is not None and (y_train.ndim != 2 or num_types != y_train.shape[0]):
2037 msg = (
2038 f'Sequence outcome_type of length {num_types}'
2039 f' requires y_train.shape=({num_types}, n),'
2040 f' found {y_train.shape=}.'
2041 )
2042 raise ValueError(msg)
2043 if (
2044 error_scale is not None
2045 and error_scale.ndim == 2
2046 and (y_train.ndim != 2 or error_scale.shape[0] != y_train.shape[0])
2047 ):
2048 msg = (
2049 f'2D error_scale (per-component scales) requires y_train of '
2050 f'shape (k, n) with matching k; got {error_scale.shape=}, '
2051 f'{y_train.shape=}.'
2052 )
2053 raise ValueError(msg)
2055 if isinstance(outcome_type, tuple):
2056 binary_mask = jnp.array([t is OutcomeType.binary for t in outcome_type])
2057 else:
2058 binary_mask = jnp.bool_(outcome_type is OutcomeType.binary)
2059 binary_mask = jnp.broadcast_to(binary_mask, y_train.shape[:-1])
2061 return outcome_type, binary_mask
2064class SparseKwArgs(TypedDict):
2065 theta: FloatLike | None
2066 a: FloatLike | None
2067 b: FloatLike | None
2068 rho: FloatLike | None
2069 sparse_on_at: int | None
2070 augment: bool
2073def _process_sparsity_settings(
2074 max_split: UInt[Array, ' p'], sparse: SparseConfig, n_burn: int
2075) -> SparseKwArgs:
2076 """Return the arguments for `mcmcstep.init` related to sparsity."""
2077 theta = a = b = rho = sparse_on_at = None
2078 if sparse.enabled:
2079 sparse_on_at = n_burn // 2
2080 if sparse.theta is not None:
2081 theta = sparse.theta
2082 else:
2083 a, b, rho = sparse.a, sparse.b, sparse.rho
2084 if rho is None:
2085 # ignore predictors without decision rules
2086 rho = count_selectable(max_split > 0).astype(jnp.float32)
2087 return SparseKwArgs(
2088 theta=theta,
2089 a=a,
2090 b=b,
2091 rho=rho,
2092 sparse_on_at=sparse_on_at,
2093 augment=sparse.augment,
2094 )
2097@jit
2098def _process_offset_settings(
2099 y_train: Float32[Array, ' n'] | Float32[Array, 'k n'],
2100 binary_mask: Bool[Array, ''] | Bool[Array, ' k'],
2101 missing: Bool[Array, ' n'] | Bool[Array, 'k n'] | None,
2102 offset: Float32[Array, ''] | Float32[Array, ' k'] | None,
2103) -> Float32[Array, ''] | Float32[Array, ' k']:
2104 """Determine and return offset."""
2105 if offset is not None:
2106 return jnp.broadcast_to(offset, y_train.shape[:-1])
2107 if y_train.shape[-1] < 1:
2108 return jnp.zeros(y_train.shape[:-1])
2110 if missing is None:
2111 *_, n_valid = y_train.shape
2112 prop = (y_train != 0).mean(-1)
2113 mean = y_train.mean(-1)
2114 else:
2115 *_, n = y_train.shape
2116 n_valid = n - jnp.count_nonzero(missing, axis=-1)
2117 safe_n = jnp.maximum(n_valid, 1)
2118 prop = jnp.where(missing, 0, y_train != 0).sum(-1) / safe_n
2119 mean = jnp.where(missing, 0.0, y_train).sum(-1) / safe_n
2121 bound = jnp.reciprocal(1.0 + n_valid)
2122 binary_offset = ndtri(jnp.clip(prop, bound, 1 - bound))
2123 offset = jnp.where(binary_mask, binary_offset, mean)
2124 return jnp.where(n_valid > 0, offset, 0.0)
2127@jit
2128def _process_leaf_variance_settings(
2129 y_train: Float32[Array, ' n'] | Float32[Array, 'k n'],
2130 binary_mask: Bool[Array, ''] | Bool[Array, ' k'],
2131 missing: Bool[Array, ' n'] | Bool[Array, 'k n'] | None,
2132 *,
2133 k: Float[Array, ''],
2134 tau_num: Float[Array, ''] | None,
2135 sigma_mu_df: Float[Array, ''] | None,
2136) -> Wishart:
2137 """Return `sum_trees_prior_cov_inv`, with a prior iff `sigma_mu_df` is set.
2139 See `bartz.mcmcstep.Forest.sum_trees_prior_cov_inv`; the prior on it is
2140 the one on the leaf precision rescaled by the number of trees.
2141 """
2142 # determine `tau_num` if not specified
2143 *kshape, n = y_train.shape
2144 if tau_num is None:
2145 if n < 2:
2146 continuous_tau = jnp.ones(kshape)
2147 elif missing is None:
2148 continuous_tau = (y_train.max(-1) - y_train.min(-1)) / 2
2149 else:
2150 n_valid = n - jnp.count_nonzero(missing, axis=-1)
2151 ymax = jnp.where(missing, -jnp.inf, y_train).max(-1)
2152 ymin = jnp.where(missing, jnp.inf, y_train).min(-1)
2153 continuous_tau = jnp.where(n_valid >= 2, (ymax - ymin) / 2, 1.0)
2154 tau_num = jnp.where(binary_mask, 3.0, continuous_tau)
2156 # prior standard deviation of the sum of trees, the leaf one (sigma_mu)
2157 # times the square root of the number of trees
2158 sigma_sum = tau_num / k
2160 # prior precision matrix of the sum of trees
2161 sigma2_sum = jnp.broadcast_to(jnp.square(sigma_sum), kshape)
2162 sum_trees_prior_cov_inv = jnp.reciprocal(sigma2_sum)
2163 if y_train.ndim == 2:
2164 sum_trees_prior_cov_inv = jnp.diag(sum_trees_prior_cov_inv)
2166 if sigma_mu_df is None:
2167 return Wishart(nu=None, rate=None, value=sum_trees_prior_cov_inv)
2168 else:
2169 # each marginal variance is inverse-gamma with alpha = sigma_mu_df / 2
2170 # and beta = rate_ii / 2, so rate_ii = sigma_mu_df * sigma2_sum makes
2171 # sigma2_sum its harmonic mean for any k
2172 rate = sigma_mu_df * sigma2_sum
2173 if y_train.ndim == 2:
2174 rate = jnp.diag(rate)
2175 return Wishart.from_inv_wishart_marginal_nu(
2176 sigma_mu_df, rate, sum_trees_prior_cov_inv
2177 )
2180def _process_error_variance_settings(
2181 y_train: Float32[Array, ' n'] | Float32[Array, 'k n'],
2182 binary_mask: Bool[Array, ''] | Bool[Array, ' k'],
2183 missing: Bool[Array, ' n'] | Bool[Array, 'k n'] | None,
2184 *,
2185 outcome_type: OutcomeType | tuple[OutcomeType, ...],
2186 sigma_df: FloatLike,
2187 sigma_scale: FloatLike | Float[ArrayLike, ' k'] | Literal['auto'],
2188 sigma_init: FloatLike | Float[ArrayLike, ' k'] | Literal['auto'],
2189 error_scale: Float32[Array, ' n'] | Float32[Array, 'k n'] | None,
2190) -> Wishart | None:
2191 """Build the error precision prior from the user settings."""
2192 if outcome_type is OutcomeType.binary:
2193 if not isinstance(sigma_scale, str) or not isinstance(sigma_init, str):
2194 msg = (
2195 'Do not set `sigma_scale` or `sigma_init` for binary regression, '
2196 'they are ignored'
2197 )
2198 raise ValueError(msg)
2199 return None
2201 *kdims, _ = y_train.shape # () or (k,)
2202 sigma_df = jnp.asarray(sigma_df, jnp.float32)
2204 # guarded per-component variance of y_train, computed only when an 'auto'
2205 # spec needs it (this function is not jitted, so it would not be elided)
2206 if isinstance(sigma_scale, str) or isinstance(sigma_init, str):
2207 vary = _guarded_response_variance(y_train, error_scale, missing)
2208 else:
2209 vary = None
2211 # prior rate: each marginal variance is inverse-gamma with alpha =
2212 # sigma_df / 2 and beta = rate_ii / 2, so rate_ii = sigma_df * var makes var
2213 # its harmonic mean for any k
2214 rate_diag = jnp.where(
2215 binary_mask, 0.0, sigma_df * _resolve_error_variance(sigma_scale, vary, kdims)
2216 )
2218 # initial precision = 1 / var per component (1 for binary components)
2219 init_var = _resolve_error_variance(sigma_init, vary, kdims)
2220 init_diag = jnp.where(binary_mask, 1.0, jnp.reciprocal(init_var))
2222 if y_train.ndim == 2:
2223 rate, init = jnp.diag(rate_diag), jnp.diag(init_diag)
2224 else:
2225 rate, init = rate_diag, init_diag
2226 return make_error_cov_prior(sigma_df, rate, init, outcome_type, missing)
2229@jit
2230def _guarded_response_variance(
2231 y_train: Float32[Array, ' n'] | Float32[Array, 'k n'],
2232 error_scale: Float32[Array, ' n'] | Float32[Array, 'k n'] | None,
2233 missing: Bool[Array, ' n'] | Bool[Array, 'k n'] | None,
2234) -> Float32[Array, '*k']:
2235 """Per-component variance of `y_train`, used by the 'auto' error scale.
2237 A precision-weighted variance (precision ``1 / error_scale ** 2``) estimates
2238 ``sigma ** 2`` at unit error scale; `missing` entries are dropped. The
2239 variance is guarded to 1 when undefined (fewer than 2 valid points) or
2240 non-positive.
2241 """
2242 if error_scale is None and missing is None:
2243 vary = jnp.var(y_train, axis=-1)
2244 return jnp.where(vary > 0, vary, 1.0)
2245 else:
2246 prec = (
2247 jnp.ones(())
2248 if error_scale is None
2249 else jnp.reciprocal(jnp.square(error_scale))
2250 )
2251 if missing is not None:
2252 prec = jnp.where(missing, 0.0, prec)
2253 y_train = jnp.where(missing, 0.0, y_train)
2254 n_valid = jnp.count_nonzero(prec, axis=-1)
2255 wmean = jnp.sum(prec * y_train, axis=-1) / jnp.sum(prec, axis=-1)
2256 sqdev = prec * jnp.square(y_train - wmean[..., None])
2257 vary = jnp.sum(sqdev, axis=-1) / n_valid
2258 # guard on n_valid too: with a single valid point the variance is 0 in
2259 # exact arithmetic, but float rounding in wmean can leave a tiny
2260 # positive vary that would slip past the `vary > 0` guard
2261 return jnp.where((n_valid > 1) & (vary > 0), vary, 1.0)
2264def _resolve_error_variance(
2265 spec: FloatLike | Float[ArrayLike, ' k'] | Literal['auto'],
2266 vary: Float32[Array, '*k'] | None,
2267 shape: Sequence[int],
2268) -> Float32[Array, '*k']:
2269 """Per-component error variance from a scale spec ('auto' uses var(y))."""
2270 if isinstance(spec, str):
2271 if spec != 'auto':
2272 msg = f"unrecognized value {spec!r}, expected 'auto' or a number"
2273 raise ValueError(msg)
2274 assert vary is not None # computed iff some spec is 'auto'
2275 return vary
2276 else:
2277 return jnp.broadcast_to(jnp.square(jnp.asarray(spec, jnp.float32)), shape)
2280def make_error_cov_prior(
2281 marginal_nu: Float32[Array, ''],
2282 rate: Float32[Array, ''] | Float32[Array, 'k k'],
2283 value: Float32[Array, ''] | Float32[Array, 'k k'],
2284 outcome_type: OutcomeType | tuple[OutcomeType, ...],
2285 missing: Bool[Array, ' n'] | Bool[Array, 'k n'] | None,
2286) -> Wishart:
2287 """Build the error precision prior, diagonal-constrained where required.
2289 Mixed binary-continuous and partial-missing (2-D mask) regression restrict
2290 the error covariance to diagonal, so they take a `DiagWishart`; the dense
2291 cases take a `Wishart`. `init` re-checks this choice. `marginal_nu` is the
2292 degrees of freedom of each marginal variance, `value` the initial value of
2293 the precision.
2294 """
2295 if isinstance(outcome_type, tuple):
2296 binary = [t is OutcomeType.binary for t in outcome_type]
2297 is_mixed = any(binary) and not all(binary)
2298 else:
2299 is_mixed = False
2300 # a 2-D missingness mask only occurs with multivariate y (checked in `init`)
2301 partial_missing = missing is not None and missing.ndim == 2
2302 cls = DiagWishart if is_mixed or partial_missing else Wishart
2303 return cls.from_inv_wishart_marginal_nu(marginal_nu, rate, value)
2306def _setup_mcmc(
2307 mcmc_key: Key[Array, ''],
2308 x_train: Real[Array, 'p n'],
2309 y_train: Float32[Array, ' n'] | Float32[Array, 'k n'],
2310 *,
2311 outcome_type: OutcomeType | tuple[OutcomeType, ...],
2312 offset: Float32[Array, ''] | Float32[Array, ' k'],
2313 error_scale: Float[Array, ' n'] | Float[Array, 'k n'] | None,
2314 missing: Bool[Array, ' n'] | Bool[Array, 'k n'] | None,
2315 max_split: UInt[Array, ' p'],
2316 sum_trees_prior_cov_inv: Wishart,
2317 error_cov_inv: Wishart | None,
2318 power: FloatLike,
2319 base: FloatLike,
2320 maxdepth: int,
2321 num_trees: int,
2322 init_kw: Mapping[str, Any],
2323 rm_const: bool,
2324 sparse: SparseConfig,
2325 varprob: Float[ArrayLike, ' p'] | None,
2326 num_chains: int | None,
2327 num_chain_devices: int | None | Literal['auto'],
2328 num_data_devices: int | None,
2329 devices: Literal['cpu', 'gpu'] | Device | Sequence[Device] | None,
2330 n_burn: int,
2331) -> tuple[State, Key[Array, ''], Device | None, Literal['cpu', 'gpu'] | None]:
2332 max_split, log_s, filter_splitless_vars = process_varprob(
2333 varprob, max_split, rm_const=rm_const, sparse=sparse.enabled
2334 )
2335 sparse_kw = _process_sparsity_settings(max_split, sparse, n_burn)
2337 device_kw, device, check_platform = process_device_settings(
2338 y_train, num_chains, num_chain_devices, num_data_devices, devices
2339 )
2341 kw: dict = dict(
2342 X=x_train,
2343 y=y_train,
2344 outcome_type=outcome_type,
2345 offset=offset,
2346 error_scale=error_scale,
2347 missing=missing,
2348 max_split=max_split,
2349 num_trees=num_trees,
2350 p_nonterminal=make_p_nonterminal(maxdepth, base, power),
2351 sum_trees_prior_cov_inv=sum_trees_prior_cov_inv,
2352 error_cov_inv=error_cov_inv,
2353 min_points_per_decision_node=10,
2354 filter_splitless_vars=filter_splitless_vars,
2355 log_s=log_s,
2356 **sparse_kw,
2357 **device_kw,
2358 )
2360 kw = dict(kw, **init_kw)
2362 state = init(**kw)
2364 # put state and mcmc key on device if requested explicitly by the user
2365 if device is not None:
2366 mcmc_key, state = device_put((mcmc_key, state), device, donate=True)
2368 return state, mcmc_key, device, check_platform
2371def _run_mcmc(
2372 key: Key[Array, ''],
2373 mcmc_state: State,
2374 n_save: int,
2375 *,
2376 n_burn: int,
2377 n_skip: int,
2378 printevery: int | None,
2379 pbar: bool,
2380 precompute_predict_train: bool,
2381 run_mcmc_kw: Mapping,
2382 check_platform: Literal['cpu', 'gpu'] | None,
2383) -> RunMCMCResult:
2384 # fill list of callbacks
2385 callbacks = ()
2386 if printevery is not None:
2387 if pbar:
2388 callbacks += (TqdmCallback.from_state(mcmc_state, report_every=printevery),)
2389 else:
2390 callbacks += (
2391 PrintCallback.from_state(
2392 mcmc_state,
2393 dot_every=None if printevery == 1 else 1,
2394 report_every=printevery,
2395 ),
2396 )
2397 if check_platform is not None:
2398 callbacks += (CheckPlatformCallback(check_platform),)
2400 # prepare arguments
2401 kw: dict = dict(
2402 n_burn=n_burn,
2403 n_skip=n_skip,
2404 inner_loop_length=printevery,
2405 callback=CallbackTuple(callbacks),
2406 )
2407 if precompute_predict_train:
2408 kw = dict(**kw, main_trace_type=MainTraceWithTrainPred)
2409 kw = dict(kw, **run_mcmc_kw)
2411 return run_mcmc(key, mcmc_state, n_save, **kw)
2414@jit(static_argnames='p')
2415# this is jitted such that lax.collapse below does not create a copy
2416def varcount(p: int, trace: MainTrace) -> Int32[Array, 'ndpost p']:
2417 """Histogram of predictor usage for decision rules in the trees, squashing chains."""
2418 varcount: Int32[Array, '*chains samples p']
2419 varcount = compute_varcount(p, trace)
2420 return lax.collapse(varcount, 0, -1)
2423@jit(static_argnames=('has_binary', 'mean'))
2424def get_error_sdev(
2425 trace: MainTrace,
2426 binary_indices: Int32[Array, ' kb'] | None,
2427 *,
2428 has_binary: bool,
2429 mean: bool = False,
2430) -> (
2431 Float32[Array, ' ndpost']
2432 | Float32[Array, 'ndpost k']
2433 | Float32[Array, '']
2434 | Float32[Array, ' k']
2435):
2436 """Error standard deviation, post-burnin, chains concatenated."""
2437 prec = trace.error_cov_inv
2438 if trace.has_chains:
2439 # shape (chains, samples) or (chains, samples, k, k), concatenate chains
2440 prec = lax.collapse(prec, 0, 2)
2441 is_uv = prec.ndim == 1
2442 if is_uv:
2443 # univariate case, reshape to 1x1 matrix
2444 prec = prec[..., None, None]
2446 # invert precision to covariance, then take diagonal variance
2447 cov = inv_via_chol_with_gersh(prec)
2448 var = jnp.diagonal(cov, axis1=-2, axis2=-1)
2449 if mean:
2450 var = var.mean(0)
2451 sdev = jnp.sqrt(var)
2452 if is_uv:
2453 sdev = sdev.squeeze(-1)
2454 if binary_indices is not None:
2455 sdev = sdev.at[..., binary_indices].set(jnp.nan, unique_indices=True)
2456 elif has_binary:
2457 sdev = jnp.full_like(sdev, jnp.nan)
2458 return sdev
2461@jit(static_argnames='only_continuous')
2462def get_latent_prec(
2463 burnin_trace: BurninTrace,
2464 main_trace: MainTrace,
2465 binary_indices: Int32[Array, ' kb'] | None,
2466 *,
2467 only_continuous: bool = False,
2468) -> (
2469 Float32[Array, ' n_burn_plus_n_save']
2470 | Float32[Array, 'n_burn_plus_n_save k k']
2471 | Float32[Array, 'num_chains n_burn_plus_n_save']
2472 | Float32[Array, 'num_chains n_burn_plus_n_save k k']
2473):
2474 """Latent error precision trace, burn-in + main concatenated."""
2475 burnin = burnin_trace.error_cov_inv
2476 main = main_trace.error_cov_inv
2477 sample_axis = trace_sample_axes(main_trace).error_cov_inv
2478 prec = jnp.concatenate([burnin, main], axis=sample_axis)
2479 if only_continuous and binary_indices is not None:
2480 *_, k, _ = prec.shape
2481 kc = k - binary_indices.size
2482 mask = (
2483 jnp.ones(k, dtype=bool).at[binary_indices].set(False, unique_indices=True)
2484 )
2485 (cont_indices,) = jnp.nonzero(mask, size=kc)
2486 prec = prec[..., cont_indices[:, None], cont_indices[None, :]]
2487 return prec
2490@jit
2491def get_accept(
2492 burnin_trace: BurninTrace, main_trace: MainTrace
2493) -> (
2494 Float32[Array, ' n_burn_plus_n_save']
2495 | Float32[Array, 'num_chains n_burn_plus_n_save']
2496):
2497 """Fraction of trees with an accepted move, burn-in + main concatenated."""
2498 sample_axis = trace_sample_axes(main_trace).grow_acc_count
2499 acc = jnp.concatenate(
2500 [
2501 burnin_trace.grow_acc_count + burnin_trace.prune_acc_count,
2502 main_trace.grow_acc_count + main_trace.prune_acc_count,
2503 ],
2504 axis=sample_axis,
2505 )
2506 *_, num_trees, _ = main_trace.split_tree.shape
2507 return acc / num_trees
2510@jit
2511def varprob(forest: Forest, trace: MainTrace) -> Float32[Array, 'ndpost p']:
2512 """Posterior samples of predictor selection probability, chains concatenated."""
2513 max_split = forest.max_split
2514 p = max_split.size
2515 ndpost = trace.grow_prop_count.size
2516 varprob = trace.varprob
2517 if varprob is None:
2518 p_eff = jnp.count_nonzero(max_split)
2519 out = jnp.where(max_split, 1 / p_eff, 0)
2520 return jnp.broadcast_to(out, (ndpost, p))
2521 elif isinstance(varprob, VarprobInState):
2522 log_s = forest.sparsity.log_s
2523 assert log_s is not None
2524 out = softmax(log_s, where=max_split.astype(bool))
2525 return jnp.broadcast_to(out, (ndpost, p))
2526 else:
2527 return varprob.reshape(-1, p)
2530@jit
2531def check_trees(
2532 trace: MainTrace, max_split: UInt[Array, ' p']
2533) -> UInt[Array, 'num_chains n_save num_trees']:
2534 """Apply `bartz.grove.check_trace` to all the tree draws."""
2535 trees = project(TreesTrace, trace)
2536 out: UInt[Array, '*chains samples num_trees']
2537 out = check_trace(trees, max_split)
2538 if out.ndim < 3:
2539 out = out[None, :, :]
2540 return out
2543@jit
2544def tree_goes_bad(
2545 trace: MainTrace, max_split: UInt[Array, ' p']
2546) -> Bool[Array, 'num_chains n_save num_trees']:
2547 """Find iterations where a tree becomes invalid."""
2548 bad = check_trees(trace, max_split).astype(bool)
2549 bad_before = jnp.pad(bad[:, :-1, :], [(0, 0), (1, 0), (0, 0)])
2550 return bad & ~bad_before
2553@jit
2554def compare_resid(
2555 state: State,
2556) -> tuple[
2557 Float32[Array, '*num_chains n'] | Float32[Array, '*num_chains k n'],
2558 Float32[Array, '*num_chains n'] | Float32[Array, '*num_chains k n'],
2559]:
2560 """Re-compute residuals to compare them with the updated ones."""
2561 resid1 = state.resid * state.resid_unit[..., None]
2563 forests = project(TreesTrace, state.forest)
2564 trees = evaluate_forest(state.X, forests, sum_batch_axis=-1)
2566 if state.has_chains: 2566 ↛ 2569line 2566 didn't jump to line 2569 because the condition on line 2566 was always true
2567 ref = vmap(outcome_target, in_axes=(chain_vmap_axes(state),))(state)
2568 else:
2569 ref = outcome_target(state)
2570 resid2 = ref - (trees + state.forest.offset[..., None])
2572 return resid1, resid2
2575@jit(static_argnames='node_type')
2576def points_per_node_distr_trace(
2577 X: UInt[Array, 'p n'], trace: MainTrace, node_type: Literal['leaf', 'leaf-parent']
2578) -> Int32[Array, '*num_chains n_save n+1']:
2579 """Histogram of number of points per node, for every tree draw in the trace."""
2580 out: Int32[Array, '*chains samples n+1']
2581 out = points_per_node_distr(
2582 X, trace.var_tree, trace.split_tree, node_type, sum_batch_axis=-1
2583 )
2584 if out.ndim < 3:
2585 out = out[None, :, :]
2586 return out
2589class DeviceKwArgs(TypedDict):
2590 num_chains: int | None
2591 mesh: Mesh | None
2592 leaf_dtype: DTypeLike
2593 prec_scale_dtype: DTypeLike
2596def process_device_settings(
2597 y_train: Float32[Array, ' n'] | Float32[Array, 'k n'],
2598 num_chains: int | None,
2599 num_chain_devices: int | None | Literal['auto'],
2600 num_data_devices: int | None,
2601 devices: Literal['cpu', 'gpu'] | Device | Sequence[Device] | None,
2602) -> tuple[DeviceKwArgs, Device | None, Literal['cpu', 'gpu'] | None]:
2603 """Return the arguments for `mcmcstep.init` related to devices, an optional device where to put the state, and the platform to check at runtime iff it was deduced."""
2604 # whether the user pinned a concrete pool of devices (vs. inheriting all of
2605 # the platform's devices); the auto chain sharding may not exceed that pool
2606 explicit_devices = devices is not None and not isinstance(devices, str)
2608 # the platform is deduced (rather than fixed by the user) only when neither a
2609 # device pool nor a platform string is passed
2610 platform_deduced = devices is None
2612 platform, device, devices = _determine_devices(y_train, devices)
2613 check_platform = platform if platform_deduced else None
2614 num_chain_devices = _determine_num_chain_devices(
2615 platform,
2616 num_chains,
2617 num_chain_devices,
2618 num_data_devices=num_data_devices,
2619 num_devices=len(devices),
2620 explicit_devices=explicit_devices,
2621 )
2622 mesh, device = _determine_mesh(num_chain_devices, num_data_devices, device, devices)
2624 # prepare arguments to `init`
2625 dtype = jnp.float16 if platform == 'gpu' else jnp.float32
2626 settings = DeviceKwArgs(
2627 num_chains=num_chains, mesh=mesh, leaf_dtype=dtype, prec_scale_dtype=dtype
2628 )
2630 return settings, device, check_platform
2633def _determine_devices(
2634 y_train: Float32[Array, ' n'] | Float32[Array, 'k n'],
2635 devices: Literal['cpu', 'gpu'] | Device | Sequence[Device] | None,
2636) -> tuple[Literal['cpu', 'gpu'], Device | None, Sequence[Device]]:
2637 """Determine the target platform and set of devices for the MCMC, and possibly a single target device."""
2638 if isinstance(devices, str):
2639 platform: Literal['cpu', 'gpu'] = devices # ty:ignore[invalid-assignment]
2640 devices = jax.devices(platform)
2641 return platform, devices[0], devices
2642 elif devices is not None:
2643 if not hasattr(devices, '__len__'):
2644 devices = (devices,)
2645 device = devices[0]
2646 return device.platform, device, devices
2647 elif hasattr(y_train, 'platform'): 2647 ↛ 2654line 2647 didn't jump to line 2654 because the condition on line 2647 was always true
2648 # set device=None because if the devices were not specified explicitly
2649 # we may be in the case where computation will follow data placement,
2650 # do not disturb jax as the user may be playing with vmap, jit, reshard...
2651 platform = cast(Literal['cpu', 'gpu'], y_train.platform())
2652 return platform, None, jax.devices(platform)
2653 else:
2654 msg = 'not possible to infer device from `y_train`, please set `devices`'
2655 raise ValueError(msg)
2658def _largest_divisor_at_most(n: int, cap: int) -> int:
2659 """Return the largest divisor of `n` in [1, cap]."""
2660 for d in range(cap, 0, -1): 2660 ↛ 2663line 2660 didn't jump to line 2663 because the loop on line 2660 didn't complete
2661 if n % d == 0:
2662 return d
2663 return 1 # unreachable: 1 always divides n
2666def _determine_num_chain_devices(
2667 platform: str,
2668 num_chains: int | None,
2669 num_chain_devices: int | None | Literal['auto'],
2670 *,
2671 num_data_devices: int | None,
2672 num_devices: int,
2673 explicit_devices: bool,
2674) -> int | None:
2675 """Resolve and validate `num_chain_devices`, returning the chain mesh axis size or `None`."""
2676 if num_chain_devices == 'auto':
2677 num_chain_devices = _auto_num_chain_devices(
2678 platform, num_chains, num_data_devices, num_devices, explicit_devices
2679 )
2681 # an explicit value must be a positive divisor of the number of chains
2682 if num_chain_devices is not None:
2683 effective_chains = 1 if num_chains is None else num_chains
2684 if num_chain_devices < 1 or effective_chains % num_chain_devices:
2685 chains_desc = (
2686 'a single chain (num_chains=None)'
2687 if num_chains is None
2688 else f'num_chains={num_chains}'
2689 )
2690 msg = (
2691 f'num_chain_devices={num_chain_devices} must be a positive '
2692 f'divisor of the number of chains ({chains_desc})'
2693 )
2694 raise ValueError(msg)
2696 # there is no chain axis to shard when the chains are scalar
2697 if num_chains is None:
2698 return None
2699 return num_chain_devices
2702def _auto_num_chain_devices(
2703 platform: str,
2704 num_chains: int | None,
2705 num_data_devices: int | None,
2706 num_devices: int,
2707 explicit_devices: bool,
2708) -> int | None:
2709 """Pick `num_chain_devices` automatically for multi-chain runs.
2711 `num_data_devices` reserves devices for the data axis, so the chain axis can
2712 only use a fraction of them; this keeps the ``chains x data`` mesh within the
2713 `num_devices` available devices.
2714 """
2715 if num_chains is None or num_chains == 1:
2716 return None
2717 data_devices = num_data_devices or 1
2719 # the mesh draws from `num_devices` devices, whether those are all the
2720 # platform's devices or an explicit subset passed by the user
2721 device_budget = max(1, num_devices // data_devices)
2723 if platform == 'cpu':
2724 # cpu devices are virtual, so aim for one per core, and warn if jax is
2725 # set up with fewer
2726 core_budget = max(1, get_available_cpu_count() // data_devices)
2727 num_shards = _largest_divisor_at_most(num_chains, core_budget)
2728 if num_shards > device_budget:
2729 new_num_shards = _largest_divisor_at_most(num_chains, device_budget)
2730 warn(
2731 _auto_chain_devices_warning(
2732 num_chains=num_chains,
2733 desired=num_shards,
2734 actual=new_num_shards,
2735 device_budget=device_budget,
2736 num_devices=num_devices,
2737 num_data_devices=num_data_devices,
2738 explicit_devices=explicit_devices,
2739 )
2740 )
2741 num_shards = new_num_shards
2742 else:
2743 # accelerators are physical, so use all of them
2744 num_shards = _largest_divisor_at_most(num_chains, device_budget)
2746 return num_shards if num_shards > 1 else None
2749def _auto_chain_devices_warning(
2750 *,
2751 num_chains: int,
2752 desired: int,
2753 actual: int,
2754 device_budget: int,
2755 num_devices: int,
2756 num_data_devices: int | None,
2757 explicit_devices: bool,
2758) -> str:
2759 """Compose the warning shown when auto chain sharding is capped by the device count."""
2760 if explicit_devices:
2761 pool = f'the {num_devices} devices passed in `devices`'
2762 few = f'only {num_devices} devices were passed in `devices`'
2763 advice = ''
2764 else:
2765 pool = f'the {num_devices} jax cpu devices'
2766 few = f'jax is set up with only {num_devices} cpu devices'
2767 advice = (
2768 ' To enable more parallelization, increase the limit with '
2769 '`jax.config.update("jax_num_cpu_devices", <num_devices>)`.'
2770 )
2771 if num_data_devices:
2772 limit = (
2773 f'only {device_budget} of {pool} are free for chains '
2774 f'(num_data_devices={num_data_devices} reserves the rest)'
2775 )
2776 else:
2777 limit = few
2778 return (
2779 f'`Bart` would like to shard {num_chains} chains across {desired} '
2780 f'devices, but {limit}, so it will use {actual} devices for chains '
2781 f'instead.{advice}'
2782 )
2785def _determine_mesh(
2786 num_chain_devices: int | None,
2787 num_data_devices: int | None,
2788 device: Device | None,
2789 devices: Sequence[Device],
2790) -> tuple[Mesh, None] | tuple[None, Device | None]:
2791 """Create a jax device mesh for `mcmcstep.init()`."""
2792 if num_chain_devices is None and num_data_devices is None:
2793 return None, device
2794 else:
2795 mesh = {}
2796 if num_chain_devices is not None:
2797 mesh.update(chains=num_chain_devices)
2798 if num_data_devices is not None:
2799 mesh.update(data=num_data_devices)
2800 mesh = make_mesh(
2801 tuple(mesh.values()),
2802 tuple(mesh),
2803 axis_types=(AxisType.Auto,) * len(mesh),
2804 devices=devices,
2805 )
2806 return mesh, None
2807 # set device=None because `mcmcstep.init` will `device_put` with the
2808 # mesh already, we don't want to undo its work
2811def apply_varprob(
2812 varprob: Float[ArrayLike, ' p'] | None,
2813 max_split: UInt[Array, ' p'],
2814 name: str,
2815 *,
2816 sparse: bool = False,
2817) -> tuple[UInt[Array, ' p'], Float32[Array, ' p'] | None]:
2818 """Block the predictors with zero `varprob` and convert it to `log_s`.
2820 With `sparse`, `varprob` is only the initial value of the chain, so zero is
2821 rejected instead of excluding the predictor.
2822 """
2823 if varprob is None:
2824 return max_split, None
2826 varprob = jnp.asarray(varprob, jnp.float32)
2827 if varprob.shape != max_split.shape:
2828 msg = f'`{name}` must have shape {max_split.shape}, got {varprob.shape}'
2829 raise ValueError(msg)
2831 if sparse:
2832 valid = jnp.all(varprob > 0)
2833 msg = f'`{name}` must be > 0 with sparsity, as it is only the initial value'
2834 else:
2835 valid = jnp.all(varprob >= 0) & jnp.any(varprob > 0)
2836 msg = f'`{name}` must be >= 0, with at least one > 0'
2838 varprob = error_if(varprob, ~valid, msg)
2839 blocked = varprob == 0
2840 log_s = jnp.log(jnp.where(blocked, 1.0, varprob))
2841 return jnp.where(blocked, 0, max_split), log_s
2844def process_varprob(
2845 varprob: Float[ArrayLike, ' p'] | None,
2846 max_split: UInt[Array, ' p'],
2847 *,
2848 rm_const: bool,
2849 sparse: bool,
2850) -> tuple[UInt[Array, ' p'], Float32[Array, ' p'] | None, int]:
2851 """Block the predictors with zero `varprob`, and set `filter_splitless_vars`."""
2852 blocked_max_split, log_s = apply_varprob(
2853 varprob, max_split, 'varprob', sparse=sparse
2854 )
2855 if rm_const:
2856 filter_splitless_vars = jnp.sum(blocked_max_split == 0).item()
2857 elif varprob is None or sparse:
2858 # nothing is blocked, `init` raises if some predictor has no splits
2859 filter_splitless_vars = 0
2860 else:
2861 # `varprob` may be traced, so allow up to all but one predictor to be
2862 # blocked, which is cheap with `log_s` set, and check by hand that the
2863 # predictors without splits are blocked
2864 unblocked = (max_split == 0) & (jnp.asarray(varprob) != 0)
2865 blocked_max_split = error_if(
2866 blocked_max_split,
2867 jnp.any(unblocked),
2868 'there are predictors with no splits and nonzero `varprob`, set '
2869 '`rm_const=True` to ignore them',
2870 )
2871 (p,) = max_split.shape
2872 filter_splitless_vars = p - 1
2873 return blocked_max_split, log_s, filter_splitless_vars
2876def check_level(
2877 level: FloatLike | None, *, used: bool, setting: str
2878) -> Float[Array, ''] | None:
2879 """Check `level` is in (0, 1) when `used`, and not specified otherwise."""
2880 msg = None
2881 if used and level is None:
2882 msg = f'{setting} requires `level`'
2883 elif not used and level is not None:
2884 msg = f'`level` must be `None` because {setting} does not use it'
2885 if msg is not None:
2886 raise ValueError(msg)
2887 if level is not None:
2888 level = jnp.asarray(level)
2889 level = error_if(
2890 level, ~((level > 0) & (level < 1)), '`level` must be in (0, 1)'
2891 )
2892 return level
2895def allow_nans(nan_filled: bool) -> AbstractContextManager:
2896 """Disable `jax_debug_nans` if the output is filled with NaN on purpose."""
2897 # jax checks the outputs of the jitted calls, so this must wrap them
2898 return debug_nans(False) if nan_filled else nullcontext()
2901def predict_latent(
2902 x: UInt[Array, 'p m'],
2903 trace: MainTrace,
2904 test_points: Literal['none', 'autobatch', 'shard_and_autobatch'] = 'none',
2905) -> Float32[Array, 'ndpost m'] | Float32[Array, 'ndpost k m']:
2906 """Evaluate trees on already quantized `x`, and squash chains."""
2907 return evaluate_trace(x, trace, flatten_chains=True, test_points=test_points)
2910@jit(static_argnames=('has_binary', 'kind', 'test_points'))
2911def predict(
2912 key: Key[Array, ''] | None,
2913 trace: MainTrace,
2914 x_test: UInt[Array, 'p m'],
2915 *,
2916 error_scale: Float[Array, ' m'] | Float[Array, 'k m'] | None,
2917 binary_indices: Int32[Array, ' kb'] | None,
2918 has_binary: bool,
2919 kind: PredictKind,
2920 level: FloatLike | None,
2921 test_points: Literal['none', 'autobatch', 'shard_and_autobatch'],
2922) -> Prediction:
2923 """Implement `Bart.predict` by evaluating the trees on `x_test`."""
2924 # get latent i.e. bare sum-of-trees predictions
2925 latent = predict_latent(x_test, trace, test_points)
2926 return _predict_from_latent(
2927 key,
2928 trace,
2929 latent,
2930 error_scale=error_scale,
2931 binary_indices=binary_indices,
2932 has_binary=has_binary,
2933 kind=kind,
2934 level=level,
2935 )
2938@jit(static_argnames=('has_binary', 'kind'))
2939def predict_train(
2940 key: Key[Array, ''] | None,
2941 trace: MainTraceWithTrainPred,
2942 *,
2943 error_scale: Float[Array, ' n'] | Float[Array, 'k n'] | None,
2944 binary_indices: Int32[Array, ' kb'] | None,
2945 has_binary: bool,
2946 kind: PredictKind,
2947 level: FloatLike | None,
2948) -> Prediction:
2949 """Implement `Bart.predict('train')` from the precomputed predictions."""
2950 latent = _flatten_chain_sample(trace.train_pred, has_chains=trace.has_chains)
2951 return _predict_from_latent(
2952 key,
2953 trace,
2954 latent,
2955 error_scale=error_scale,
2956 binary_indices=binary_indices,
2957 has_binary=has_binary,
2958 kind=kind,
2959 level=level,
2960 )
2963def _predict_from_latent(
2964 key: Key[Array, ''] | None,
2965 trace: MainTrace,
2966 latent: Float32[Array, 'ndpost m'] | Float32[Array, 'ndpost k m'],
2967 *,
2968 error_scale: Float[Array, ' m'] | Float[Array, 'k m'] | None,
2969 binary_indices: Int32[Array, ' kb'] | None,
2970 has_binary: bool,
2971 kind: PredictKind,
2972 level: FloatLike | None,
2973) -> Prediction:
2974 """Turn the sum-of-trees `latent` samples into the requested prediction kind."""
2975 if kind is PredictKind.outcome_samples:
2976 assert key is not None
2977 out = sample_outcome(
2978 key,
2979 trace,
2980 latent,
2981 error_scale=error_scale,
2982 binary_indices=binary_indices,
2983 has_binary=has_binary,
2984 )
2985 else:
2986 out = summarize_latent(
2987 latent,
2988 trace.error_cov_inv,
2989 error_scale=error_scale,
2990 binary_indices=binary_indices,
2991 has_binary=has_binary,
2992 kind=kind,
2993 level=level,
2994 )
2995 return out
2998def summarize_latent(
2999 latent: Float32[Array, 'ndpost m'] | Float32[Array, 'ndpost k m'],
3000 error_cov_inv: Float32[Array, '*chains_and_samples']
3001 | Float32[Array, '*chains_and_samples k k'],
3002 *,
3003 error_scale: Float[Array, ' m'] | Float[Array, 'k m'] | None,
3004 binary_indices: Int32[Array, ' kb'] | None,
3005 has_binary: bool,
3006 kind: PredictKind,
3007 level: FloatLike | None,
3008) -> Prediction:
3009 """Compute the prediction kinds that are deterministic given `latent`."""
3010 # bring the univariate case to the multivariate layout with k = 1
3011 univariate = latent.ndim == 2
3012 if univariate:
3013 latent = latent[:, None, :]
3014 ndpost, k, m = latent.shape
3015 w = jnp.broadcast_to(1.0 if error_scale is None else error_scale, (k, m))
3016 binary = binary_mask(k, binary_indices, has_binary)
3018 # covariance of the latent error, before scaling it by `w`, with unit
3019 # variance for binary components
3020 cov = inv_via_chol_with_gersh(error_cov_inv.reshape(ndpost, k, k))
3022 sdev = latent_sdev(cov, w)
3023 mean_samples = conditional_mean(latent, sdev, binary)
3025 if kind in LATENT_PREDICTIONS:
3026 out = summarize_samples(kind, latent, level)
3027 elif kind in MEAN_PREDICTIONS:
3028 out = summarize_samples(kind, mean_samples, level)
3029 else:
3030 out = summarize_outcome(
3031 kind,
3032 latent=latent,
3033 mean_samples=mean_samples,
3034 cov=cov,
3035 sdev=sdev,
3036 w=w,
3037 binary=binary,
3038 level=level,
3039 )
3041 # remove the k = 1 axes if the outcome is univariate, they are always
3042 # just before the axis of the test points
3043 if univariate:
3044 out = out.squeeze((-3, -2) if kind in COV_PREDICTIONS else -2)
3046 return out
3049def summarize_samples(
3050 kind: PredictKind, samples: Float32[Array, 'ndpost k m'], level: FloatLike | None
3051) -> MultivariatePrediction:
3052 """Compute a ``latent_*`` or ``mean*`` kind from the samples of its quantity."""
3053 match kind:
3054 case PredictKind.latent_samples | PredictKind.mean_samples:
3055 out = samples
3056 case PredictKind.latent_mean | PredictKind.mean:
3057 out = samples.mean(0)
3058 case PredictKind.latent_cov | PredictKind.mean_cov:
3059 out = sample_cov(samples)
3060 case PredictKind.latent_var | PredictKind.mean_var:
3061 out = samples.var(0)
3062 case PredictKind.latent_sdev | PredictKind.mean_sdev:
3063 out = samples.std(0)
3064 case PredictKind.latent_interval | PredictKind.mean_interval: 3064 ↛ 3067line 3064 didn't jump to line 3067 because the pattern on line 3064 always matched
3065 tail = tail_probability(level)
3066 out = samples_quantile(samples, jnp.stack([tail, 1 - tail]))
3067 return out
3070def summarize_outcome( # noqa: C901, the match over the kinds
3071 kind: PredictKind,
3072 *,
3073 latent: Float32[Array, 'ndpost k m'],
3074 mean_samples: Float32[Array, 'ndpost k m'],
3075 cov: Float32[Array, 'ndpost k k'],
3076 sdev: Float32[Array, 'ndpost k m'],
3077 w: Float32[Array, 'k m'],
3078 binary: Bool[Array, ' k'],
3079 level: FloatLike | None,
3080) -> MultivariatePrediction:
3081 """Compute a ``cond_*`` or ``outcome_*`` kind, other than ``outcome_samples``.
3083 `cov` is the covariance of the latent error before scaling it by `w`, and
3084 `sdev` its marginal sdev after.
3085 """
3086 # variance of the outcome given the parameters
3087 var = jnp.where(
3088 binary[:, None], mean_samples * (1 - mean_samples), jnp.square(sdev)
3089 )
3091 match kind:
3092 case PredictKind.cond_cov_samples:
3093 out = conditional_cov(cov, w, var, binary)
3094 case PredictKind.cond_var_samples:
3095 out = var
3096 case PredictKind.cond_sdev_samples:
3097 out = jnp.sqrt(var)
3098 case PredictKind.cond_cov:
3099 # the conditional covariance is linear in `cov` and `var`
3100 out = conditional_cov(cov.mean(0), w, var.mean(0), binary)
3101 case PredictKind.cond_var:
3102 out = var.mean(0)
3103 case PredictKind.cond_sdev:
3104 out = jnp.sqrt(var.mean(0))
3105 case PredictKind.outcome_cov:
3106 cond = conditional_cov(cov.mean(0), w, var.mean(0), binary)
3107 out = cond + sample_cov(mean_samples)
3108 case PredictKind.outcome_var:
3109 out = var.mean(0) + mean_samples.var(0)
3110 case PredictKind.outcome_sdev:
3111 out = jnp.sqrt(var.mean(0) + mean_samples.var(0))
3112 case PredictKind.outcome_interval: 3112 ↛ 3115line 3112 didn't jump to line 3115 because the pattern on line 3112 always matched
3113 interval = mixture_interval(latent, sdev, level)
3114 out = jnp.where(binary[:, None], jnp.nan, interval)
3115 return out
3118def binary_mask(
3119 k: int, binary_indices: Int32[Array, ' kb'] | None, has_binary: bool
3120) -> Bool[Array, ' k']:
3121 """Return a mask of the binary outcome components."""
3122 if not has_binary:
3123 return jnp.zeros(k, bool)
3124 elif binary_indices is None:
3125 return jnp.ones(k, bool)
3126 else:
3127 return jnp.zeros(k, bool).at[binary_indices].set(True, unique_indices=True)
3130def latent_sdev(
3131 cov: Float32[Array, 'ndpost k k'], w: Float32[Array, 'k m']
3132) -> Float32[Array, 'ndpost k m']:
3133 """Marginal sdev of the latent error, given its covariance before scaling by `w`."""
3134 var = jnp.diagonal(cov, axis1=-2, axis2=-1)
3135 return jnp.sqrt(var)[:, :, None] * w
3138def conditional_mean(
3139 latent: Float32[Array, 'ndpost k m'],
3140 sdev: Float32[Array, 'ndpost k m'],
3141 binary: Bool[Array, ' k'],
3142) -> Float32[Array, 'ndpost k m']:
3143 """Mean of the outcome given the parameters, P(y=1) on binary components."""
3144 return jnp.where(binary[:, None], ndtr(latent / sdev), latent)
3147def conditional_cov(
3148 cov: Float32[Array, '*batch k k'],
3149 w: Float32[Array, 'k m'],
3150 var: Float32[Array, '*batch k m'],
3151 binary: Bool[Array, ' k'],
3152) -> Float32[Array, '*batch k k m']:
3153 """Covariance of the outcome given the parameters.
3155 `cov` is the covariance of the latent error before scaling it by `w`, and
3156 `var` the variance of the outcome.
3157 """
3158 *_, k, _ = cov.shape
3159 out = cov[..., :, :, None] * w[:, None, :] * w[None, :, :]
3160 # binary components are independent of the others, with variance `var`
3161 continuous = ~binary
3162 out = jnp.where(continuous[:, None, None] & continuous[None, :, None], out, 0.0)
3163 diagonal = jnp.eye(k, dtype=bool)[:, :, None]
3164 return jnp.where(diagonal, var[..., :, None, :], out)
3167def sample_cov(samples: Float32[Array, 'ndpost k m']) -> Float32[Array, 'k k m']:
3168 """Covariance across the components of the empirical distribution of `samples`."""
3169 num_samples, _, _ = samples.shape
3170 dev = samples - samples.mean(0)
3171 return jnp.einsum('sim,sjm->ijm', dev, dev) / num_samples
3174def mixture_interval(
3175 loc: Float32[Array, 'ndpost k m'],
3176 scale: Float32[Array, 'ndpost k m'],
3177 level: FloatLike | None,
3178) -> Float32[Array, '2 k m']:
3179 """Equal-tailed interval of an equal-weight mixture of normal distributions."""
3180 tail = tail_probability(level)
3181 prob = jnp.stack([tail, 1 - tail])[:, None, None]
3183 # the quantile of the mixture is between the extreme quantiles of the
3184 # components, and bisection keeps it inside the bracket
3185 quantiles = loc + scale * ndtri(prob)[:, None, :, :]
3186 bracket = quantiles.min(1), quantiles.max(1)
3188 def bisect(
3189 _: Int32[Array, ''],
3190 bracket: tuple[Float32[Array, '2 k m'], Float32[Array, '2 k m']],
3191 ) -> tuple[Float32[Array, '2 k m'], Float32[Array, '2 k m']]:
3192 lo, hi = bracket
3193 mid = (lo + hi) / 2
3194 cdf = ndtr((mid[:, None, :, :] - loc) / scale).mean(1)
3195 below = cdf < prob
3196 return jnp.where(below, mid, lo), jnp.where(below, hi, mid)
3198 # halve the bracket until it's narrower than the float resolution of its
3199 # initial width
3200 num_steps = jnp.finfo(loc.dtype).nmant + 2
3201 lo, hi = lax.fori_loop(0, num_steps, bisect, bracket)
3202 return (lo + hi) / 2
3205def _flatten_chain_sample(
3206 arr: Float[Array, '*shape'], *, has_chains: bool
3207) -> Float[Array, '*flat_shape']:
3208 """Fold the chain axis into the sample axis, matching `predict_latent`'s layout."""
3209 if has_chains:
3210 return lax.collapse(arr, 0, 2)
3211 else:
3212 return arr
3215@jit(static_argnames='has_binary')
3216def sample_outcome(
3217 key: Key[Array, ''],
3218 trace: MainTrace,
3219 latent: Float32[Array, 'ndpost m'] | Float32[Array, 'ndpost k m'],
3220 *,
3221 error_scale: Float32[Array, ' m'] | Float32[Array, 'k m'] | None,
3222 binary_indices: Int32[Array, ' kb'] | None,
3223 has_binary: bool,
3224) -> Float32[Array, 'ndpost m'] | Float32[Array, 'ndpost k m']:
3225 """Sample from the posterior predictive distribution."""
3226 prec = trace.error_cov_inv
3228 if latent.ndim > 2: # multivariate case
3229 error_cov_inv = lax.collapse(prec, 0, -2)
3231 # Cholesky of precision: error_cov_inv = L @ L^T
3232 L = chol_with_gersh(error_cov_inv) # (ndpost, k, k)
3234 # Sample z ~ N(0, I) and solve L^T @ error = z
3235 # so error = L^{-T} z ~ N(0, L^{-T} L^{-1}) = N(0, Sigma)
3236 z = random.normal(key, latent.shape) # (ndpost, k, m)
3237 error = solve_triangular(L, z, trans='T', lower=True) # (ndpost, k, m)
3238 if error_scale is not None: 3238 ↛ 3251line 3238 didn't jump to line 3251 because the condition on line 3238 was always true
3239 # error_scale is (m,) or (k, m) so it always broadcasts right
3240 error *= error_scale
3241 else: # univariate
3242 # pure binary probit has unit-scale latent error; continuous scales it
3243 # by `sigma`. Either way, optionally rescaled per datapoint by error_scale.
3244 error = random.normal(key, latent.shape)
3245 if not has_binary:
3246 sigma = jnp.sqrt(jnp.reciprocal(prec)).reshape(-1)
3247 error *= sigma[..., None]
3248 if error_scale is not None:
3249 error *= error_scale[None, :]
3251 outcome = latent + error
3253 # convert binary outcomes via latent probit thresholding
3254 if binary_indices is not None:
3255 idx = jnp.s_[..., binary_indices, :]
3256 outcome = outcome.at[idx].set(
3257 jnp.where(outcome[idx] > 0, 1.0, 0.0), unique_indices=True
3258 )
3259 elif has_binary:
3260 outcome = jnp.where(outcome > 0, 1.0, 0.0)
3262 return outcome
3265def score_basis(kind: ScoreKind, target: ScoreTarget) -> PredictKind:
3266 """Return the kind of predictions a score is computed from."""
3267 match target:
3268 case ScoreTarget.latent:
3269 out = PredictKind.latent_samples
3270 case ScoreTarget.mean:
3271 out = PredictKind.mean_samples
3272 case ScoreTarget.outcome if kind in (
3273 ScoreKind.mse,
3274 ScoreKind.rmse,
3275 ScoreKind.r2,
3276 ScoreKind.brier,
3277 ):
3278 # the point prediction of the outcome is its mean
3279 out = PredictKind.mean
3280 case ScoreTarget.outcome: 3280 ↛ 3282line 3280 didn't jump to line 3282 because the pattern on line 3280 always matched
3281 out = PredictKind.outcome_samples
3282 return out
3285@jit(static_argnames=('has_binary', 'kind', 'target'))
3286def score(
3287 latent: Float32[Array, 'ndpost m'] | Float32[Array, 'ndpost k m'],
3288 error_cov_inv: Float32[Array, '*chains_and_samples']
3289 | Float32[Array, '*chains_and_samples k k'],
3290 truth: Float32[Array, ' m'] | Float32[Array, 'k m'],
3291 *,
3292 error_scale: Float32[Array, ' m'] | Float32[Array, 'k m'] | None,
3293 binary_indices: Int32[Array, ' kb'] | None,
3294 has_binary: bool,
3295 kind: ScoreKind,
3296 target: ScoreTarget,
3297 level: FloatLike | None,
3298) -> (
3299 Float32[Array, '']
3300 | Float32[Array, ' k']
3301 | Float32[Array, ' m']
3302 | Float32[Array, 'k m']
3303 | Float32[Array, 'ndpost m']
3304 | Float32[Array, 'ndpost k m']
3305):
3306 """Implement `Bart.score` given the latent samples at the test points."""
3307 # bring the univariate case to the multivariate layout with k = 1
3308 univariate = truth.ndim == 1
3309 if univariate:
3310 latent = latent[:, None, :]
3311 truth = truth[None, :]
3312 ndpost, k, _ = latent.shape
3313 prec = error_cov_inv.reshape(ndpost, k, k)
3314 w = jnp.broadcast_to(1.0 if error_scale is None else error_scale, truth.shape)
3315 binary = binary_mask(k, binary_indices, has_binary)
3317 # binary outcomes are booleans like `y_train`, the other truths are used as is
3318 if target is ScoreTarget.outcome:
3319 truth = jnp.where(binary[:, None], truth != 0, truth)
3321 # marginal sdev of the latent error, with unit variance for binary components
3322 sdev = latent_sdev(inv_via_chol_with_gersh(prec), w)
3324 if kind in DENSITY_KINDS:
3325 out = density_score(
3326 kind, latent=latent, prec=prec, y=truth, w=w, sdev=sdev, binary=binary
3327 )
3328 else:
3329 out = component_score(
3330 kind,
3331 target,
3332 latent=latent,
3333 mean_samples=conditional_mean(latent, sdev, binary),
3334 sdev=sdev,
3335 truth=truth,
3336 binary=binary,
3337 level=level,
3338 )
3340 # remove k=1 axis if the input was scalar
3341 if univariate and kind not in JOINT_KINDS:
3342 k_axis = 1 if kind in (ScoreKind.loglik, ScoreKind.loglik_marginal) else 0
3343 out = out.squeeze(k_axis)
3345 return out
3348def density_score(
3349 kind: ScoreKind,
3350 *,
3351 latent: Float32[Array, 'ndpost k m'],
3352 prec: Float32[Array, 'ndpost k k'],
3353 y: Float32[Array, 'k m'],
3354 w: Float32[Array, 'k m'],
3355 sdev: Float32[Array, 'ndpost k m'],
3356 binary: Bool[Array, ' k'],
3357) -> (
3358 Float32[Array, '']
3359 | Float32[Array, ' k']
3360 | Float32[Array, ' m']
3361 | Float32[Array, 'k m']
3362 | Float32[Array, 'ndpost m']
3363 | Float32[Array, 'ndpost k m']
3364):
3365 """Compute the scores based on the density of the outcome."""
3366 # `y` must be an outcome if we arrive here, it's not a mean or a latent
3368 # binary components: P(y = 1) = Phi(latent / sdev)
3369 sign = 2 * y - 1
3370 probit = jnp.where(binary[:, None], log_ndtr(sign * latent / sdev), 0.0)
3372 if kind in JOINT_KINDS:
3373 loglik = joint_normal_loglik(latent=latent, prec=prec, y=y, w=w, binary=binary)
3374 loglik += probit.sum(1)
3375 else:
3376 normal = norm.logpdf(y, latent, sdev)
3377 loglik = jnp.where(binary[:, None], probit, normal)
3379 lpd = logmeanexp(loglik, axis=0)
3381 match kind:
3382 case ScoreKind.loglik | ScoreKind.loglik_joint | ScoreKind.loglik_marginal:
3383 out = loglik
3384 case ScoreKind.lpd | ScoreKind.lpd_joint | ScoreKind.lpd_marginal:
3385 out = lpd
3386 case ScoreKind.mlpd | ScoreKind.mlpd_joint | ScoreKind.mlpd_marginal:
3387 out = lpd.mean(-1)
3388 case ScoreKind.logloss: 3388 ↛ 3391line 3388 didn't jump to line 3391 because the pattern on line 3388 always matched
3389 out = -lpd.mean(-1)
3391 return out
3394def joint_normal_loglik(
3395 *,
3396 latent: Float32[Array, 'ndpost k m'],
3397 prec: Float32[Array, 'ndpost k k'],
3398 y: Float32[Array, 'k m'],
3399 w: Float32[Array, 'k m'],
3400 binary: Bool[Array, ' k'],
3401) -> Float32[Array, 'ndpost m']:
3402 """Compute the log density of the continuous components, joint across them."""
3403 # the error is normal with covariance D Sigma D, D = diag(w). The latent
3404 # errors of the binary components are independent of the others with unit
3405 # variance, so their rows and columns of `prec` are those of the identity,
3406 # and zeroing their residuals drops them out.
3407 continuous = ~binary[:, None]
3408 resid = jnp.where(continuous, (y - latent) / w, 0.0)
3409 L = chol_with_gersh(prec) # prec = L L^T
3410 quad = jnp.square(jnp.einsum('sjl,sjm->slm', L, resid)).sum(1)
3411 logdet = _logdet_from_chol(L)
3412 log_w = jnp.where(continuous, jnp.log(w), 0.0).sum(0)
3413 num_continuous = jnp.count_nonzero(continuous)
3414 out = 0.5 * (logdet[:, None] - quad - num_continuous * jnp.log(2 * jnp.pi))
3415 return out - log_w
3418def component_score( # noqa: C901, the match over the kinds
3419 kind: ScoreKind,
3420 target: ScoreTarget,
3421 *,
3422 latent: Float32[Array, 'ndpost k m'],
3423 mean_samples: Float32[Array, 'ndpost k m'],
3424 sdev: Float32[Array, 'ndpost k m'],
3425 truth: Float32[Array, 'k m'],
3426 binary: Bool[Array, ' k'],
3427 level: FloatLike | None,
3428) -> Float32[Array, ' k'] | Float32[Array, 'k m']:
3429 """Compute the scores which are separate for each component."""
3430 # the point prediction of the outcome is its mean
3431 samples = latent if target is ScoreTarget.latent else mean_samples
3432 sq_err = jnp.square(truth - samples.mean(0))
3433 mse = sq_err.mean(-1)
3434 outcome = target is ScoreTarget.outcome
3436 match kind:
3437 case ScoreKind.mse:
3438 out = mse
3439 case ScoreKind.rmse:
3440 out = jnp.sqrt(mse)
3441 case ScoreKind.r2:
3442 out = 1 - mse / jnp.var(truth, axis=-1)
3443 case ScoreKind.brier:
3444 out = jnp.where(binary, mse, jnp.nan)
3445 case ScoreKind.crps if outcome:
3446 # the CRPS of a Bernoulli is the squared error of the probability
3447 crps = crps_normal_mixture(truth, latent, sdev)
3448 out = jnp.where(binary[:, None], sq_err, crps).mean(-1)
3449 case ScoreKind.crps:
3450 out = crps_samples(truth, samples).mean(-1)
3451 case ScoreKind.pit if outcome:
3452 pit = ndtr((truth - latent) / sdev).mean(0)
3453 out = jnp.where(binary[:, None], jnp.nan, pit)
3454 case ScoreKind.pit:
3455 out = samples_cdf(samples, truth)
3456 case ScoreKind.coverage if outcome:
3457 # the interval is of the mixture, whose cdf is the mean of the cdfs
3458 cdf = ndtr((truth - latent) / sdev).mean(0)
3459 tail = tail_probability(level)
3460 coverage = ((cdf >= tail) & (cdf <= 1 - tail)).mean(-1)
3461 out = jnp.where(binary, jnp.nan, coverage)
3462 case ScoreKind.coverage: 3462 ↛ 3467line 3462 didn't jump to line 3467 because the pattern on line 3462 always matched
3463 tail = tail_probability(level)
3464 lo, hi = samples_quantile(samples, jnp.stack([tail, 1 - tail]))
3465 out = ((lo <= truth) & (truth <= hi)).mean(-1)
3467 return out
3470def tail_probability(level: FloatLike | None) -> FloatLike:
3471 """Probability outside an equal-tailed interval on each side."""
3472 assert level is not None # checked by `Bart.score` and `Bart.predict`
3473 return (1 - level) / 2
3476def samples_cdf(
3477 samples: Float32[Array, ' num_samples *shape'], x: Float32[Array, '*shape']
3478) -> Float32[Array, '*shape']:
3479 """Cumulative distribution function of `samples`, interpolated, evaluated at `x`.
3481 The interpolated distribution puts mass 1 / num_samples uniformly on each
3482 gap between consecutive samples, and 1 / (2 num_samples) on the smallest
3483 and on the largest sample. Its quantile function is `samples_quantile`.
3484 """
3485 num_samples, *_ = samples.shape
3486 xs = jnp.sort(samples, axis=0)
3487 left = xs[:-1, ...]
3488 right = xs[1:, ...]
3490 # each gap between consecutive samples carries 1 / num_samples uniformly,
3491 # or as an atom if the samples are tied
3492 gap = right - left
3493 positive = gap > 0
3494 in_gap = jnp.clip((x - left) / jnp.where(positive, gap, 1.0), 0.0, 1.0)
3495 in_gap = jnp.where(positive, in_gap, x >= left)
3497 # plus 1 / (2 num_samples) on each of the extreme samples
3498 ends = 0.5 * (x >= xs[0, ...]) + 0.5 * (x >= xs[-1, ...])
3499 return (ends + in_gap.sum(0)) / num_samples
3502def samples_quantile(
3503 samples: Float32[Array, ' num_samples *shape'], prob: Float32[Array, ' q']
3504) -> Float32[Array, ' q *shape']:
3505 """Quantiles of `samples` like ``numpy.quantile(..., method='hazen')``.
3507 The sorted samples are the quantiles at ``(r + 1/2) / num_samples``, for r
3508 = 0, ..., num_samples - 1, with linear interpolation in between, and the
3509 extreme samples beyond.
3510 """
3511 num_samples, *_ = samples.shape
3512 xs = jnp.sort(samples, axis=0)
3513 pos = jnp.clip(num_samples * prob - 0.5, 0, num_samples - 1)
3514 below = jnp.floor(pos).astype(jnp.int32)
3515 above = jnp.minimum(below + 1, num_samples - 1)
3516 weight = (pos - below).reshape(pos.shape + (1,) * (xs.ndim - 1))
3517 return xs[below, ...] + weight * (xs[above, ...] - xs[below, ...])
3520def crps_normal_mixture(
3521 y: Float32[Array, '*shape'],
3522 loc: Float32[Array, ' num_samples *shape'],
3523 scale: Float32[Array, ' num_samples *shape'],
3524) -> Float32[Array, '*shape']:
3525 """CRPS of an equal-weight mixture of normal distributions, evaluated at `y`.
3527 Use ``CRPS(F, y) = E|X - y| - E|X - X'| / 2``, with X, X' ~ F independent
3528 (Gneiting & Raftery 2007, eq. 21), which is closed-form for normals.
3529 """
3530 num_samples, *_ = loc.shape
3531 to_y = mean_abs_normal(y - loc, scale).mean(0)
3533 # sum E|X_s - X_t| over the sample pairs (s, t), looping over the offset t - s
3534 # mod num_samples; the offsets r and num_samples - r give the same terms
3535 def add_offset(
3536 r: Int32[Array, ''], acc: Float32[Array, '*shape']
3537 ) -> Float32[Array, '*shape']:
3538 loc_r = jnp.roll(loc, r, axis=0)
3539 scale_r = jnp.roll(scale, r, axis=0)
3540 pair_scale = jnp.hypot(scale, scale_r)
3541 terms = mean_abs_normal(loc - loc_r, pair_scale).sum(0)
3542 return acc + jnp.where(2 * r == num_samples, 1, 2) * terms
3544 # at offset 0, E|N(0, 2 scale^2)| = 2 scale / sqrt(pi)
3545 diagonal = 2 * lax.rsqrt(jnp.pi) * scale.sum(0)
3546 # loop instead of vectorizing to keep the memory linear in num_samples
3547 pairs = lax.fori_loop(1, num_samples // 2 + 1, add_offset, diagonal)
3548 # float to avoid overflowing int32
3549 return to_y - pairs / (2.0 * num_samples * num_samples)
3552def mean_abs_normal(
3553 loc: Float32[Array, '*shape'], scale: Float32[Array, '*shape']
3554) -> Float32[Array, '*shape']:
3555 """Compute ``E|X|`` with ``X ~ N(loc, scale^2)``."""
3556 z = loc / scale
3557 return loc * (2 * ndtr(z) - 1) + 2 * scale * norm.pdf(z)
3560def crps_samples(
3561 y: Float32[Array, '*shape'], samples: Float32[Array, ' num_samples *shape']
3562) -> Float32[Array, '*shape']:
3563 """CRPS of the empirical distribution of `samples`, evaluated at `y`.
3565 Use ``CRPS(F, y) = E|X - y| - E|X - X'| / 2`` as `crps_normal_mixture`,
3566 with the sum over the pairs of samples computed from the sorted samples.
3567 """
3568 num_samples, *_ = samples.shape
3569 # center to reduce the rounding errors in the sum over pairs
3570 center = samples.mean(0)
3571 x = jnp.sort(samples - center, axis=0)
3572 to_y = jnp.abs(x - (y - center)).mean(0)
3573 # sum_{s,t} |x_s - x_t| = 2 sum_r (2r - S + 1) x_(r), r = 0, ..., S - 1
3574 weight = 2 * jnp.arange(num_samples) - (num_samples - 1)
3575 pairs = 2 * jnp.einsum('s,s...->...', weight, x)
3576 # float to avoid overflowing int32
3577 return to_y - pairs / (2.0 * num_samples * num_samples)