Coverage for src/bartz/mcmcstep/_state.py: 99%

723 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-30 12:50 +0000

1# bartz/src/bartz/mcmcstep/_state.py 

2# 

3# Copyright (c) 2024-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. 

24 

25"""Module defining the BART MCMC state and initialization.""" 

26 

27import math 

28from collections.abc import Callable, Sequence 

29from dataclasses import dataclass, replace 

30from enum import Enum 

31from functools import partial, reduce, wraps 

32from typing import Literal, NamedTuple, TypedDict, TypeVar, cast 

33from warnings import warn 

34 

35import jax 

36import numpy 

37from equinox import error_if, filter_jit 

38from jax import NamedSharding, device_put, lax, make_mesh, random, shard_map, tree, vmap 

39from jax import numpy as jnp 

40from jax.sharding import AxisType, Mesh, PartitionSpec 

41from jax.typing import DTypeLike 

42from jaxtyping import ( 

43 Array, 

44 Bool, 

45 Float, 

46 Float32, 

47 Int32, 

48 Integer, 

49 Key, 

50 PyTree, 

51 Shaped, 

52 UInt, 

53 UInt32, 

54) 

55from numpy import ndarray 

56 

57from bartz._jaxext import ( 

58 Module, 

59 cholesky, 

60 field, 

61 float32_matmuls, 

62 forbid_x64, 

63 get_cpu_thread_count, 

64 jaxtyping_disabled, 

65 jit, 

66 jit_active, 

67 minimal_unsigned_arange, 

68 minimal_unsigned_dtype, 

69 solve_triangular, 

70) 

71from bartz.grove import tree_depths 

72from bartz.mcmcstep._axes import CHAIN_AXIS, chain_vmap_axes, data_vmap_axes 

73from bartz.mcmcstep._lazy import ( 

74 _is_lazy_or_none, 

75 _lazy_from_array, 

76 _LazyArray, 

77 _wrap_chain, 

78 add_dummy_axis, 

79 lazy, 

80) 

81from bartz.mcmcstep._reduction import ( 

82 AutoBatchedReduction, 

83 AutoOneHotOrPopcountReduction, 

84 AutoOneHotReduction, 

85 ReductionConfig, 

86) 

87from bartz.npz import serializable 

88 

89ArrayLike = Array | ndarray 

90 

91FloatLike = float | Float[ArrayLike, ''] 

92 

93 

94class OutcomeType(Enum): 

95 """Likelihood types for each outcome component in the regression.""" 

96 

97 continuous = 'continuous' 

98 """Continuous outcome with Normal error.""" 

99 

100 binary = 'binary' 

101 """Binary outcome in {0, 1} with probit link.""" 

102 

103 

104T = TypeVar('T') 

105 

106 

107@serializable 

108class Wishart(Module): 

109 """A precision matrix with a Wishart prior, bundled with its current value. 

110 

111 Represents a random precision (inverse covariance) ``value`` drawn from a 

112 Wishart prior with degrees of freedom `nu` and rate matrix `rate`. The 

113 univariate case (``k = 1``) is the Gamma special case; the relationship to 

114 the inverse-gamma prior on the variance is ``alpha = nu / 2``, 

115 ``beta = rate / 2``. The prior mean of the precision is ``nu * rate^-1``. 

116 Each marginal error variance (diagonal of the inverse) is inverse-gamma 

117 with ``alpha = inv_wishart_marginal_nu / 2``, ``beta = rate_ii / 2``. 

118 

119 Set `nu` and `rate` to `None` to represent a precision held fixed at `value` 

120 with no prior (e.g. the identity in binary regression). 

121 """ 

122 

123 nu: Float32[Array, ''] | None 

124 """Degrees of freedom of the Wishart prior, or `None` if there is no prior.""" 

125 

126 rate: Float32[Array, ''] | Float32[Array, 'k k'] | None 

127 """The rate matrix of the Wishart prior (scalar for univariate), or `None` 

128 if there is no prior. Equal to the inverse-gamma ``scale`` in the 

129 univariate case.""" 

130 

131 value: Float32[Array, '*chains k k'] | Float32[Array, '*chains'] = field( 

132 chains=CHAIN_AXIS 

133 ) 

134 """The precision matrix (scalar for univariate).""" 

135 

136 def __init__( 

137 self, 

138 nu: FloatLike | None, 

139 rate: FloatLike | Float[ArrayLike, 'k k'] | None, 

140 value: FloatLike 

141 | Float[ArrayLike, '*chains k k'] 

142 | Float[ArrayLike, '*chains'], 

143 ) -> None: 

144 # `init` passes a deferred `_LazyArray` (cast to `Array`) for `value` to 

145 # route it through sharding. 

146 assert (nu is None) == (rate is None), 'set both or neither of nu and rate' 

147 self.nu = None if nu is None else jnp.asarray(nu, jnp.float32) 

148 self.rate = None if rate is None else jnp.asarray(rate, jnp.float32) 

149 if isinstance(value, _LazyArray): 

150 self.value = cast(Array, value) 

151 else: 

152 self.value = jnp.asarray(value, jnp.float32) 

153 

154 @classmethod 

155 def from_inv_wishart_marginal_nu( 

156 cls, 

157 marginal_nu: FloatLike, 

158 rate: FloatLike | Float[ArrayLike, 'k k'], 

159 value: FloatLike 

160 | Float[ArrayLike, '*chains k k'] 

161 | Float[ArrayLike, '*chains'], 

162 ) -> 'Wishart': 

163 """Build the prior from the degrees of freedom of each marginal variance. 

164 

165 Sets ``nu = marginal_nu + k - 1``, the inverse of 

166 `inv_wishart_marginal_nu`. 

167 """ 

168 if jnp.ndim(rate) == 0: 

169 nu = marginal_nu 

170 else: 

171 k, _ = jnp.shape(rate) 

172 nu = marginal_nu + (k - 1) 

173 return cls(nu=nu, rate=rate, value=value) 

174 

175 @property 

176 def inv_wishart_marginal_nu(self) -> Float32[Array, ''] | None: 

177 """Degrees of freedom of the inverse-gamma marginal of each variance. 

178 

179 Equal to ``nu - k + 1``, or `None` if there is no prior. 

180 """ 

181 if self.nu is None: 

182 return None 

183 else: 

184 assert self.rate is not None 

185 if self.rate.ndim == 0: 

186 return self.nu 

187 else: 

188 k, _ = self.rate.shape 

189 return self.nu - (k - 1) 

190 

191 

192@serializable 

193class DiagWishart(Wishart): 

194 """A diagonal precision matrix with independent chi-square diagonal entries. 

195 

196 Despite the name this is not a Wishart restricted to diagonal matrices, but 

197 a convenience type: a diagonal precision whose entries are mutually 

198 independent, each with its own Gamma (scaled chi-square) prior. Only the 

199 multivariate (matrix) case is supported. 

200 

201 With the same `nu` and `rate`, each component's variance has the same prior 

202 as the corresponding marginal variance under the dense `Wishart`: the gamma 

203 shape of each precision entry is ``inv_wishart_marginal_nu / 2``, not 

204 ``nu / 2``. 

205 

206 Used for mixed binary-continuous regression and for continuous multivariate 

207 regression with per-datapoint missingness. 

208 """ 

209 

210 def __init__( 

211 self, 

212 nu: FloatLike | None, 

213 rate: FloatLike | Float[ArrayLike, 'k k'] | None, 

214 value: FloatLike 

215 | Float[ArrayLike, '*chains k k'] 

216 | Float[ArrayLike, '*chains'], 

217 ) -> None: 

218 # explicit (delegating) init so the static checker uses this signature 

219 # instead of synthesizing a stricter one from the inherited fields 

220 assert rate is None or jnp.ndim(rate) == 2, ( 

221 'DiagWishart supports only the multivariate (matrix) case' 

222 ) 

223 super().__init__(nu, rate, value) 

224 

225 

226@serializable 

227class Sparsity(Module): 

228 """The parameters of the prior probability of the variables to split along.""" 

229 

230 log_s: Float32[Array, '*chains p'] | None = field(chains=CHAIN_AXIS) 

231 """The logarithm of the prior probability for choosing a variable to split 

232 along in a decision rule. Not normalized. Variables that do not have any 

233 available decision rule at a given node are masked away. If `None`, use a 

234 uniform distribution. Without `theta`, it is constant and shared by the 

235 chains, see `has_chains`.""" 

236 

237 theta: Float32[Array, '*chains'] | None = field(chains=CHAIN_AXIS) 

238 """The concentration parameter for the Dirichlet prior on the variable 

239 distribution `s`. If not set, `log_s` is left constant.""" 

240 

241 a: Float32[Array, ''] | None 

242 """First shape parameter of the prior on `theta`. If not set, `theta` is 

243 left constant.""" 

244 

245 b: Float32[Array, ''] | None 

246 """Second shape parameter of the prior on `theta`. If not set, `theta` is 

247 left constant.""" 

248 

249 rho: Float32[Array, ''] | None 

250 """Scale parameter of the prior on `theta`. If not set, `theta` is left constant.""" 

251 

252 log_theta_range: Float32[Array, ''] | None 

253 """The domain of `theta` is ``|log(theta / rho)| <= log_theta_range``. 

254 `None` if `theta` is constant.""" 

255 

256 @property 

257 def has_chains(self) -> bool: 

258 """Whether `log_s` and `theta` carry a chain axis. 

259 

260 Only if `theta` is set and has a chain axis: otherwise `log_s` is 

261 constant and shared by the chains. 

262 """ 

263 return self.theta is not None and self.theta.ndim > 0 

264 

265 

266@serializable 

267class Forest(Module): 

268 """Represents the MCMC state of a sum of trees.""" 

269 

270 # Implementation note related to runtime type checking: Heap-array fields 

271 # follow the `bartz.grove.TreesTrace` convention: the union-free integer 

272 # trees are declared before `leaf_tree` and carry the bindable 

273 # `max_num_leaves` axis, while `p_nonterminal` is checked against 

274 # `2*max_num_leaves`. Declaring a union-free `*chains` 

275 # field first binds the variadic chain axis (plus `num_trees` and 

276 # `max_num_leaves`) before `leaf_tree`'s `... | ... k ...` union is 

277 # evaluated, so the runtime typechecker can't mis-bind `*chains` against 

278 # the `k` axis of a multivariate forest (the layouts are otherwise 

279 # rank-ambiguous). No dummy anchor field needed. 

280 

281 var_tree: UInt[Array, '*chains num_trees max_num_leaves'] = field(chains=CHAIN_AXIS) 

282 """Variables/predictors/axes of decision rules.""" 

283 

284 split_tree: UInt[Array, '*chains num_trees max_num_leaves'] = field( 

285 chains=CHAIN_AXIS 

286 ) 

287 """Cutpoints/boundaries of decision rules.""" 

288 

289 affluence_tree: Bool[Array, '*chains num_trees max_num_leaves'] = field( 

290 chains=CHAIN_AXIS 

291 ) 

292 """Marks leaves that can be grown.""" 

293 

294 leaf_tree: ( 

295 Float[Array, '*chains num_trees max_num_leaves'] 

296 | Float[Array, '*chains num_trees k max_num_leaves'] 

297 ) = field(chains=CHAIN_AXIS) 

298 """The leaf values, in units of `leaf_unit`, laid out as in 

299 `bartz.grove.TreeHeaps`. The function computed by the forest is 

300 ``offset + leaf_unit * (sum of leaves)``.""" 

301 

302 leaf_unit: Float32[Array, ''] | Float32[Array, ' k'] 

303 """The storage unit of the leaves. Keeps the stored values O(1) whatever 

304 the data units, so they do not under/overflow narrow `leaf_tree` dtypes. 

305 Set to the marginal prior standard deviation of a leaf with all the trees 

306 in use, rounded to a power of two so converting to and from data units is 

307 exact.""" 

308 

309 offset: Float32[Array, ''] | Float32[Array, ' k'] 

310 """Constant shift added to the scaled sum of trees, see `leaf_tree`.""" 

311 

312 used_trees: Int32[Array, '*chains'] | None = field(chains=CHAIN_AXIS) 

313 """The number of trees in use, `None` if all the trees are always in use. 

314 Only the first `used_trees` trees in the arrays are part of the model; 

315 `step` skips the others in the sequential accept/reject loop and, on gpu or 

316 with few trees in use, in the update of `leaf_indices`. The other trees 

317 shall be lone roots with zero leaves, as `step` keeps them, such that the 

318 function computed by the forest is the sum of all the trees anyway.""" 

319 

320 grow_prop_count: Int32[Array, '*chains'] = field(chains=CHAIN_AXIS) 

321 """The number of grow proposals made during the last MCMC step.""" 

322 

323 prune_prop_count: Int32[Array, '*chains'] = field(chains=CHAIN_AXIS) 

324 """The number of prune proposals made during the last MCMC step.""" 

325 

326 grow_acc_count: Int32[Array, '*chains'] = field(chains=CHAIN_AXIS) 

327 """The number of grow moves accepted during the last MCMC step.""" 

328 

329 prune_acc_count: Int32[Array, '*chains'] = field(chains=CHAIN_AXIS) 

330 """The number of prune moves accepted during the last MCMC step.""" 

331 

332 max_split: UInt[Array, ' p'] 

333 """The maximum split index for each predictor. The predictors with 0 are 

334 ignored, as if they did not exist.""" 

335 

336 blocked_vars: UInt[Array, ' q'] | None 

337 """The indices of the predictors with ``max_split == 0``, padded with 

338 values >= p, or `None` if there are none. Redundant with `max_split`, it 

339 speeds up proposing moves.""" 

340 

341 p_nonterminal: Float32[Array, ' 2*max_num_leaves'] 

342 """The prior probability of each node being nonterminal (conditional on its 

343 ancestors leaving at least one available decision rule). Includes the nodes 

344 at maximum depth which shall be set to 0.""" 

345 

346 p_propose_grow: Float32[Array, ' max_num_leaves'] 

347 """The unnormalized probability of picking a leaf for a grow proposal.""" 

348 

349 leaf_indices: UInt[Array, '*chains num_trees n'] = field(chains=CHAIN_AXIS, data=-1) 

350 """The index in `leaf_tree` of the leaf each datapoint falls into, for 

351 each tree, in the largest version of the tree compatible with the last 

352 moves. 

353 

354 A pending prune (accepted prune or rejected grow, marked per-tree by 

355 `to_prune`) is not yet applied to the indices; `step` folds it in at the 

356 beginning of the next iteration. Evaluating the trees at these indices is 

357 correct anyway because `leaf_tree` mirrors the value of a pruned node onto 

358 its dangling right child, while the left one shares its index.""" 

359 

360 to_prune: Bool[Array, '*chains num_trees'] = field(chains=CHAIN_AXIS) 

361 """Whether the last move on each tree ended in a prune (accepted prune or 

362 rejected grow) whose application to `leaf_indices` is still pending.""" 

363 

364 move_node: Int32[Array, '*chains num_trees'] = field(chains=CHAIN_AXIS) 

365 """The node the last move on each tree operated on (the leaf to grow or 

366 the node to prune). Meaningful only where `to_prune` is set.""" 

367 

368 tree_life: Int32[Array, '*chains num_trees'] = field(chains=CHAIN_AXIS) 

369 """The number of MCMC steps since each tree was last pruned to a lone root, 

370 or since the start.""" 

371 

372 count_tree: UInt32[Array, '*chains num_trees max_num_leaves'] | None = field( 

373 chains=CHAIN_AXIS 

374 ) 

375 """The number of datapoints at each index in `leaf_indices`, so in the same 

376 version of each tree: with a pending prune, the children are still counted 

377 apart. `None` if there are per-datapoint error scales and no 

378 minimum-points-per-node constraints, which makes the counts unused.""" 

379 

380 prec_tree: ( 

381 Float32[Array, '*chains num_trees max_num_leaves'] 

382 | Float32[Array, '*chains num_trees k k max_num_leaves'] 

383 | None 

384 ) = field(chains=CHAIN_AXIS) 

385 """The sum of `State.prec_scale` over the datapoints at each index in 

386 `leaf_indices`, in the same units. `None` if there are no per-datapoint 

387 error scales, in which case `count_tree` takes its place.""" 

388 

389 min_points_per_decision_node: Int32[Array, ''] | None 

390 """The minimum number of data points in a decision node.""" 

391 

392 min_points_per_leaf: Int32[Array, ''] | None 

393 """The minimum number of data points in a leaf node.""" 

394 

395 log_trans_prior: Float32[Array, '*chains num_trees'] | None = field( 

396 chains=CHAIN_AXIS 

397 ) 

398 """The log transition and prior Metropolis-Hastings ratio for the proposed 

399 move on each tree. Arbitrary for a tree without an allowed move, like those 

400 not in use.""" 

401 

402 log_likelihood: Float32[Array, '*chains num_trees'] | None = field( 

403 chains=CHAIN_AXIS 

404 ) 

405 """The log likelihood ratio, dirty like `log_trans_prior`.""" 

406 

407 sum_trees_prior_cov_inv: Wishart 

408 """The prior precision matrix of the sum of trees (a scalar inverse 

409 variance for univariate), with its Wishart prior. Conditional on the tree 

410 structures, the leaves of the trees in use have zero mean and precision 

411 ``used_trees * sum_trees_prior_cov_inv.value`` (``num_trees`` if 

412 `used_trees` is not set), such that the prior covariance of the sum of 

413 trees does not depend on the number of trees. If `Wishart.nu` is `None`, 

414 the precision is held fixed.""" 

415 

416 sparsity: Sparsity 

417 """The parameters of the prior probability of the variables to split 

418 along.""" 

419 

420 @property 

421 def has_chains(self) -> bool: 

422 """Whether non-constant attributes in the forest carry an explicit chain axis.""" 

423 return self.var_tree.ndim > 2 

424 

425 

426@serializable 

427class StepConfig(Module): 

428 """Options for the MCMC step.""" 

429 

430 steps_done: Int32[Array, ''] 

431 """The number of MCMC steps completed so far.""" 

432 

433 sparse_on_at: Int32[Array, ''] | None 

434 """After how many steps to turn on variable selection. If `None`, variable 

435 selection is disabled.""" 

436 

437 resid_reduction_config: ReductionConfig 

438 """How to sum the residuals in each leaf.""" 

439 

440 count_reduction_config: ReductionConfig 

441 """How to count the datapoints in each leaf.""" 

442 

443 prec_reduction_config: ReductionConfig 

444 """How to sum the likelihood precisions in each leaf.""" 

445 

446 prec_count_num_trees: int | None = field(static=True) 

447 """Batch size for processing trees to compute count and prec trees, see `init`.""" 

448 

449 one_bin_prec_reduction: bool = field(static=True) 

450 """Whether to sum the precisions in only one child of a grown node and 

451 derive the other by difference. Ignored (always off) if there's no 

452 constraint on the number of points per leaf 

453 (`Forest.min_points_per_decision_node` and `Forest.min_points_per_leaf` are 

454 `None`).""" 

455 

456 sequential_unroll: int | bool = field(static=True) 

457 """How much to unroll the sequential accept/reject loop over trees in 

458 `step`, if `Forest.used_trees` is not set. See the ``unroll`` argument of 

459 `jax.lax.scan`.""" 

460 

461 sequential_block_size: int | None = field(static=True) 

462 """If `Forest.used_trees` is set, the sequential accept/reject loop over 

463 trees in `step` visits them in fully unrolled blocks of this size, and 

464 checks whether there are trees in use left only between blocks. The visits 

465 to the trees not in use in the last block have no effect. If `None`, 2 on 

466 cpu and 4 on gpu.""" 

467 

468 parallel_block_size: int | None = field(static=True) 

469 """If `Forest.used_trees` is set, the update of `Forest.leaf_indices` and 

470 related caches in `step`, which is parallel across trees, processes the 

471 trees in blocks of this size, a divisor of the number of trees, stopping 

472 after the trees in use. If `None`, the size is set based on the number of 

473 datapoints, and on cpu all the trees are processed at once instead unless 

474 few are in use.""" 

475 

476 random_tree_scan: bool = field(static=True) 

477 """Whether the sequential accept/reject loop over trees in `step` visits 

478 the trees in a new random order at each step, instead of in storage 

479 order.""" 

480 

481 augment: bool = field(static=True) 

482 """Whether to account exactly, via data augmentation, for the decision 

483 rules forbidden by the ancestors of each node when updating 

484 `Sparsity.log_s`.""" 

485 

486 mesh: Mesh | None = field(static=True) 

487 """The mesh used to shard data and computation across multiple devices.""" 

488 

489 leaf_quantization: Int32[Array, ''] | None = None 

490 """If set, quantize the leaves to multiples of ``eps(resid dtype) * 2 ** 

491 leaf_quantization`` in `State.resid_eff_scale` units, which makes the 

492 running updates of `State.resid` mostly exact, (almost) stopping their 

493 random-walk rounding drift, assuming ``|resid| < 2 ** (leaf_quantization + 

494 1)`` holds (in the same units) for most datapoints most of the time. 

495 Intended mostly for use with float16 residuals. Sensible settings are 0 and 

496 1, with 0 leaving some drift, 1 practically no drift, and no setting above 

497 1 justifying the reduced accuracy. With enough datapoints or trees the 

498 MCMC breaks down because the sampled leaf variation becomes smaller than 

499 the quantum, so this setting can not be used liberally.""" 

500 

501 @property 

502 def data_sharded(self) -> bool: 

503 """Whether the data axis is sharded across devices.""" 

504 return self.mesh is not None and 'data' in self.mesh.axis_names 

505 

506 

507@serializable 

508class State(Module): 

509 """Represents the MCMC state of BART.""" 

510 

511 _chain_anchor: Float32[Array, '*chains'] = field(chains=CHAIN_AXIS) 

512 """Unused per-chain scalar, declared first as a runtime-typechecker anchor. 

513 Its single (union-free) ``*chains`` annotation binds the variadic chain 

514 axis before the ``... | ... k ...`` unions of `z`/`resid` (z over the 

515 binary-outcome ``kb`` axis) are checked; otherwise those can mis-bind 

516 ``*chains`` against the outcome axis for a multivariate-without-chains 

517 state (the layouts are rank-ambiguous). Unlike `Forest`, `State` has no 

518 genuine union-free chain field to reorder into this slot, so a dummy one is 

519 carried.""" 

520 

521 X: UInt[Array, 'p n'] = field(data=-1) 

522 """The predictors.""" 

523 

524 y: Float32[Array, ' n'] | Float32[Array, 'k n'] = field(data=-1) 

525 """The response, in data units. Binary components are stored as 0/1. 

526 Missing values are replaced by `Forest.offset`.""" 

527 

528 z: None | Float32[Array, '*chains n'] | Float32[Array, '*chains kb n'] = field( 

529 chains=CHAIN_AXIS, data=-1 

530 ) 

531 """The latent outcomes for binary regression. `None` in continuous 

532 regression. In the mixed binary-continuous case, only the binary outcome 

533 components are stored.""" 

534 

535 binary_indices: None | Int32[Array, ' kb'] 

536 """The indices of binary outcome components in the full list of outcome 

537 components. `None` when there are no binary components.""" 

538 

539 resid: Float[Array, '*chains n'] | Float[Array, '*chains k n'] = field( 

540 chains=CHAIN_AXIS, data=-1 

541 ) 

542 """The residuals, ``resid_unit * resid = (y or z) - sum of trees``.""" 

543 

544 resid_unit: Float32[Array, ''] | Float32[Array, ' k'] 

545 """The storage unit of `resid` (see `init`'s ``resid_dtype``), same scheme 

546 as `Forest.leaf_unit`. Set to the marginal prior standard deviation of the 

547 sum of trees, rounded to a power of two.""" 

548 

549 resid_eff_scale: Float32[Array, '*chains'] | Float32[Array, '*chains k'] = field( 

550 chains=CHAIN_AXIS 

551 ) 

552 """The measured scale of the residuals (their precision-weighted root mean 

553 square in data units), rounded to a power of two. Sets the leaf 

554 quantization grid (see `StepConfig.leaf_quantization`). Initialized to 

555 `resid_unit`, then tracks the MCMC (while the storage unit of `resid` stays 

556 fixed at `resid_unit`). Not updated in purely binary regression, where the 

557 scale of the latent residuals should be stable.""" 

558 

559 resid_inexact_integral: Float32[Array, '*chains'] | Float32[Array, '*chains k'] = ( 

560 field(chains=CHAIN_AXIS) 

561 ) 

562 """Sum over the MCMC steps done of the mean square of the residuals (in 

563 `resid_unit` units) large enough that their running updates round, times 

564 the fraction of trees in use. Used by `sum_trees_eps` to estimate the 

565 accumulated rounding drift.""" 

566 

567 error_cov_inv: Wishart 

568 """The inverse error covariance (``error_cov_inv.value``, scalar for 

569 univariate) with its Wishart prior. Fixed at the identity with no prior in 

570 binary regression.""" 

571 

572 error_scale: Float32[Array, ' n'] | Float32[Array, 'k n'] | None = field(data=-1) 

573 """The per-datapoint error scales (the ``error_scale`` argument of `init`). 

574 The error precision on a datapoint is ``error_cov_inv.value / 

575 outer(error_scale, error_scale)``. For binary components the (fixed, unit) 

576 probit latent error is scaled instead, so the success probability is 

577 ``Phi(sum of trees / error_scale)``. `inv_sdev_scale` and `prec_scale` are 

578 derived from this and the missingness mask.""" 

579 

580 prec_scale: Float[Array, ' n'] | Float[Array, 'k k n'] | None = field(data=-1) 

581 """The scale on the error precision, ``prec_scale = outer(inv_sdev_scale, 

582 inv_sdev_scale)`` per datapoint (``inv_sdev_scale ** 2`` for scalar 

583 scales), so it's in units of ``inv_sdev_unit ** 2``. Stored, like 

584 `inv_sdev_scale`, in `init`'s ``prec_scale_dtype``.""" 

585 

586 inv_sdev_scale: Float[Array, ' n'] | Float[Array, 'k n'] | None = field(data=-1) 

587 """``inv_sdev_scale * inv_sdev_unit = 1 / error_scale``, zeroed at missing 

588 datapoints. Not `None` when ``missing`` is set even if fit without error 

589 scales.""" 

590 

591 inv_sdev_unit: Float32[Array, ''] | Float32[Array, ' k'] 

592 """The storage unit of `inv_sdev_scale`, to avoid under/overflow with short 

593 dtypes; same scheme as `Forest.leaf_unit`. Set to the root mean square of 

594 ``1 / error_scale`` over non-missing datapoints, rounded to a power of two; 

595 1 if fit without error scales. Constant along the MCMC.""" 

596 

597 n_non_missing: Int32[Array, ''] | Int32[Array, ' k'] 

598 """The number of non-missing datapoints.""" 

599 

600 sum_diag_prec_scale: Float32[Array, ''] | Float32[Array, ' k'] 

601 """``sum(1 / error_scale ** 2)`` over non-missing datapoints; equal to 

602 `n_non_missing` if fit without error scales.""" 

603 

604 forest: Forest 

605 """The sum of trees model.""" 

606 

607 config: StepConfig 

608 """Metadata and configurations for the MCMC step.""" 

609 

610 @property 

611 def has_chains(self) -> bool: 

612 """Whether non-constant attributes in the state carry an explicit chain axis.""" 

613 return self.forest.has_chains 

614 

615 def num_chains(self) -> int | None: 

616 """Return the number of chains, or `None` if not multichain.""" 

617 if not self.has_chains: 

618 return None 

619 c = chain_vmap_axes(self.forest).var_tree 

620 return self.forest.var_tree.shape[c] 

621 

622 @jit 

623 def sum_trees_eps(self) -> Float32[Array, ''] | Float32[Array, ' k']: 

624 """Estimate the absolute accuracy limit of the sum of trees (in data units). 

625 

626 The analogue of ``finfo(dtype).eps`` for the sum of trees. This combines three 

627 terms: floating point resolution, random walk accumulation of numerical error 

628 on running residuals, and if leaf quantization is active, breakdown of the 

629 mcmc due to the quantization being too coarse. The latter term is currently 

630 broken actually, sorry about that. 

631 """ 

632 resolution, drift, snap = self._sum_trees_eps() 

633 return jnp.maximum(jnp.maximum(resolution, drift), snap) 

634 

635 def _sum_trees_eps( 

636 self, 

637 ) -> tuple[ 

638 Float32[Array, ''] | Float32[Array, ' k'], 

639 Float32[Array, ''] | Float32[Array, ' k'], 

640 Float32[Array, ''] | Float32[Array, ' k'], 

641 ]: 

642 """Return the resolution, drift, and snap terms of `sum_trees_eps` separately.""" 

643 eps_leaf = jnp.finfo(self.forest.leaf_tree.dtype).eps 

644 eps_resid = jnp.finfo(self.resid.dtype).eps 

645 

646 # the trees in use, on average over the chains and in total 

647 split_tree = self.forest.split_tree 

648 *chains, num_trees, _ = split_tree.shape 

649 used_trees = jnp.mean(num_used_trees(self.forest)) 

650 num_used = used_trees * math.prod(chains) 

651 

652 # the prior standard deviation of a leaf; `resid_unit` is the one of 

653 # the sum of trees (up to rounding) 

654 leaf_sdev = self.resid_unit * lax.rsqrt(jnp.maximum(used_trees, 1.0)) 

655 

656 # rounding of the stored leaves at their typical magnitude 

657 dtype_quantum = eps_leaf * leaf_sdev 

658 

659 if self.config.leaf_quantization is None: 

660 resolution = dtype_quantum 

661 # float leaf storage rounds relative to the leaf magnitude, so 

662 # leaves near zero keep a fine grid and sampling is not pinned 

663 snap = jnp.zeros_like(dtype_quantum) 

664 else: 

665 # quantized leaves all sit on one grid closed under addition (the 

666 # scales are powers of two, so leaf storage rounds within the 

667 # grid even where its spacing is coarser), so the sum resolves 

668 # multiples of the quantum whatever the number of trees 

669 q = self.config.leaf_quantization 

670 scale_chain_axes = range(self.resid_eff_scale.ndim - self.resid_unit.ndim) 

671 eff_scale = jnp.mean(self.resid_eff_scale, axis=tuple(scale_chain_axes)) 

672 managed_quantum = eps_resid * eff_scale * 2.0**q 

673 resolution = jnp.maximum(managed_quantum, dtype_quantum) 

674 

675 # determine average error precision; the folded `inv_sdev_unit` 

676 # puts the stored `prec_scale` mean in data units 

677 prec = scaled_error_cov_inv(self) 

678 n_eff = jnp.maximum(self.n_non_missing, 1) 

679 if self.prec_scale is not None: 

680 prec *= self.prec_scale.sum(axis=-1, dtype=jnp.float32) / n_eff 

681 

682 # convert precision to variance and average it over chains 

683 if self.resid_unit.ndim: 

684 error_var = jnp.diagonal( 

685 inv_via_chol_with_gersh(prec), axis1=-2, axis2=-1 

686 ) 

687 else: 

688 error_var = jnp.reciprocal(prec) 

689 var_chain_axes = range(error_var.ndim - self.resid_unit.ndim) 

690 error_var = jnp.mean(error_var, axis=tuple(var_chain_axes)) 

691 

692 # a quantized leaf moves only when its full conditional mean 

693 # crosses half a quantum; the mean responds to the leaf's average 

694 # residual through the posterior shrinkage factor s = t / (1 + t), 

695 # t = (leaf_sdev / error_sdev)^2 * n_leaf, so residual features 

696 # smaller than quantum / (2 s) cannot move the sampler. Typical 

697 # values are used for the error variance (chain mean, datapoint 

698 # mean of prec_scale) and n_leaf (datapoints over leaves per tree 

699 # in use; the trees not in use have no splits). 

700 num_splits = jnp.count_nonzero(split_tree) 

701 leaves_per_tree = 1.0 + num_splits / jnp.maximum(num_used, 1) 

702 n_leaf = n_eff / leaves_per_tree 

703 t = jnp.square(leaf_sdev) * n_leaf / error_var 

704 snap = managed_quantum / 2.0 * (1.0 + jnp.reciprocal(t)) 

705 

706 # random walk drift of the accumulated rounding errors: each of the 

707 # `used_trees` updates per step charges eps_resid * |resid| to the 

708 # residuals large enough to round, whose mean square, times 

709 # `used_trees / num_trees`, is integrated over the steps done in 

710 # `resid_inexact_integral` 

711 integral = self.resid_inexact_integral 

712 chain_axes = range(integral.ndim - self.resid_unit.ndim) 

713 integral = jnp.mean(integral, axis=tuple(chain_axes)) 

714 drift = eps_resid * self.resid_unit * jnp.sqrt(num_trees * integral) 

715 

716 return resolution, drift, snap 

717 

718 

719def check_diagonal(rate: Float32[Array, 'k k']) -> Float32[Array, 'k k']: 

720 """Raise if the Wishart `rate` is not diagonal.""" 

721 diag = jnp.diag(jnp.diag(rate)) 

722 return error_if(rate, jnp.any(rate != diag), 'error_cov_inv.rate must be diagonal') 

723 

724 

725def check_binary_unit_precision( 

726 value: Float32[Array, 'k k'], binary_mask: Sequence[bool] 

727) -> Float32[Array, 'k k']: 

728 """Raise if the binary diagonal entries of `value` are not fixed at 1.""" 

729 binary = jnp.array(binary_mask) 

730 off_unit = jnp.any(binary & (jnp.diag(value) != 1.0)) 

731 return error_if( 

732 value, 

733 off_unit, 

734 'binary error precision must be 1 (the default for a zero rate)', 

735 ) 

736 

737 

738def init_shape_shifting_parameters( 

739 *, 

740 y: Float32[Array, ' n'] | Float32[Array, 'k n'], 

741 outcome_type: OutcomeType | list[OutcomeType], 

742 offset: Float32[Array, ''] | Float32[Array, ' k'], 

743 error_scale: Float32[ArrayLike, ' n'] | Float32[ArrayLike, 'k n'] | None, 

744 error_cov_inv: Wishart | None, 

745 sum_trees_prior_cov_inv: Wishart, 

746 missing: Bool[ArrayLike, ' n'] | Bool[ArrayLike, 'k n'] | None, 

747) -> tuple[bool, tuple[int, ...], Wishart, None | Int32[Array, ' kb']]: 

748 """ 

749 Check and initialize parameters that change array type/shape based on outcome kind. 

750 

751 Parameters 

752 ---------- 

753 y 

754 The response variable (used only for shape checks). 

755 outcome_type 

756 Whether the regression is continuous or binary. Can be a list of 

757 `OutcomeType` for per-component specification in the multivariate case. 

758 offset 

759 The offset to add to the predictions. 

760 error_scale 

761 Per-datapoint error scales, ``(n,)`` or ``(k, n)`` (used only for 

762 shape checks). 

763 error_cov_inv 

764 The Wishart prior on the error precision and its initial value, or 

765 `None` for binary regression. The mixed and partial-missing diagonal 

766 modes require a `DiagWishart`; in the mixed case the binary components 

767 must have an initial precision of 1. 

768 sum_trees_prior_cov_inv 

769 The Wishart prior on the precision of the sum of trees and its initial 

770 value (used only for shape and type checks). 

771 missing 

772 The per-datapoint missingness mask, used to detect partial missingness 

773 (2-D mask) so that diagonal-mode initialization is selected. 

774 

775 Returns 

776 ------- 

777 is_binary 

778 Whether all outcomes are binary. 

779 kshape 

780 The outcome shape, empty for univariate, (k,) for multivariate. 

781 error_cov_inv 

782 The Wishart prior with its initial value resolved for the outcome kind. 

783 binary_indices 

784 The indices of binary outcome components, or `None` if there are none. 

785 """ 

786 kshape = offset.shape 

787 

788 # determine per-component outcome kinds 

789 if isinstance(outcome_type, list): 

790 assert kshape, 'per-component outcome_type requires multivariate y' 

791 (k,) = kshape 

792 assert len(outcome_type) == k 

793 binary_mask = [t is OutcomeType.binary for t in outcome_type] 

794 is_binary = all(binary_mask) 

795 is_mixed = any(binary_mask) and not is_binary 

796 else: 

797 is_binary = outcome_type is OutcomeType.binary 

798 is_mixed = False 

799 

800 if is_mixed: 

801 binary_indices = jnp.array([i for i, b in enumerate(binary_mask) if b]) 

802 else: 

803 binary_indices = None 

804 

805 partial_missing = missing is not None and missing.ndim == 2 and kshape 

806 

807 assert ( 

808 error_scale is None 

809 or error_scale.shape == y.shape # (k, n) 

810 or error_scale.shape == y.shape[-1:] # (n,) 

811 ) 

812 

813 # All-binary: no prior, the precision is fixed at the identity. 

814 if is_binary: 

815 assert error_cov_inv is None, 'no error covariance prior in binary regression' 

816 value = jnp.eye(kshape[0]) if kshape else jnp.array(1.0) 

817 error_cov_inv = Wishart(nu=None, rate=None, value=value) 

818 

819 # Mixed binary-continuous, or continuous-mv with 2-D missingness: diagonal 

820 # error covariance, updated component-wise. The caller must supply a 

821 # `DiagWishart`; in the mixed case the binary components must have unit 

822 # initial precision (see `DiagWishart`). 

823 elif is_mixed or partial_missing: 

824 assert isinstance(error_cov_inv, DiagWishart), ( 

825 'mixed binary-continuous or partial-missing regression requires a ' 

826 'DiagWishart error_cov_inv prior' 

827 ) 

828 assert error_cov_inv.rate is not None 

829 assert error_cov_inv.rate.shape == 2 * kshape 

830 assert error_cov_inv.value.shape == 2 * kshape 

831 rate = check_diagonal(error_cov_inv.rate) 

832 value = check_diagonal(error_cov_inv.value) 

833 if is_mixed: 

834 value = check_binary_unit_precision(value, binary_mask) 

835 error_cov_inv = replace(error_cov_inv, rate=rate, value=value) 

836 

837 # All-continuous: a dense `Wishart`. 

838 else: 

839 assert error_cov_inv is not None 

840 assert type(error_cov_inv) is Wishart, ( 

841 'continuous regression requires a dense Wishart error_cov_inv prior' 

842 ) 

843 rate = error_cov_inv.rate 

844 if rate is None: 

845 warn( 

846 '`error_cov_inv` has no prior, so the error precision is held ' 

847 'fixed at its initial value' 

848 ) 

849 else: 

850 assert rate.shape == 2 * kshape 

851 assert error_cov_inv.value.shape == 2 * kshape 

852 

853 assert y.shape[:-1] == kshape 

854 

855 assert type(sum_trees_prior_cov_inv) is Wishart, ( 

856 'sum_trees_prior_cov_inv must be a dense Wishart' 

857 ) 

858 assert sum_trees_prior_cov_inv.value.shape == 2 * kshape 

859 if sum_trees_prior_cov_inv.rate is not None: 

860 assert sum_trees_prior_cov_inv.rate.shape == 2 * kshape 

861 

862 return is_binary, kshape, error_cov_inv, binary_indices 

863 

864 

865def check_splitless_vars( 

866 filter_splitless_vars: int, 

867 max_split: UInt[Array, ' p'], 

868 offset: Float32[Array, ''] | Float32[Array, ' k'], 

869) -> Float32[Array, ''] | Float32[Array, ' k']: 

870 """Check there aren't too many deactivated predictors.""" 

871 msg = ( 

872 f'there are more than {filter_splitless_vars=} predictors with no splits, ' 

873 'please increase `filter_splitless_vars` or investigate the missing splits' 

874 ) 

875 return error_if(offset, jnp.sum(max_split == 0) > filter_splitless_vars, msg) 

876 

877 

878def parse_outcome_type( 

879 outcome_type: 'OutcomeType | str | Sequence[OutcomeType | str]', 

880) -> 'OutcomeType | list[OutcomeType]': 

881 """Normalize outcome_type to enum (or list of enums).""" 

882 if isinstance(outcome_type, Sequence) and not isinstance(outcome_type, str): 

883 return [OutcomeType(t) for t in outcome_type] 

884 else: 

885 return OutcomeType(outcome_type) 

886 

887 

888def parse_p_nonterminal( 

889 p_nonterminal: Float32[ArrayLike, ' d'], 

890) -> Float32[Array, ' d+1']: 

891 """Check it's in (0, 1) and pad with a 0 at the end.""" 

892 p_nonterminal = jnp.asarray(p_nonterminal) 

893 ok = (p_nonterminal > 0) & (p_nonterminal < 1) 

894 p_nonterminal = error_if(p_nonterminal, ~ok, 'p_nonterminal must be in (0, 1)') 

895 return jnp.pad(p_nonterminal, (0, 1)) 

896 

897 

898def parse_used_trees( 

899 used_trees: int | Integer[ArrayLike, ''] | None, num_trees: int 

900) -> Int32[Array, ''] | None: 

901 """Check `used_trees` is in [0, num_trees].""" 

902 if used_trees is None: 

903 return None 

904 else: 

905 used_trees = jnp.asarray(used_trees, jnp.int32) 

906 bad = (used_trees < 0) | (used_trees > num_trees) 

907 return error_if(used_trees, bad, f'used_trees must be in [0, {num_trees}]') 

908 

909 

910def parse_parallel_block_size( 

911 parallel_block_size: int | None, num_trees: int 

912) -> int | None: 

913 """Check `parallel_block_size` is a positive divisor of `num_trees`.""" 

914 if parallel_block_size is not None and ( 

915 parallel_block_size < 1 or num_trees % parallel_block_size 

916 ): 

917 msg = f'{parallel_block_size=} is not a positive divisor of {num_trees=}' 

918 raise ValueError(msg) 

919 else: 

920 return parallel_block_size 

921 

922 

923def parse_sequential_block_size(sequential_block_size: int | None) -> int | None: 

924 """Check `sequential_block_size` is positive.""" 

925 if sequential_block_size is not None and sequential_block_size < 1: 

926 msg = f'{sequential_block_size=} is not positive' 

927 raise ValueError(msg) 

928 else: 

929 return sequential_block_size 

930 

931 

932def check_equal_blocks(num_trees: int) -> None: 

933 """Raise if `num_trees` is not a multiple of `PARALLEL_MIN_BLOCKS`, see `init`.""" 

934 if num_trees % PARALLEL_MIN_BLOCKS: 

935 lower = num_trees - num_trees % PARALLEL_MIN_BLOCKS 

936 upper = lower + PARALLEL_MIN_BLOCKS 

937 nearest = f'{lower} or {upper}' if lower else f'{upper}' 

938 msg = ( 

939 f'{num_trees=} is not a multiple of {PARALLEL_MIN_BLOCKS}, as required ' 

940 f'if `used_trees` is set; use {nearest}, or set `check_num_trees=False`' 

941 ) 

942 raise ValueError(msg) 

943 

944 

945@forbid_x64 

946def make_p_nonterminal( 

947 d: int, alpha: FloatLike = 0.95, beta: FloatLike = 2.0 

948) -> Float32[Array, ' {d}']: 

949 """Prepare the `p_nonterminal` argument to `init`. 

950 

951 It is calculated according to the formula: 

952 

953 P_nt(depth) = alpha / (1 + depth)^beta, with depth 0-based 

954 

955 Parameters 

956 ---------- 

957 d 

958 The maximum depth of the trees (d=0 means tree with only root node) 

959 alpha 

960 The a priori probability of the root node having children, conditional 

961 on it being possible 

962 beta 

963 The exponent of the power decay of the probability of having children 

964 with depth. 

965 

966 Returns 

967 ------- 

968 An array of probabilities, one per tree level but the last. 

969 """ 

970 assert d >= 0 

971 depth = jnp.arange(d) 

972 return alpha / (1 + depth).astype(float) ** beta 

973 

974 

975@forbid_x64 

976@float32_matmuls 

977def init( 

978 *, 

979 X: UInt[ArrayLike, 'p n'], 

980 y: Float32[ArrayLike, ' n'] | Float32[ArrayLike, ' k n'], 

981 outcome_type: OutcomeType | str | Sequence[OutcomeType | str] = 'continuous', 

982 offset: FloatLike | Float[ArrayLike, ' k'], 

983 max_split: UInt[ArrayLike, ' p'], 

984 num_trees: int, 

985 used_trees: int | Integer[ArrayLike, ''] | None = None, 

986 check_num_trees: bool = True, 

987 p_nonterminal: Float32[ArrayLike, ' d'], 

988 sum_trees_prior_cov_inv: Wishart, 

989 leaf_dtype: DTypeLike = jnp.float32, 

990 prec_scale_dtype: DTypeLike = jnp.float32, 

991 resid_dtype: DTypeLike = jnp.float32, 

992 leaf_quantization: int | Integer[ArrayLike, ''] | None = None, 

993 error_cov_inv: Wishart | None = None, 

994 error_scale: Float32[ArrayLike, ' n'] | Float32[ArrayLike, 'k n'] | None = None, 

995 missing: Bool[ArrayLike, ' n'] | Bool[ArrayLike, 'k n'] | None = None, 

996 min_points_per_decision_node: int | Integer[ArrayLike, ''] | None = None, 

997 min_points_per_leaf: int | Integer[ArrayLike, ''] | None = None, 

998 resid_reduction_config: ReductionConfig = AutoBatchedReduction(), 

999 count_reduction_config: ReductionConfig = AutoOneHotOrPopcountReduction(), 

1000 prec_reduction_config: ReductionConfig = AutoOneHotReduction(), 

1001 prec_count_num_trees: int | None | Literal['auto'] = 'auto', 

1002 one_bin_prec_reduction: bool | Literal['auto'] = 'auto', 

1003 sequential_unroll: int | bool = 2, 

1004 sequential_block_size: int | None = None, 

1005 parallel_block_size: int | None = None, 

1006 random_tree_scan: bool = False, 

1007 save_ratios: bool = False, 

1008 filter_splitless_vars: int = 0, 

1009 log_s: Float32[ArrayLike, ' p'] | None = None, 

1010 theta: FloatLike | None = None, 

1011 a: FloatLike | None = None, 

1012 b: FloatLike | None = None, 

1013 rho: FloatLike | None = None, 

1014 sparse_on_at: int | Integer[ArrayLike, ''] | None = None, 

1015 augment: bool = True, 

1016 num_chains: int | None = None, 

1017 mesh: Mesh | dict[str, int] | None = None, 

1018) -> State: 

1019 """ 

1020 Make a BART posterior sampling MCMC initial state. 

1021 

1022 Parameters 

1023 ---------- 

1024 X 

1025 The predictors. Note this is trasposed compared to the usual convention. 

1026 y 

1027 The response. If two-dimensional, the outcome is multivariate with the 

1028 first axis indicating the component. For binary data, non-zero means 1, 

1029 zero means 0. 

1030 outcome_type 

1031 Whether the regression is continuous or binary (probit). Can also be a 

1032 sequence of `OutcomeType` values, one per outcome component, for mixed 

1033 binary-continuous multivariate regression. 

1034 offset 

1035 Constant shift added to the sum of trees. 0 if not specified. 

1036 max_split 

1037 The maximum split index for each variable. All split ranges start at 1. 

1038 The variables with 0 are ignored, as if they did not exist, see 

1039 `filter_splitless_vars`. 

1040 num_trees 

1041 The maximum number of trees. 

1042 used_trees 

1043 The initial number of trees. If not specified, the number of trees is 

1044 fixed at `num_trees`. For best performance, leave this unset when the 

1045 number of trees is fixed. 

1046 check_num_trees 

1047 Whether to raise an error if `used_trees` is specified and `num_trees` 

1048 is not a multiple of 8, such that the trees divide into equal blocks. 

1049 p_nonterminal 

1050 The probability of a nonterminal node at each depth. The maximum depth 

1051 of the trees is the length of this array. Use `make_p_nonterminal` to 

1052 set it with the conventional formula. 

1053 sum_trees_prior_cov_inv 

1054 The Wishart prior on the precision of the sum of trees (a scalar 

1055 inverse variance for univariate) and its initial value; the precision 

1056 of a leaf is the number of trees in use times that, see 

1057 `Forest.sum_trees_prior_cov_inv`. Set `Wishart.nu` and `Wishart.rate` 

1058 to `None` to hold the precision fixed. Must be a dense `Wishart`, not 

1059 a `DiagWishart`. 

1060 leaf_dtype 

1061 prec_scale_dtype 

1062 resid_dtype 

1063 Storage dtypes for, respectively: leaves (`Forest.leaf_tree`), derived 

1064 error scales (`State.prec_scale` and `State.inv_sdev_scale`; the raw 

1065 `State.error_scale` stays float32), and running residuals 

1066 (`State.resid`). These quantities are stored in scaled units so that 

1067 narrow dtypes do not under/overflow (see `Forest.leaf_unit`), though 

1068 float16 error scales may still overflow if their dynamic range is high 

1069 enough. Leaf full conditionals are always computed and sampled in 

1070 float32. Narrow residual dtypes may easily break the MCMC, 

1071 `resid_dtype` is an experimental setting. 

1072 leaf_quantization 

1073 Quantize the leaves to (almost) stop the numerical drift of the running 

1074 residuals, see `StepConfig.leaf_quantization`. 

1075 error_cov_inv 

1076 The prior and initial value of the error term precision matrix (see 

1077 `Wishart`). Leave it unspecified for binary regression. Mixed 

1078 binary-continuous and per-outcome-component missingness require a 

1079 `DiagWishart`. 

1080 error_scale 

1081 Per-datapoint error scales (called ``w`` in the R package BART3); see 

1082 `State.error_scale`. An unspecified `error_scale` is equivalent to 

1083 ``error_scale = 1`` for all datapoints. 

1084 missing 

1085 Boolean mask indicating which datapoints are missing. `True` marks 

1086 entries to be ignored by the MCMC. The masked values of `y` may be 

1087 anything, even non-finite. If `missing` is 2-D, `error_cov_inv` must 

1088 be a `DiagWishart`. 

1089 min_points_per_decision_node 

1090 min_points_per_leaf 

1091 The minimum number of datapoints in a decision node and in a leaf, 

1092 respectively; 0 if not specified. The leaf constraint is not taken into 

1093 account in the proposal distribution because that would be expensive. 

1094 The two are independent and not checked for coherence; it makes sense 

1095 to set ``min_points_per_decision_node >= 2 * min_points_per_leaf``. 

1096 resid_reduction_config 

1097 count_reduction_config 

1098 prec_reduction_config 

1099 How to sum the residuals, count the datapoints, and sum the likelihood 

1100 precisions in each leaf, respectively. See `ReductionConfig` and its 

1101 subclasses. 

1102 prec_count_num_trees 

1103 The number of trees to process at a time on cpu when computing the 

1104 likelihood precision or counting datapoints, except for counts with the 

1105 default popcount reduction, which needs no batching. If `None`, do all 

1106 trees at once, which may use too much memory. If 'auto' (default), it's 

1107 chosen automatically. 

1108 one_bin_prec_reduction 

1109 Whether to turn on the optimization of summing the likelihood 

1110 precisions in only one child of a grown node and deriving the other by 

1111 subtracting it from the parent. The default ``'auto'`` will try to turn 

1112 it on and raise/warn if not possible. 

1113 sequential_unroll 

1114 See `StepConfig.sequential_unroll`. Unrolling may speed up the MCMC at 

1115 the cost of longer compilation; 1 means no unrolling. 

1116 sequential_block_size 

1117 Computational performance parameter. Larger `sequential_block_size` may 

1118 speed up the MCMC on GPU at the cost of longer compilation. See 

1119 `StepConfig.sequential_block_size`. 

1120 parallel_block_size 

1121 Computational performance parameter, a divisor of `num_trees`. See 

1122 `StepConfig.parallel_block_size`. 

1123 random_tree_scan 

1124 If `True`, run the Gibbs scan over trees in random order (different on 

1125 each MCMC iteration) instead of in fixed order. 

1126 save_ratios 

1127 Whether to save the Metropolis-Hastings ratios. 

1128 filter_splitless_vars 

1129 The maximum number of variables without splits that can be ignored. If 

1130 there are more, `init` raises an exception. 

1131 log_s 

1132 theta 

1133 a 

1134 b 

1135 rho 

1136 Sparsity (variable selection) parameters, see `Sparsity.log_s` and 

1137 `Sparsity.theta`. If `rho`, `a`, `b` are set, an unspecified `theta` is 

1138 initialized to `rho`; if `theta` is set, an unspecified `log_s` is 

1139 initialized to uniform. 

1140 sparse_on_at 

1141 After how many MCMC steps to turn on variable selection. 

1142 augment 

1143 See `StepConfig.augment`. If disabled, forbidden decision rules are 

1144 ignored when counting variable usage, which may be faster but is 

1145 an approximation. 

1146 num_chains 

1147 The number of independent MCMC chains. Single chain with scalar values 

1148 if not specified. 

1149 mesh 

1150 A jax mesh used to shard data and computation across multiple devices. 

1151 If it has a 'chains' axis, that axis is used to shard the chains. If it 

1152 has a 'data' axis, that axis is used to shard the datapoints. 

1153 

1154 As a shorthand, if a dictionary mapping axis names to axis size is 

1155 passed, the corresponding mesh is created, e.g., ``dict(chains=4, 

1156 data=2)`` will let jax pick 8 devices to split chains (which must be a 

1157 multiple of 4) across 4 pairs of devices, where in each pair the data 

1158 is split in two. 

1159 

1160 Note: if a mesh is passed, the arrays are always sharded according to 

1161 it. In particular even if the mesh has no 'chains' or 'data' axis, the 

1162 arrays will be replicated on all devices in the mesh. 

1163 

1164 Returns 

1165 ------- 

1166 An initialized BART MCMC state. 

1167 

1168 Raises 

1169 ------ 

1170 ValueError 

1171 If arguments unused in binary regression are set, if `num_trees` fails 

1172 the check enabled by `check_num_trees`, or if a block size is invalid. 

1173 

1174 Notes 

1175 ----- 

1176 In decision nodes, the values in ``X[i, :]`` are compared to a cutpoint out 

1177 of the range ``[1, 2, ..., max_split[i]]``. A point belongs to the left 

1178 child iff ``X[i, j] < cutpoint``. Thus it makes sense for ``X[i, :]`` to be 

1179 integers in the range ``[0, 1, ..., max_split[i]]``. 

1180 

1181 In general the arrays passed to this function as arguments may be donated, 

1182 invalidating them. Create copies before passing them to `init` if this 

1183 happens and you need them again. 

1184 """ 

1185 # convert to array all array-like arguments that are used in other 

1186 # configurations but don't need further processing themselves 

1187 X = jnp.asarray(X) 

1188 y = jnp.asarray(y) 

1189 assert y.dtype == jnp.float32 

1190 offset = jnp.asarray(offset) 

1191 max_split = jnp.asarray(max_split) 

1192 error_scale = asarray_or_none(error_scale) 

1193 missing = asarray_or_none(missing) 

1194 assert missing is None or missing.ndim <= y.ndim 

1195 

1196 # normalize outcome_type to enum (or list of enums) 

1197 outcome_type = parse_outcome_type(outcome_type) 

1198 

1199 # check p_nonterminal and pad it with a 0 at the end (still not final shape) 

1200 p_nonterminal = parse_p_nonterminal(p_nonterminal) 

1201 

1202 used_trees = parse_used_trees(used_trees, num_trees) 

1203 

1204 # process arguments that change depending on outcome type 

1205 is_binary, kshape, error_cov_inv, binary_indices = init_shape_shifting_parameters( 

1206 y=y, 

1207 outcome_type=outcome_type, 

1208 offset=offset, 

1209 error_scale=error_scale, 

1210 error_cov_inv=error_cov_inv, 

1211 sum_trees_prior_cov_inv=sum_trees_prior_cov_inv, 

1212 missing=missing, 

1213 ) 

1214 

1215 storage = determine_storage_params( 

1216 leaf_dtype=leaf_dtype, 

1217 prec_scale_dtype=prec_scale_dtype, 

1218 resid_dtype=resid_dtype, 

1219 sum_trees_prior_cov_inv=sum_trees_prior_cov_inv.value, 

1220 kshape=kshape, 

1221 num_trees=num_trees, 

1222 ) 

1223 

1224 # extract array sizes from arguments 

1225 (num_levels,) = p_nonterminal.shape 

1226 p, n = X.shape 

1227 

1228 if check_num_trees and used_trees is not None: 

1229 check_equal_blocks(num_trees) 

1230 

1231 # check and initialize sparsity parameters 

1232 if not all_none_or_not_none(rho, a, b): 1232 ↛ 1233line 1232 didn't jump to line 1233 because the condition on line 1232 was never true

1233 msg = 'rho, a, b are not either all `None` or all set' 

1234 raise ValueError(msg) 

1235 if theta is None and rho is not None: 

1236 theta = rho 

1237 if log_s is None and theta is not None: 

1238 log_s = jnp.zeros(max_split.size) 

1239 if not all_none_or_not_none(theta, sparse_on_at): 1239 ↛ 1240line 1239 didn't jump to line 1240 because the condition on line 1239 was never true

1240 msg = 'sparsity params (either theta or rho,a,b) and sparse_on_at must be either all None or all set' 

1241 raise ValueError(msg) 

1242 

1243 # determine settings for reductions 

1244 mesh = parse_mesh(num_chains, mesh) 

1245 red_cfg = parse_reduction_configs( 

1246 resid_reduction_config=resid_reduction_config, 

1247 count_reduction_config=count_reduction_config, 

1248 prec_reduction_config=prec_reduction_config, 

1249 prec_count_num_trees=prec_count_num_trees, 

1250 y=y, 

1251 num_trees=num_trees, 

1252 num_chains=num_chains, 

1253 mesh=mesh, 

1254 ) 

1255 

1256 # check there aren't too many deactivated predictors 

1257 offset = check_splitless_vars(filter_splitless_vars, max_split, offset) 

1258 

1259 heap_size = 2**num_levels 

1260 max_num_leaves = heap_size // 2 

1261 

1262 # Assemble the state, shard it, then fill in the post-shard fields. This 

1263 # whole region runs with type-checking disabled because the state carries 

1264 # deliberately wrong-typed intermediates parked in its fields for sharding: 

1265 # `_LazyArray` leaves (each chain-bearing leaf is built at its core no-chain 

1266 # shape, then `add_chains` wraps it to broadcast in the chain axis) and the 

1267 # user `missing` mask in the `inv_sdev_scale` slot. The context ends once 

1268 # every field has been replaced by its final, correctly-typed array. 

1269 with jaxtyping_disabled(): 

1270 state = State( 

1271 _chain_anchor=lazy(jnp.zeros, ()), # typechecker chain anchor 

1272 X=X, 

1273 y=y, 

1274 z=( 

1275 lazy(jnp.full, y.shape, offset[..., None]) 

1276 if is_binary 

1277 else lazy( 

1278 jnp.full, (binary_indices.size, n), offset[binary_indices, None] 

1279 ) 

1280 if binary_indices is not None 

1281 else None 

1282 ), 

1283 binary_indices=binary_indices, 

1284 resid=( 

1285 lazy(jnp.zeros, y.shape, storage.resid_dtype) 

1286 if is_binary 

1287 # resid is created later after y and offset are sharded 

1288 else cast(Array, None) 

1289 ), 

1290 resid_unit=storage.resid_unit, 

1291 resid_eff_scale=lazy(jnp.full, kshape, storage.resid_unit), 

1292 resid_inexact_integral=lazy(jnp.zeros, kshape), 

1293 # only `value` carries the chain axis, so it becomes the lazy leaf; 

1294 # the prior params `nu`/`rate` are shared across chains 

1295 error_cov_inv=replace( 

1296 error_cov_inv, value=_lazy_from_array(error_cov_inv.value) 

1297 ), 

1298 # `error_scale` goes straight to its field; `missing` is parked in 

1299 # the `inv_sdev_scale` slot so it gets sharded with everything 

1300 # else. `compute_scale_related_attrs` derives `prec_scale` and 

1301 # `inv_sdev_scale` post-shard. 

1302 error_scale=error_scale, 

1303 prec_scale=None, 

1304 inv_sdev_scale=missing, 

1305 # invalid placeholders; the true values are set post-shard by 

1306 # `compute_scale_related_attrs` 

1307 inv_sdev_unit=cast(Array, None), 

1308 n_non_missing=cast(Array, None), 

1309 sum_diag_prec_scale=cast(Array, None), 

1310 forest=Forest( 

1311 leaf_tree=lazy( 

1312 jnp.zeros, (num_trees, *kshape, max_num_leaves), storage.leaf_dtype 

1313 ), 

1314 leaf_unit=storage.leaf_unit, 

1315 offset=offset, 

1316 var_tree=lazy( 

1317 jnp.zeros, 

1318 (num_trees, max_num_leaves), 

1319 minimal_unsigned_dtype(p - 1), 

1320 ), 

1321 split_tree=lazy( 

1322 jnp.zeros, (num_trees, max_num_leaves), max_split.dtype 

1323 ), 

1324 affluence_tree=lazy( 

1325 initial_affluence_tree, 

1326 (num_trees, max_num_leaves), 

1327 n, 

1328 min_points_per_decision_node, 

1329 max_split, 

1330 ), 

1331 blocked_vars=get_blocked_vars(filter_splitless_vars, max_split), 

1332 max_split=max_split, 

1333 used_trees=_lazy_from_array(used_trees), 

1334 grow_prop_count=lazy(jnp.zeros, (), int), 

1335 grow_acc_count=lazy(jnp.zeros, (), int), 

1336 prune_prop_count=lazy(jnp.zeros, (), int), 

1337 prune_acc_count=lazy(jnp.zeros, (), int), 

1338 p_nonterminal=p_nonterminal[tree_depths(heap_size)], 

1339 p_propose_grow=p_nonterminal[tree_depths(max_num_leaves)], 

1340 leaf_indices=lazy( 

1341 jnp.zeros, 

1342 (num_trees, n), 

1343 minimal_unsigned_dtype(max_num_leaves - 1), 

1344 ), 

1345 # no pending prune: `step` starts by applying the pending 

1346 # prunes to `leaf_indices`, which shall be a no-op on init 

1347 to_prune=lazy(jnp.zeros, (num_trees,), bool), 

1348 move_node=lazy(jnp.zeros, (num_trees,), jnp.int32), 

1349 tree_life=lazy(jnp.zeros, (num_trees,), jnp.int32), 

1350 # the counts serve the minimum-points constraints and stand in 

1351 # for the precisions when there are no per-datapoint scales 

1352 # (`prec_scale` is set iff `error_scale` or `missing` is given) 

1353 count_tree=( 

1354 lazy(initial_count_tree, (num_trees, max_num_leaves), n) 

1355 if min_points_per_decision_node is not None 

1356 or min_points_per_leaf is not None 

1357 or (error_scale is None and missing is None) 

1358 else None 

1359 ), 

1360 # prec_tree is created later, it needs the sharded prec_scale 

1361 prec_tree=None, 

1362 min_points_per_decision_node=asarray_or_none( 

1363 min_points_per_decision_node 

1364 ), 

1365 min_points_per_leaf=asarray_or_none(min_points_per_leaf), 

1366 log_trans_prior=lazy(jnp.zeros, (num_trees,)) if save_ratios else None, 

1367 log_likelihood=lazy(jnp.zeros, (num_trees,)) if save_ratios else None, 

1368 # only `value` carries the chain axis, see `error_cov_inv` 

1369 sum_trees_prior_cov_inv=replace( 

1370 sum_trees_prior_cov_inv, 

1371 value=_lazy_from_array(sum_trees_prior_cov_inv.value), 

1372 ), 

1373 sparsity=Sparsity( 

1374 log_s=_lazy_from_array(asarray_or_none(log_s)), 

1375 theta=_lazy_from_array(asarray_or_none(theta)), 

1376 rho=asarray_or_none(rho), 

1377 a=asarray_or_none(a), 

1378 b=asarray_or_none(b), 

1379 log_theta_range=None if rho is None else jnp.float32(40.0), 

1380 ), 

1381 ), 

1382 config=StepConfig( 

1383 steps_done=jnp.int32(0), 

1384 sparse_on_at=asarray_or_none(sparse_on_at), 

1385 sequential_unroll=sequential_unroll, 

1386 sequential_block_size=parse_sequential_block_size( 

1387 sequential_block_size 

1388 ), 

1389 parallel_block_size=parse_parallel_block_size( 

1390 parallel_block_size, num_trees 

1391 ), 

1392 random_tree_scan=random_tree_scan, 

1393 augment=augment, 

1394 mesh=mesh, 

1395 leaf_quantization=asarray_or_none(leaf_quantization), 

1396 # invalid placeholder; the true value is set post-shard, it 

1397 # depends on `compute_scale_related_attrs` 

1398 one_bin_prec_reduction=cast(bool, None), 

1399 **red_cfg, 

1400 ), 

1401 ) 

1402 

1403 # add the chain axis to every chain-marked leaf at the position 

1404 # declared by its field metadata 

1405 state = add_chains(state, num_chains) 

1406 

1407 # delete big input arrays such that they can be deleted as soon as they 

1408 # are sharded, only those arrays that contain an (n,) sized axis 

1409 del X, error_scale, missing, y 

1410 

1411 # move all arrays to the appropriate device and instantiate lazy arrays 

1412 state = shard_state(state) 

1413 

1414 # replace y at masked positions post-shard (the mask is parked in 

1415 # `inv_sdev_scale`), before `resid` is derived from y 

1416 if state.inv_sdev_scale is not None: 

1417 state = replace( 

1418 state, y=sanitize_y(state.y, state.inv_sdev_scale, state.forest.offset) 

1419 ) 

1420 

1421 # derive the scale arrays and their constant summaries after sharding 

1422 # to do the calculation on the right devices. `state.error_scale` 

1423 # already holds the sharded user-supplied scale and 

1424 # `state.inv_sdev_scale` holds the parked `missing` mask. 

1425 # `compute_scale_related_attrs` does not donate `error_scale`, so it 

1426 # stays in place; the derived scales fold in the mask, the raw scale 

1427 # does not. 

1428 attrs = compute_scale_related_attrs( 

1429 state.error_scale, state.inv_sdev_scale, storage.prec_scale_dtype, n 

1430 ) 

1431 state = replace( 

1432 state, 

1433 prec_scale=attrs.prec_scale, 

1434 inv_sdev_scale=attrs.inv_sdev_scale, 

1435 inv_sdev_unit=attrs.inv_sdev_unit, 

1436 n_non_missing=attrs.n_non_missing, 

1437 sum_diag_prec_scale=attrs.sum_diag_prec_scale, 

1438 config=replace( 

1439 state.config, 

1440 one_bin_prec_reduction=resolve_one_bin_prec_reduction( 

1441 one_bin_prec_reduction, 

1442 has_counts=min_points_per_decision_node is not None 

1443 or min_points_per_leaf is not None, 

1444 has_error_scale=state.error_scale is not None, 

1445 error_scale_min_max_ratio=attrs.error_scale_min_max_ratio, 

1446 n=n, 

1447 ), 

1448 ), 

1449 ) 

1450 

1451 # calculate initial resid in the continuous outcome case, such that y 

1452 # and offset are already sharded if needed 

1453 if state.resid is None: 

1454 state = set_initial_resid(state, num_chains, storage.resid_dtype) 

1455 # charge the one-time rounding of the initial residuals into storage 

1456 # when it uses a dtype narrower than y (else the cast is exact) 

1457 if jnp.finfo(storage.resid_dtype).nmant < jnp.finfo(state.y.dtype).nmant: 

1458 state = replace( 

1459 state, 

1460 resid_inexact_integral=initial_resid_inexact_integral( 

1461 state.resid, state.n_non_missing, num_trees 

1462 ), 

1463 ) 

1464 

1465 # calculate the initial prec_tree from the sharded prec_scale 

1466 if state.prec_scale is not None: 

1467 state = set_initial_prec_tree(state, num_chains, num_trees, max_num_leaves) 

1468 

1469 # all the wrong-typed intermediates have now been replaced by their final 

1470 # values, so type-checking can resume; make all types strong to avoid 

1471 # unwanted recompilations 

1472 return remove_weak_types(state) 

1473 

1474 

1475def parse_float_dtype(dtype: DTypeLike) -> jnp.dtype: 

1476 """Normalize a storage dtype and check it is floating point.""" 

1477 dtype = jnp.dtype(dtype) 

1478 assert jnp.issubdtype(dtype, jnp.floating) 

1479 return dtype 

1480 

1481 

1482def compute_sum_sdev( 

1483 sum_trees_prior_cov_inv: Float32[Array, ''] | Float32[Array, 'k k'], 

1484 kshape: tuple[int, ...], 

1485) -> Float32[Array, ''] | Float32[Array, ' k']: 

1486 """Compute the marginal prior standard deviation of the sum of trees. 

1487 

1488 A degenerate prior precision (e.g., infinite, from `bartz.Bart` with 

1489 constant ``y``) yields a zero or non-finite scale; fall back to 1 to avoid 

1490 nan leaves (an infinite precision pins the leaves to zero anyway). 

1491 """ 

1492 if kshape: 

1493 cov = inv_via_chol_with_gersh(sum_trees_prior_cov_inv) 

1494 sdev = jnp.sqrt(jnp.diagonal(cov)) 

1495 else: 

1496 sdev = jnp.sqrt(jnp.reciprocal(sum_trees_prior_cov_inv)) 

1497 return jnp.where(jnp.isfinite(sdev) & (sdev > 0), sdev, 1.0) 

1498 

1499 

1500def round_to_pow2(x: Float32[Array, '*shape']) -> Float32[Array, '*shape']: 

1501 """Round to the nearest power of two.""" 

1502 # note: don't use exp2, not exact. `2 ** x` checked exact on cpu & cuda. 

1503 return 2 ** jnp.round(jnp.log2(x)) 

1504 

1505 

1506def scaled_error_cov_inv( 

1507 state: State, 

1508) -> Float32[Array, '*chains'] | Float32[Array, '*chains k k']: 

1509 """Return the error precision with ``inv_sdev_unit ** 2`` folded in. 

1510 

1511 `State.prec_scale` and everything summed from it (`Forest.prec_tree`, the 

1512 per-leaf precision-scaled residual sums) are stored in units of 

1513 ``State.inv_sdev_unit ** 2``, so their products with this scaled precision 

1514 are in data units. Returns ``error_cov_inv.value`` as-is when there are no 

1515 per-datapoint error scales. 

1516 """ 

1517 value = state.error_cov_inv.value 

1518 unit = state.inv_sdev_unit 

1519 if state.prec_scale is None: 

1520 return value 

1521 elif unit.ndim: 

1522 return value * (unit[:, None] * unit[None, :]) 

1523 else: 

1524 return value * jnp.square(unit) 

1525 

1526 

1527@dataclass(frozen=True) 

1528class StorageParams: 

1529 """Storage dtypes and units for the leaves and residuals.""" 

1530 

1531 leaf_dtype: jnp.dtype 

1532 prec_scale_dtype: jnp.dtype 

1533 resid_dtype: jnp.dtype 

1534 leaf_unit: Float32[Array, ''] | Float32[Array, ' k'] 

1535 resid_unit: Float32[Array, ''] | Float32[Array, ' k'] 

1536 

1537 

1538def determine_storage_params( 

1539 *, 

1540 leaf_dtype: DTypeLike, 

1541 prec_scale_dtype: DTypeLike, 

1542 resid_dtype: DTypeLike, 

1543 sum_trees_prior_cov_inv: Float32[Array, ''] | Float32[Array, 'k k'], 

1544 kshape: tuple[int, ...], 

1545 num_trees: int, 

1546) -> StorageParams: 

1547 """Normalize the storage dtypes and compute the leaf and residual units.""" 

1548 sum_sdev = compute_sum_sdev(sum_trees_prior_cov_inv, kshape) 

1549 return StorageParams( 

1550 leaf_dtype=parse_float_dtype(leaf_dtype), 

1551 prec_scale_dtype=parse_float_dtype(prec_scale_dtype), 

1552 resid_dtype=parse_float_dtype(resid_dtype), 

1553 # the leaves are the smallest with all the trees in use 

1554 leaf_unit=round_to_pow2(sum_sdev / max(num_trees, 1) ** 0.5), 

1555 resid_unit=round_to_pow2(sum_sdev), 

1556 ) 

1557 

1558 

1559def set_initial_resid( 

1560 state: 'State', num_chains: int | None, resid_dtype: jnp.dtype 

1561) -> 'State': 

1562 """Build the continuous-outcome `resid` and shard it. 

1563 

1564 Called post-shard so the captured ``state.y``, ``state.forest.offset`` and 

1565 ``state.binary_indices`` are already on the target devices. Sharding axes are 

1566 read via `chain_vmap_axes` / `data_vmap_axes` on a shape preview where the 

1567 new `resid` leaf has the chain-extended ``ndim`` (inflated by a placeholder 

1568 when `num_chains` is not `None`). 

1569 """ 

1570 inner = _LazyArray( 

1571 initial_resid, 

1572 state.y.shape, 

1573 state.y, 

1574 state.forest.offset, 

1575 state.binary_indices, 

1576 state.resid_unit, 

1577 resid_dtype, 

1578 ) 

1579 preview_resid = add_dummy_axis(inner) if num_chains is not None else inner 

1580 preview = replace(state, resid=preview_resid) 

1581 chain_axis = chain_vmap_axes(preview).resid 

1582 data_axis = data_vmap_axes(preview).resid 

1583 resid = _wrap_chain(inner, chain_axis, num_chains) 

1584 resid = shard_leaf(resid, chain_axis, data_axis, state.config.mesh) 

1585 return replace(state, resid=resid) 

1586 

1587 

1588@jit 

1589def initial_resid_inexact_integral( 

1590 resid: Float[Array, '*chains n'] | Float[Array, '*chains k n'], 

1591 n_non_missing: Int32[Array, ''] | Int32[Array, ' k'], 

1592 num_trees: int, 

1593) -> Float32[Array, '*chains'] | Float32[Array, '*chains k']: 

1594 """Seed value for `State.resid_inexact_integral` from the initial rounding. 

1595 

1596 Casting the initial residuals to a storage dtype narrower than `y` rounds 

1597 them once, and the running updates never fix this offset (they either round 

1598 again, which the per-step accounting covers, or preserve it exactly), so it 

1599 is charged upfront as one tree-update's worth of rounding. 

1600 """ 

1601 # masked residuals are set to 0 at this stage, so they drop out of the sum 

1602 ms = jnp.einsum('...n,...n->...', resid, resid, preferred_element_type=jnp.float32) 

1603 ms /= jnp.maximum(n_non_missing, 1) 

1604 return ms / num_trees 

1605 

1606 

1607def initial_resid( # noqa: PLR0917, `_LazyArray` passes arguments by position 

1608 shape: tuple[int, ...], 

1609 y: Float32[Array, ' n'] | Float32[Array, 'k n'], 

1610 offset: Float32[Array, ''] | Float32[Array, ' k'], 

1611 binary_indices: Int32[Array, ' kb'] | None, 

1612 resid_unit: Float32[Array, ''] | Float32[Array, ' k'], 

1613 resid_dtype: jnp.dtype, 

1614) -> Float[Array, ' n'] | Float[Array, 'k n']: 

1615 """Calculate the initial value for `State.resid` in the continuous outcome case. 

1616 

1617 The residual is stored in units of `resid_unit` and dtype `resid_dtype`. In 

1618 the mixed binary-continuous case, binary rows are zeroed out (their residual 

1619 starts at ``z - trees - offset = 0``). 

1620 """ 

1621 resid = jnp.broadcast_to(y - offset[..., None], shape) 

1622 if binary_indices is not None: 

1623 resid = resid.at[..., binary_indices, :].set(0.0, unique_indices=True) 

1624 return (resid / resid_unit[..., None]).astype(resid_dtype) 

1625 

1626 

1627def initial_affluence_tree( 

1628 shape: tuple[int, ...], 

1629 n: int, 

1630 min_points_per_decision_node: int | None, 

1631 max_split: UInt[Array, ' p'], 

1632) -> Shaped[Array, '...']: 

1633 """Create the initial value of `Forest.affluence_tree`.""" 

1634 enough_points = ( 

1635 True 

1636 if min_points_per_decision_node is None 

1637 else n >= min_points_per_decision_node 

1638 ) 

1639 return jnp.zeros(shape, bool).at[..., 1].set(enough_points & jnp.any(max_split)) 

1640 

1641 

1642def initial_count_tree(shape: tuple[int, ...], n: int) -> Shaped[Array, '...']: 

1643 """Create the initial value of `Forest.count_tree`: all datapoints in the root.""" 

1644 return jnp.zeros(shape, jnp.uint32).at[..., 0].set(n) 

1645 

1646 

1647def set_initial_prec_tree( 

1648 state: State, num_chains: int | None, num_trees: int, max_num_leaves: int 

1649) -> State: 

1650 """Build the cached per-leaf precision for root-only trees and shard it. 

1651 

1652 Called post-shard so the captured ``state.prec_scale`` is already on the 

1653 target devices; mirrors `set_initial_resid`. 

1654 """ 

1655 assert state.prec_scale is not None 

1656 shape = (num_trees, *state.prec_scale.shape[:-1], max_num_leaves) 

1657 inner = _LazyArray(initial_prec_tree, shape, state.prec_scale) 

1658 preview_tree = add_dummy_axis(inner) if num_chains is not None else inner 

1659 preview = replace(state, forest=replace(state.forest, prec_tree=preview_tree)) 

1660 chain_axis = chain_vmap_axes(preview).forest.prec_tree 

1661 prec_tree = _wrap_chain(inner, chain_axis, num_chains) 

1662 prec_tree = shard_leaf(prec_tree, chain_axis, None, state.config.mesh) 

1663 return replace(state, forest=replace(state.forest, prec_tree=prec_tree)) 

1664 

1665 

1666def initial_prec_tree( 

1667 shape: tuple[int, ...], prec_scale: Float[Array, ' n'] | Float[Array, 'k k n'] 

1668) -> ( 

1669 Float32[Array, 'num_trees max_num_leaves'] 

1670 | Float32[Array, 'num_trees k k max_num_leaves'] 

1671): 

1672 """Create the initial value of `Forest.prec_tree`: all datapoints in the root.""" 

1673 return ( 

1674 jnp.zeros(shape, jnp.float32) 

1675 .at[..., 0] 

1676 .set(prec_scale.sum(axis=-1, dtype=jnp.float32)) 

1677 ) 

1678 

1679 

1680@jit(donate_argnums=(0,)) 

1681def sanitize_y( 

1682 y: Float32[Array, ' n'] | Float32[Array, 'k n'], 

1683 missing: Bool[Array, ' n'] | Bool[Array, 'k n'], 

1684 offset: Float32[Array, ''] | Float32[Array, ' k'], 

1685) -> Float32[Array, ' n'] | Float32[Array, 'k n']: 

1686 """Replace `y` with `offset` at masked positions. 

1687 

1688 The MCMC ignores masked datapoints through their zeroed precision, but the 

1689 values parked in `y` still enter `resid`; garbage values of large magnitude 

1690 would degrade the accuracy of quantities derived from it, like the ``y - 

1691 resid`` train predictions. Donates `y` to overwrite it in place. 

1692 """ 

1693 return jnp.where(missing, offset[..., None], y) 

1694 

1695 

1696class ScaleRelatedAttrs(NamedTuple): 

1697 """Output of `compute_scale_related_attrs`.""" 

1698 

1699 inv_sdev_scale: Float[Array, ' n'] | Float[Array, 'k n'] | None 

1700 prec_scale: Float[Array, ' n'] | Float[Array, 'k k n'] | None 

1701 inv_sdev_unit: Float32[Array, ''] | Float32[Array, ' k'] 

1702 n_non_missing: Int32[Array, ''] | Int32[Array, ' k'] 

1703 sum_diag_prec_scale: Float32[Array, ''] | Float32[Array, ' k'] 

1704 error_scale_min_max_ratio: Float32[Array, ''] 

1705 

1706 

1707@jit(donate_argnums=(1,), static_argnums=(2, 3)) 

1708def compute_scale_related_attrs( 

1709 error_scale: Float32[Array, ' n'] | Float32[Array, 'k n'] | None, 

1710 missing: Bool[Array, ' n'] | Bool[Array, 'k n'] | None, 

1711 prec_scale_dtype: jnp.dtype, 

1712 n: int, 

1713) -> ScaleRelatedAttrs: 

1714 """Compute all the fixed quantities derived from `error_scale` and `missing`.""" 

1715 if error_scale is None and missing is None: 

1716 n_non_missing = jnp.full((), n) 

1717 return ScaleRelatedAttrs( 

1718 inv_sdev_scale=None, 

1719 prec_scale=None, 

1720 inv_sdev_unit=jnp.float32(1.0), 

1721 n_non_missing=n_non_missing, 

1722 sum_diag_prec_scale=n_non_missing.astype(jnp.float32), 

1723 error_scale_min_max_ratio=jnp.float32(1.0), 

1724 ) 

1725 

1726 # compute inv_sdev_scale 

1727 if error_scale is None: 

1728 inv_sdev_scale = jnp.array(1.0) # becomes a vector with the `where` below 

1729 else: 

1730 inv_sdev_scale = jnp.reciprocal(error_scale) 

1731 if missing is not None: 

1732 inv_sdev_scale = jnp.where(missing, 0.0, inv_sdev_scale) 

1733 

1734 # count non-missing points, and the equivalent error-scaled quantity 

1735 n_non_missing = jnp.sum(inv_sdev_scale != 0, axis=-1) 

1736 sum_diag_prec_scale = jnp.einsum('...n,...n->...', inv_sdev_scale, inv_sdev_scale) 

1737 

1738 # min(error_scale) / max(error_scale), with the missing datapoints taken 

1739 # to have infinite error scale 

1740 if inv_sdev_scale.size: 

1741 max_inv_sdev = jnp.max(inv_sdev_scale) 

1742 error_scale_min_max_ratio = jnp.min(inv_sdev_scale) / jnp.where( 

1743 max_inv_sdev > 0, max_inv_sdev, 1.0 

1744 ) 

1745 else: 

1746 error_scale_min_max_ratio = jnp.float32(1.0) 

1747 

1748 # compute inv_sdev_unit and factor it out of inv_sdev_scale 

1749 inv_sdev_unit = round_to_pow2( 

1750 jnp.sqrt(sum_diag_prec_scale / jnp.maximum(n_non_missing, 1)) 

1751 ) 

1752 inv_sdev_unit = jnp.where(inv_sdev_unit, inv_sdev_unit, 1.0) 

1753 inv_sdev_scale = inv_sdev_scale / inv_sdev_unit[..., None] 

1754 

1755 # compute prec_scale 

1756 if inv_sdev_scale.ndim == 1: 

1757 prec_scale = jnp.square(inv_sdev_scale) 

1758 else: 

1759 prec_scale = jnp.einsum('an,bn->abn', inv_sdev_scale, inv_sdev_scale) 

1760 

1761 return ScaleRelatedAttrs( 

1762 inv_sdev_scale=inv_sdev_scale.astype(prec_scale_dtype), 

1763 prec_scale=prec_scale.astype(prec_scale_dtype), 

1764 inv_sdev_unit=inv_sdev_unit, 

1765 n_non_missing=n_non_missing, 

1766 sum_diag_prec_scale=sum_diag_prec_scale, 

1767 error_scale_min_max_ratio=error_scale_min_max_ratio, 

1768 ) 

1769 

1770 

1771def resolve_one_bin_prec_reduction( 

1772 one_bin_prec_reduction: bool | Literal['auto'], 

1773 *, 

1774 has_counts: bool, 

1775 has_error_scale: bool, 

1776 error_scale_min_max_ratio: Float32[Array, ''], 

1777 n: int, 

1778) -> bool: 

1779 """Resolve the `one_bin_prec_reduction` argument of `init`.""" 

1780 if isinstance(one_bin_prec_reduction, bool): 

1781 return one_bin_prec_reduction 

1782 elif not has_counts: 

1783 # without the counts the setting is ignored 

1784 return False 

1785 elif not has_error_scale: 

1786 # the precisions are 0 or 1, so their sums are exact up to float32 

1787 # mantissa bits 

1788 return n <= 2**24 

1789 elif jit_active(): 

1790 msg = ( 

1791 "The setting `one_bin_prec_reduction='auto'` needs to read the values " 

1792 "of `error_scale`, but `bartz.mcmcstep.init()` can't do it because it " 

1793 'has been invoked inside a `jax.jit`-compiled function. Set it ' 

1794 'explicitly (as `Bart(..., init_kw=dict(one_bin_prec_reduction=' 

1795 'True/False))` if using `Bart`), it is safe to set it to `True` if ' 

1796 'max(error_scale) / min(error_scale) <= 100 and no datapoint is ' 

1797 'missing' 

1798 ) 

1799 raise ValueError(msg) 

1800 elif (ratio := error_scale_min_max_ratio.item()) >= 0.01: 

1801 return True 

1802 else: 

1803 if ratio > 0: 

1804 reason = f'`error_scale` spans a ratio of {1 / ratio:.3g} > 100' 

1805 else: 

1806 reason = 'some datapoints are missing' 

1807 msg = ( 

1808 '`one_bin_prec_reduction` optimization set automatically to `False` ' 

1809 f'because {reason}, which might make it numerically unstable; set it ' 

1810 'explicitly to silence this warning' 

1811 ) 

1812 warn(msg) 

1813 return False 

1814 

1815 

1816def get_blocked_vars( 

1817 filter_splitless_vars: int, max_split: UInt[Array, ' p'] 

1818) -> None | UInt[Array, ' q']: 

1819 """Initialize the `blocked_vars` field.""" 

1820 if filter_splitless_vars: 

1821 (p,) = max_split.shape 

1822 (blocked_vars,) = jnp.nonzero( 

1823 max_split == 0, size=filter_splitless_vars, fill_value=p 

1824 ) 

1825 return blocked_vars.astype(minimal_unsigned_dtype(p)) 

1826 # see `fully_used_variables` for the type cast 

1827 else: 

1828 return None 

1829 

1830 

1831def add_chains(state: 'State', num_chains: int | None) -> 'State': 

1832 """Extend chain-marked `_LazyArray` leaves to include a chain axis of size `num_chains`. 

1833 

1834 Walks `state`, asks `chain_vmap_axes` where each leaf's chain axis lives, 

1835 and wraps the carried `_LazyArray` so its factory creates the core array 

1836 and then broadcasts a chain axis in at that position. To make 

1837 `chain_vmap_axes` normalize against the chain-extended ``ndim``, the 

1838 lookup is done on a shape preview built via `add_dummy_axis`. No-op when 

1839 `num_chains` is `None`. 

1840 

1841 Chain-marked leaves are required to be `_LazyArray` (or `None`); eager 

1842 arrays at chain-marked positions are rejected so that all chain insertion 

1843 happens at concretization time inside `shard_state`. 

1844 """ 

1845 if num_chains is None: 

1846 return state 

1847 preview = add_dummy_axis(state) 

1848 chain_axes = chain_vmap_axes(preview) 

1849 

1850 def wrap(leaf: object, chain_axis: int | None) -> object: 

1851 if chain_axis is None or leaf is None: 

1852 return leaf 

1853 assert isinstance(leaf, _LazyArray), ( 

1854 f'expected _LazyArray for chain-marked leaf, got {type(leaf).__name__}' 

1855 ) 

1856 return _wrap_chain(leaf, chain_axis, num_chains) 

1857 

1858 return tree.map(wrap, state, chain_axes, is_leaf=_is_lazy_or_none) 

1859 

1860 

1861def parse_mesh( 

1862 num_chains: int | None, mesh: Mesh | dict[str, int] | None 

1863) -> Mesh | None: 

1864 """Parse the `mesh` argument.""" 

1865 if mesh is None: 

1866 return None 

1867 

1868 # convert dict format to actual mesh 

1869 if not isinstance(mesh, Mesh): 

1870 assert set(mesh).issubset({'chains', 'data'}) 

1871 mesh = make_mesh( 

1872 tuple(mesh.values()), tuple(mesh), axis_types=(AxisType.Auto,) * len(mesh) 

1873 ) 

1874 

1875 # the chains mesh axis must be consistent with the number of chains 

1876 if 'chains' in mesh.axis_names: 

1877 if num_chains is None: 

1878 msg = "mesh has a 'chains' axis but num_chains is None (scalar, no chain axis)" 

1879 raise ValueError(msg) 

1880 chains_axis = get_axis_size(mesh, 'chains') 

1881 if num_chains % chains_axis: 

1882 msg = ( 

1883 f"mesh 'chains' axis of size {chains_axis} does not divide " 

1884 f'num_chains={num_chains}' 

1885 ) 

1886 raise ValueError(msg) 

1887 

1888 # check the axes we use are in auto mode 

1889 assert 'chains' not in mesh.axis_names or 'chains' in mesh.auto_axes 

1890 assert 'data' not in mesh.axis_names or 'data' in mesh.auto_axes 

1891 

1892 return mesh 

1893 

1894 

1895@partial(filter_jit, donate='all') 

1896# jit and donate because otherwise type conversion would create copies 

1897def remove_weak_types(x: PyTree[Array, 'T']) -> PyTree[Array, 'T']: 

1898 """Make all types strong. 

1899 

1900 This is to avoid recompilation in `run_mcmc` or `step`. 

1901 """ 

1902 

1903 def remove_weak(x: T) -> T: 

1904 if isinstance(x, Array) and x.weak_type: 

1905 return cast(T, x.astype(x.dtype)) 

1906 else: 

1907 return x 

1908 

1909 return tree.map(remove_weak, x) 

1910 

1911 

1912def shard_state(state: State) -> State: 

1913 """Place all arrays on the appropriate devices, and instantiate lazily defined arrays.""" 

1914 mesh = state.config.mesh 

1915 axes = chain_vmap_axes(state), data_vmap_axes(state) 

1916 

1917 def shard_lazy( 

1918 x: Shaped[Array, '...'] | Shaped[_LazyArray, '...'] | None, 

1919 chain_axis: int | None, 

1920 data_axis: int | None, 

1921 ) -> Shaped[Array, '...'] | None: 

1922 if isinstance(x, _LazyArray): 

1923 return shard_leaf(x, chain_axis, data_axis, mesh) 

1924 else: 

1925 return x 

1926 

1927 def shard_eager( 

1928 orig: Shaped[Array, '...'] | Shaped[_LazyArray, '...'] | None, 

1929 x: Shaped[Array, '...'] | None, 

1930 chain_axis: int | None, 

1931 data_axis: int | None, 

1932 ) -> Shaped[Array, '...'] | None: 

1933 if isinstance(orig, _LazyArray): 

1934 return x 

1935 else: 

1936 return shard_leaf(x, chain_axis, data_axis, mesh) 

1937 

1938 # instantiate the lazy arrays first because `shard_leaf` donates the eager 

1939 # arrays, which lazy arrays may capture 

1940 new_state = tree.map(shard_lazy, state, *axes, is_leaf=_is_lazy_or_none) 

1941 return tree.map(shard_eager, state, new_state, *axes, is_leaf=_is_lazy_or_none) 

1942 

1943 

1944def leaf_partition_spec( 

1945 ndim: int, chain_axis: int | None, data_axis: int | None, mesh: Mesh 

1946) -> PartitionSpec: 

1947 """Build a `PartitionSpec` for a leaf with the given chain/data axes.""" 

1948 spec = [None] * ndim 

1949 if chain_axis is not None and 'chains' in mesh.axis_names: 

1950 spec[chain_axis] = 'chains' 

1951 if data_axis is not None and 'data' in mesh.axis_names: 

1952 spec[data_axis] = 'data' 

1953 

1954 # remove trailing Nones to be consistent with jax's output, it's useful 

1955 # for comparing shardings during debugging 

1956 while spec and spec[-1] is None: 

1957 spec.pop() 

1958 

1959 return PartitionSpec(*spec) 

1960 

1961 

1962def shard_leaf( 

1963 x: Shaped[Array, '*shape'] | None | Shaped[_LazyArray, '*shape'], 

1964 chain_axis: int | None, 

1965 data_axis: int | None, 

1966 mesh: Mesh | None, 

1967) -> Shaped[Array, '*shape'] | None: 

1968 """Create `x` if it's lazy and shard it.""" 

1969 if x is None: 

1970 return None 

1971 

1972 if mesh is None: 

1973 sharding = None 

1974 else: 

1975 spec = leaf_partition_spec(x.ndim, chain_axis, data_axis, mesh) 

1976 sharding = NamedSharding(mesh, spec) 

1977 

1978 if isinstance(x, _LazyArray): 

1979 if mesh is not None and not jit_active(): 

1980 x = tree.map(partial(put_on_mesh, mesh=mesh), x) 

1981 x = concretize_lazy_array(x, sharding) 

1982 elif sharding is not None: 

1983 x = device_put(x, sharding, donate=True) 

1984 

1985 return x 

1986 

1987 

1988def put_on_mesh(x: T, mesh: Mesh) -> T: 

1989 """Replicate `x` over `mesh` if it's an array that lives on other devices. 

1990 

1991 This makes arrays committed elsewhere acceptable to `jit` alongside arrays 

1992 sharded over `mesh`. 

1993 """ 

1994 if isinstance(x, Array) and x.sharding.device_set != set(mesh.devices.flat): 

1995 # only small arrays are expected here, the largest being `log_s` 

1996 # with shape (p,) 

1997 assert x.nbytes <= 100 * 2**20, f'replicating a large array {x.shape=}' 

1998 return cast(T, device_put(x, NamedSharding(mesh, PartitionSpec()))) 

1999 else: 

2000 return x 

2001 

2002 

2003@filter_jit 

2004# jit such that in recent jax versions the shards are created on the right 

2005# devices immediately instead of being created on the wrong device and then 

2006# copied 

2007def concretize_lazy_array( 

2008 x: Shaped[_LazyArray, '*shape'], sharding: NamedSharding | None 

2009) -> Shaped[Array, '*shape']: 

2010 """Create an array from an abstract spec on the appropriate devices.""" 

2011 x = x() 

2012 if sharding is not None: 

2013 x = lax.with_sharding_constraint(x, sharding) 

2014 return x 

2015 

2016 

2017def all_none_or_not_none(*args: object) -> bool: 

2018 is_none = [x is None for x in args] 

2019 return all(is_none) or not any(is_none) 

2020 

2021 

2022def asarray_or_none(x: object) -> Shaped[Array, '...'] | None: 

2023 if x is None: 

2024 return None 

2025 return jnp.asarray(x) 

2026 

2027 

2028class ReductionConfigs(TypedDict): 

2029 """Fields of `StepConfig` related to reductions.""" 

2030 

2031 resid_reduction_config: ReductionConfig 

2032 count_reduction_config: ReductionConfig 

2033 prec_reduction_config: ReductionConfig 

2034 prec_count_num_trees: int | None 

2035 

2036 

2037def parse_reduction_configs( 

2038 *, 

2039 resid_reduction_config: ReductionConfig, 

2040 count_reduction_config: ReductionConfig, 

2041 prec_reduction_config: ReductionConfig, 

2042 prec_count_num_trees: int | None | Literal['auto'], 

2043 y: Float32[Array, ' n'] | Float32[Array, ' k n'] | Bool[Array, ' n'], 

2044 num_trees: int, 

2045 num_chains: int | None, 

2046 mesh: Mesh | None, 

2047) -> ReductionConfigs: 

2048 """Determine settings for indexed reduces.""" 

2049 n = y.shape[-1] 

2050 n //= get_axis_size(mesh, 'data') # per-device datapoints 

2051 

2052 # chains are vmapped together on each device, so they share the per-step 

2053 # memory of the per-tree reduction 

2054 chains_per_device = (num_chains or 1) // get_axis_size(mesh, 'chains') 

2055 

2056 # the reduction configs carry their own datapoint-batch settings (resolved 

2057 # per-platform at run time when 'auto', see `ReductionConfig`), so they are 

2058 # stored verbatim; only `prec_count_num_trees`, which does not depend on the 

2059 # platform, is resolved here 

2060 return dict( 

2061 resid_reduction_config=resid_reduction_config, 

2062 count_reduction_config=count_reduction_config, 

2063 prec_reduction_config=prec_reduction_config, 

2064 prec_count_num_trees=parse_prec_count_num_trees( 

2065 prec_count_num_trees, num_trees, n * chains_per_device 

2066 ), 

2067 ) 

2068 

2069 

2070def parse_prec_count_num_trees( 

2071 prec_count_num_trees: int | None | Literal['auto'], num_trees: int, n: int 

2072) -> int | None: 

2073 """Return the number of trees to process at a time or determine it automatically.""" 

2074 if prec_count_num_trees != 'auto': 

2075 return prec_count_num_trees 

2076 max_n_by_ntree = 2**27 # about 100M 

2077 pcnt = max_n_by_ntree // max(1, n) 

2078 pcnt = min(num_trees, pcnt) 

2079 pcnt = max(1, pcnt) 

2080 pcnt = search_divisor( 

2081 pcnt, num_trees, max(1, pcnt // 2), max(1, min(num_trees, pcnt * 2)) 

2082 ) 

2083 if pcnt >= num_trees: 2083 ↛ 2085line 2083 didn't jump to line 2085 because the condition on line 2083 was always true

2084 pcnt = None 

2085 return pcnt 

2086 

2087 

2088# With a variable number of trees, `step` can update the leaf indices of the 

2089# trees in use in equal blocks. By default a block has about 

2090# `PARALLEL_BLOCK_NUMEL[platform]` (tree, datapoint) pairs, but there are at 

2091# least `parallel_min_blocks(platform)` blocks; unless all the trees have less 

2092# than that many pairs, or their number has no suitable divisor, then they are 

2093# a single block, processed at once like a fixed number of trees. 

2094 

2095# On gpu, enough pairs to saturate it, so a block of trees takes about as long 

2096# as its share of all the trees at once. On cpu, enough for the overhead of an 

2097# iteration of the loop over blocks to be small next to the work on a block. 

2098PARALLEL_BLOCK_NUMEL = dict(cpu=2**20, gpu=2**26) 

2099 

2100# Depending on the sizes, xla on gpu may write a block through a temporary 

2101# instead of in place. The minimum number of blocks on gpu bounds the temporary 

2102# to a fraction of the leaf indices, also with many chains. `init` wants a 

2103# variable number of trees to be a multiple of it, such that they always divide 

2104# into this many blocks. 

2105PARALLEL_MIN_BLOCKS = 8 

2106 

2107 

2108def default_parallel_block_size( 

2109 num_trees: int, n: int, platform: Literal['cpu', 'gpu'] 

2110) -> int: 

2111 """Pick the default of `StepConfig.parallel_block_size`. 

2112 

2113 Parameters 

2114 ---------- 

2115 num_trees 

2116 The maximum number of trees. 

2117 n 

2118 The number of datapoints. 

2119 platform 

2120 The platform the MCMC runs on. 

2121 

2122 Returns 

2123 ------- 

2124 The number of trees in a block, a divisor of `num_trees`. 

2125 """ 

2126 target = PARALLEL_BLOCK_NUMEL[platform] // max(1, n) 

2127 up = num_trees // parallel_min_blocks(platform) 

2128 # WORKAROUND(jax<0.12.0): on cpu, xla copies the leaf indices around the 

2129 # choice at run time between blocks and all the trees in `step`, so make a 

2130 # single block; once unsupported, drop `copies` 

2131 copies = platform == 'cpu' and jax.__version_info__ < (0, 12, 0) 

2132 if target >= num_trees or up == 0 or copies: 

2133 return num_trees 

2134 else: 

2135 target = max(1, min(target, up)) 

2136 # the divisor closest to the target, but not much smaller 

2137 size = search_divisor(target, num_trees, -(-target // 2), up) 

2138 # the search returns the target if there is no such divisor 

2139 return size if num_trees % size == 0 else num_trees 

2140 

2141 

2142def parallel_min_blocks(platform: Literal['cpu', 'gpu']) -> int: 

2143 """Return the minimum number of blocks of trees to update the leaf indices in. 

2144 

2145 On cpu, the blocks in use are processed alone only if they are at most 1 in 

2146 this many, else all the trees at once are faster. 

2147 """ 

2148 if platform == 'cpu': 

2149 # Xla:cpu updates a block of trees on one thread, and all the trees at 

2150 # once split across all the threads. So the blocks in use alone are no 

2151 # slower if they are at most 1 in as many as the threads; make it twice 

2152 # as many, because a tree takes somewhat longer in a block. Without a 

2153 # cpu backend this is not used, any number of threads will do. 

2154 return 2 * (get_cpu_thread_count() or 1) 

2155 else: 

2156 return PARALLEL_MIN_BLOCKS 

2157 

2158 

2159def search_divisor(target_divisor: int, dividend: int, low: int, up: int) -> int: 

2160 """Find the divisor closest to `target_divisor` in [low, up] if `target_divisor` is not already. 

2161 

2162 If there is none, give up and return `target_divisor`. 

2163 """ 

2164 assert target_divisor >= 1 

2165 assert 1 <= low <= up <= dividend 

2166 if dividend % target_divisor == 0: 

2167 return target_divisor 

2168 candidates = numpy.arange(low, up + 1) 

2169 divisors = candidates[dividend % candidates == 0] 

2170 if divisors.size == 0: 

2171 return target_divisor 

2172 penalty = numpy.abs(divisors - target_divisor) 

2173 closest = numpy.argmin(penalty) 

2174 return divisors[closest].item() 

2175 

2176 

2177def get_axis_size(mesh: Mesh | None, axis_name: str) -> int: 

2178 if mesh is None or axis_name not in mesh.shape: 

2179 return 1 

2180 else: 

2181 return mesh.shape[axis_name] 

2182 

2183 

2184def chol_with_gersh( 

2185 mat: Float32[Array, '*batch_shape k k'], absolute_eps: bool = False 

2186) -> Float32[Array, '*batch_shape k k']: 

2187 """Cholesky with Gershgorin stabilization if near singular, supports batching.""" 

2188 return _chol_with_gersh_impl(mat, absolute_eps) 

2189 

2190 

2191@partial(jnp.vectorize, signature='(k,k)->(k,k)', excluded=(1,)) 

2192def _chol_with_gersh_impl( 

2193 mat: Float32[Array, '*batch_shape k k'], absolute_eps: bool 

2194) -> Float32[Array, '*batch_shape k k']: 

2195 # standardize to ~unit diagonal first, so the Gershgorin shift is relative 

2196 # to each component's scale instead of a single absolute value set by the 

2197 # largest one (which would swamp components with much smaller variance, e.g. 

2198 # mixing a heavily-scaled continuous outcome with O(1) binary ones). 

2199 # degenerate (non-positive or non-finite, e.g. infinite precision from a 

2200 # constant outcome) diagonals fall back to the largest finite scale, which 

2201 # leaves an infinite diagonal infinite (pinning that leaf to zero). The 

2202 # scales are powers of 2, so the scaling is exact, and a diagonal matrix 

2203 # gives the same factor as a plain Cholesky 

2204 diag = jnp.diagonal(mat) 

2205 finite_pos = jnp.isfinite(diag) & (diag > 0) 

2206 ref = reduce_last(jnp.where(finite_pos, diag, 0.0), lax.max, 0.0) 

2207 scale = jnp.where(finite_pos, diag, jnp.where(ref > 0, ref, 1.0)) 

2208 scale, inv_scale = pow2_near_sqrt(scale) 

2209 mat = mat * inv_scale[:, None] * inv_scale[None, :] 

2210 rho = reduce_last(reduce_last(jnp.abs(mat), lax.add, 0.0), lax.max, 0.0) 

2211 eps = jnp.finfo(mat.dtype).eps 

2212 k, _ = mat.shape 

2213 u = k * rho * eps 

2214 if absolute_eps: 

2215 u += eps 

2216 

2217 # the shift guarantees the factorization succeeds, but it biases the 

2218 # inverse by a relative u / lambda_min in the weakest direction, so it's 

2219 # used only if the factorization without has a pivot (squared diagonal 

2220 # entry of the factor) below u, i.e., smaller than the pivots that the 

2221 # shift guarantees, or fails (nan). Both factorizations are always done, 

2222 # stacked in a single batched call. 

2223 # select instead of u * eye, which would be nan off-diagonal if u = inf 

2224 shifted = jnp.where(jnp.eye(k, dtype=bool), mat + u, mat) 

2225 plain, shifted = cholesky(jnp.stack([mat, shifted])) 

2226 well_conditioned = reduce_last( 

2227 jnp.square(jnp.diagonal(plain)) >= u, lax.bitwise_and, True 

2228 ) 

2229 L = jnp.where(well_conditioned, plain, shifted) 

2230 return scale[:, None] * L 

2231 

2232 

2233def pow2_near_sqrt( 

2234 x: Float32[Array, '*shape'], 

2235) -> tuple[Float32[Array, '*shape'], Float32[Array, '*shape']]: 

2236 """Return a power of 2 near the square root of finite `x` > 0, and its reciprocal.""" 

2237 # with x = m 2^e, 1 <= m < 2, 2^ceil(e/2) is the power of 2 nearest to 

2238 # sqrt(x) (up to ties); reading e from the bits is much faster than log2. 

2239 # Subnormals have e = -127 in the bits, giving 2^-63, still normal. 

2240 assert x.dtype == jnp.float32 

2241 e = (lax.bitcast_convert_type(x, jnp.int32) >> 23) - 127 

2242 n = (e + 1) >> 1 

2243 pow2 = lax.bitcast_convert_type((n + 127) << 23, jnp.float32) 

2244 inv_pow2 = lax.bitcast_convert_type((127 - n) << 23, jnp.float32) 

2245 return pow2, inv_pow2 

2246 

2247 

2248# up to this axis length, reductions are faster unrolled; empty axes are left 

2249# to the library 

2250UNROLL_REDUCE_MAX_SIZE = 3 

2251 

2252 

2253def reduce_last( 

2254 x: Shaped[Array, '*shape n'], 

2255 op: Callable[[Array, Array], Array], 

2256 initial: bool | float, 

2257) -> Shaped[Array, '*shape']: 

2258 """Reduce the last axis with the binary operation `op`.""" 

2259 *_, n = x.shape 

2260 if 0 < n <= UNROLL_REDUCE_MAX_SIZE: 

2261 return reduce(op, (x[..., i] for i in range(n))) 

2262 else: 

2263 init = jnp.asarray(initial, x.dtype) 

2264 return lax.reduce(x, init, op, (x.ndim - 1,)) 

2265 

2266 

2267def inv_via_chol_with_gersh( 

2268 mat: Float32[Array, '*batch_shape k k'], 

2269) -> Float32[Array, '*batch_shape k k']: 

2270 """Compute matrix inverse via Cholesky with Gershgorin stabilization. 

2271 

2272 DO NOT USE THIS FUNCTION UNLESS YOU REALLY NEED TO. 

2273 """ 

2274 # mat = L L^T 

2275 # mat^-1 = L^-T L^-1 = L^-T I L^-1 = L^-T (L^-T I)^T 

2276 # I suspect this to be more accurate than (L^-1 I)^T (L^-1 I) 

2277 L = chol_with_gersh(mat) 

2278 eye = jnp.broadcast_to(jnp.eye(mat.shape[-1]), mat.shape) 

2279 Ltinv = solve_triangular(L, eye, trans='T', lower=True) 

2280 return solve_triangular(L, Ltinv.mT, trans='T', lower=True) 

2281 

2282 

2283# The chain decorators below are generic over the state type, so that they 

2284# preserve `State` subclasses. 

2285# WORKAROUND(python<3.12): replace with PEP 695 type parameters on the 

2286# decorators, e.g. `def vmap_chains[S: State](...)`. 

2287StateT = TypeVar('StateT', bound=State) 

2288 

2289 

2290def split_key_for_chains( 

2291 fun: Callable[[Key[Array, ''] | Key[Array, ' num_chains'], StateT], StateT], 

2292) -> Callable[[Key[Array, ''], StateT], StateT]: 

2293 """Split a single PRNG key into per-chain keys before calling `fun`. 

2294 

2295 When the state is multichain, the input key is split into 

2296 ``state.num_chains()`` keys. For single-chain states, the key is passed 

2297 through unchanged. 

2298 """ 

2299 

2300 @wraps(fun) 

2301 def wrapped(key: Key[Array, ''], state: StateT) -> StateT: 

2302 num_chains = state.num_chains() 

2303 if num_chains is None: 

2304 return fun(key, state) 

2305 keys = random.split(key, num_chains) 

2306 return fun(keys, state) 

2307 

2308 return wrapped 

2309 

2310 

2311def partition_specs(x: PyTree, mesh: Mesh) -> PyTree[PartitionSpec]: 

2312 """Per-leaf `PartitionSpec`s derived from chain/data `field` markers. 

2313 

2314 Each array leaf is sharded over ``'chains'`` along its chain axis and over 

2315 ``'data'`` along its data axis, when those axes are marked (see `field`) 

2316 and present in `mesh`; all other axes are replicated. 

2317 

2318 Parameters 

2319 ---------- 

2320 x 

2321 A pytree of arrays carrying chain/data `field` markers. 

2322 mesh 

2323 The device mesh to shard over. 

2324 

2325 Returns 

2326 ------- 

2327 A pytree matching `x` with a `PartitionSpec` in place of each array leaf. 

2328 """ 

2329 return tree.map( 

2330 lambda leaf, ca, da: leaf_partition_spec(leaf.ndim, ca, da, mesh), 

2331 x, 

2332 chain_vmap_axes(x), 

2333 data_vmap_axes(x), 

2334 ) 

2335 

2336 

2337def shard_map_state( 

2338 fun: Callable[[Key[Array, ''] | Key[Array, ' num_chains'], StateT], StateT], 

2339) -> Callable[[Key[Array, ''] | Key[Array, ' num_chains'], StateT], StateT]: 

2340 """Wrap a ``(keys, state) -> state`` function in a manual `jax.shard_map`. 

2341 

2342 Uses `state.config.mesh` (static). No-op when the mesh is `None`. The keys 

2343 input is sharded across ``'chains'`` when the state is multichain and 

2344 ``'chains'`` is in the mesh; otherwise the keys are replicated. State 

2345 leaves are sharded according to their `chains`/`data` field metadata. The 

2346 output sharding matches the input sharding. 

2347 """ 

2348 

2349 @wraps(fun) 

2350 def wrapped( 

2351 key: Key[Array, ''] | Key[Array, ' num_chains'], state: StateT 

2352 ) -> StateT: 

2353 mesh = state.config.mesh 

2354 if mesh is None: 

2355 return fun(key, state) 

2356 

2357 if state.has_chains and 'chains' in mesh.axis_names: 

2358 key_spec = PartitionSpec('chains') 

2359 else: 

2360 key_spec = PartitionSpec() 

2361 

2362 state_specs = partition_specs(state, mesh) 

2363 

2364 mapped = shard_map( 

2365 fun, 

2366 mesh=mesh, 

2367 in_specs=(key_spec, state_specs), 

2368 out_specs=state_specs, 

2369 **get_shard_map_patch_kwargs(), 

2370 ) 

2371 return mapped(key, state) 

2372 

2373 return wrapped 

2374 

2375 

2376def vmap_chains( 

2377 fun: Callable[[Key[Array, ''], StateT], StateT], 

2378) -> Callable[[Key[Array, ' num_chains'] | Key[Array, ''], StateT], StateT]: 

2379 """Vmap a ``(key, state) -> state`` function over chain axes. 

2380 

2381 When the state is multichain, `keys` must have a leading chain axis and 

2382 `fun` is vmapped over it together with the chain axes of `state`. For 

2383 single-chain states, the function is called unchanged. 

2384 """ 

2385 

2386 @wraps(fun) 

2387 def wrapped( 

2388 keys: Key[Array, ' num_chains'] | Key[Array, ''], state: StateT 

2389 ) -> StateT: 

2390 if not state.has_chains: 

2391 return fun(keys, state) 

2392 state_axes = chain_vmap_axes(state) 

2393 vmapped_fun = vmap(fun, in_axes=(0, state_axes), out_axes=state_axes) 

2394 return vmapped_fun(keys, state) 

2395 

2396 return wrapped 

2397 

2398 

2399def used_trees_mask(forest: Forest) -> Bool[Array, '*chains num_trees'] | None: 

2400 """Mark the trees in use, `None` if all are, assuming `CHAIN_AXIS` is 0.""" 

2401 if forest.used_trees is None: 

2402 return None 

2403 else: 

2404 *_, num_trees, _ = forest.var_tree.shape 

2405 trees = minimal_unsigned_arange(num_trees) 

2406 return trees < forest.used_trees[..., None] 

2407 

2408 

2409def num_used_trees(forest: Forest) -> Int32[Array, '*chains'] | int: 

2410 """Return the number of trees in use, see `Forest.used_trees`.""" 

2411 if forest.used_trees is None: 

2412 *_, num_trees, _ = forest.var_tree.shape 

2413 return num_trees 

2414 else: 

2415 return forest.used_trees 

2416 

2417 

2418def leaf_prior_precision(forest: Forest) -> Float32[Array, ''] | Float32[Array, 'k k']: 

2419 """Return the prior precision of a leaf of a forest without a chain axis. 

2420 

2421 See `Forest.sum_trees_prior_cov_inv`. Without trees in use it is the one of 

2422 a single tree, such that an infinite precision does not turn into nan. 

2423 """ 

2424 used_trees = jnp.maximum(num_used_trees(forest), 1) 

2425 return forest.sum_trees_prior_cov_inv.value * used_trees 

2426 

2427 

2428def outcome_target(state: State) -> Float32[Array, ' n'] | Float32[Array, 'k n']: 

2429 """Return the outcome the forest fits, with the latent one for binary components.""" 

2430 if state.binary_indices is not None: 

2431 assert state.z is not None 

2432 return state.y.at[state.binary_indices, :].set(state.z, unique_indices=True) 

2433 elif state.z is not None: 

2434 return state.z 

2435 else: 

2436 return state.y 

2437 

2438 

2439class ShardMapPatchKwargs(TypedDict, total=False): 

2440 check_vma: bool 

2441 

2442 

2443def get_shard_map_patch_kwargs() -> ShardMapPatchKwargs: 

2444 # bug: jax 0.8.1-0.8.2: vmap(shard_map(psum)), jax#34249; the 

2445 # jax_disable_vmap_shmap_error config did not work. 

2446 

2447 # WORKAROUND(jax<=0.8.2): remove this whole function when jax > 0.8.2 

2448 buggy = ('0.8.1', '0.8.2') 

2449 if jax.__version__ in buggy: 2449 ↛ 2450line 2449 didn't jump to line 2450 because the condition on line 2449 was never true

2450 return {'check_vma': False} 

2451 return {}