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

816 statements  

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

1# bartz/src/bartz/mcmcstep/_step.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"""Implement `step`, `step_trees`, and the accept-reject logic.""" 

26 

27import math 

28from dataclasses import replace 

29from functools import partial 

30from typing import Literal 

31 

32from equinox import AbstractVar 

33from jax import lax, named_call, random, tree, vmap 

34from jax import numpy as jnp 

35from jax.nn import log_softmax 

36from jax.scipy.special import logsumexp 

37from jaxtyping import ( 

38 Array, 

39 Bool, 

40 Float, 

41 Float32, 

42 Int32, 

43 Integer, 

44 Key, 

45 Shaped, 

46 UInt, 

47 UInt32, 

48) 

49 

50from bartz._jaxext import ( 

51 InPlace, 

52 Module, 

53 cpu_barrier, 

54 field, 

55 float32_matmuls, 

56 forbid_x64, 

57 jit, 

58 minimal_unsigned_arange, 

59 sequential_vmap, 

60 sliced_map, 

61 solve_triangular, 

62 split, 

63 truncated_normal_onesided, 

64 variable_length_scan, 

65 variable_length_update, 

66 vmap_max, 

67) 

68from bartz._jaxext.random import categorical, loggamma, poisson 

69from bartz.grove import is_leaf_used, node_to_leaf_index, var_histogram 

70from bartz.mcmcstep._moves import Moves, propose_moves, split_range 

71from bartz.mcmcstep._reduction import ( 

72 AutoOneHotOrPopcountReduction, 

73 PopcountReduction, 

74 ReductionConfig, 

75) 

76from bartz.mcmcstep._state import ( 

77 DiagWishart, 

78 Forest, 

79 State, 

80 StepConfig, 

81 Wishart, 

82 chol_with_gersh, 

83 default_parallel_block_size, 

84 leaf_prior_precision, 

85 num_used_trees, 

86 parallel_min_blocks, 

87 round_to_pow2, 

88 scaled_error_cov_inv, 

89 shard_map_state, 

90 split_key_for_chains, 

91 used_trees_mask, 

92 vmap_chains, 

93) 

94 

95 

96@jit(donate_argnums=(1,)) 

97@forbid_x64 

98@split_key_for_chains 

99@shard_map_state 

100@vmap_chains 

101@float32_matmuls 

102def step(key: Key[Array, ''], state: State) -> State: 

103 """ 

104 Do one MCMC step. 

105 

106 Parameters 

107 ---------- 

108 key 

109 A jax random key. 

110 state 

111 A BART mcmc state, as created by `init`. 

112 

113 Returns 

114 ------- 

115 The new BART mcmc state. 

116 

117 Notes 

118 ----- 

119 The memory of the input state is re-used for the output state, so the input 

120 state can not be used any more after calling `step`. All this applies 

121 outside of `jax.jit`. 

122 """ 

123 keys = split(key, 5) 

124 

125 state = step_resid_inexact_integral(state) 

126 state = step_z(keys.pop(), state) 

127 state = step_trees(keys.pop(), state) 

128 

129 state = step_sum_trees_prior_cov_inv(keys.pop(), state) 

130 state = step_error_cov_inv(keys.pop(), state) 

131 state = step_sparse(keys.pop(), state) 

132 return step_config(state) 

133 

134 

135@named_call 

136def step_resid_inexact_integral(state: State) -> State: 

137 """Accumulate the mean square of the residuals subject to rounding. 

138 

139 Adds to `State.resid_inexact_integral` the current mean square of the 

140 residuals at or above ``2^(leaf_quantization+1)`` (in 

141 `State.resid_eff_scale` units), below which the running residual updates 

142 are exact because the `State.resid` dtype spacing still matches the leaf 

143 quantum. Without quantization every update rounds and all residuals count. 

144 """ 

145 # filter away residuals below quantization threshold 

146 q = state.config.leaf_quantization 

147 resid = state.resid 

148 if q is None: 

149 inexact = resid 

150 else: 

151 # the quantization grid follows `resid_eff_scale` while `resid` stays 

152 # in `resid_unit` units, so the threshold carries their (power of 

153 # two, hence exact) ratio; it is cast to the resid dtype to keep the 

154 # comparison from widening the n-sized array 

155 exact_below = 2.0 ** (q + 1) * state.resid_eff_scale / state.resid_unit 

156 inexact = jnp.where( 

157 jnp.abs(resid) >= exact_below[..., None].astype(resid.dtype), resid, 0 

158 ) 

159 

160 # mask missing datapoints if any 

161 if state.inv_sdev_scale is not None: 

162 inexact = jnp.where(state.inv_sdev_scale != 0, inexact, 0) 

163 

164 # compute mean square residuals above threshold 

165 ms = jnp.einsum( 

166 '...n,...n->...', inexact, inexact, preferred_element_type=jnp.float32 

167 ) 

168 if state.config.data_sharded: 

169 ms = lax.psum(ms, 'data') 

170 ms /= jnp.maximum(state.n_non_missing, 1) 

171 

172 # only the trees in use update the residuals; weight each step here, as 

173 # `used_trees` may change from one step to the next 

174 if state.forest.used_trees is not None: 

175 num_trees, _ = state.forest.var_tree.shape 

176 ms *= state.forest.used_trees / num_trees 

177 

178 # accumulate to the running sum 

179 return replace(state, resid_inexact_integral=state.resid_inexact_integral + ms) 

180 

181 

182@named_call 

183def step_trees(key: Key[Array, ''], state: State) -> State: 

184 """ 

185 Forest sampling step of BART MCMC. 

186 

187 Parameters 

188 ---------- 

189 key 

190 A jax random key. 

191 state 

192 A BART mcmc state, as created by `init`. 

193 

194 Returns 

195 ------- 

196 The new BART mcmc state. 

197 

198 Notes 

199 ----- 

200 This function zeroes the proposal counters. 

201 """ 

202 keys = split(key) 

203 moves = propose_moves(keys.pop(), state.forest) 

204 return accept_moves_and_sample_leaves(keys.pop(), state, moves) 

205 

206 

207def random_tree_order(key: Key[Array, ''], forest: Forest) -> UInt[Array, ' num_trees']: 

208 """Draw a random order to visit the trees, with the trees in use first.""" 

209 num_trees, _ = forest.var_tree.shape 

210 trees = minimal_unsigned_arange(num_trees) 

211 order = random.permutation(key, trees) 

212 if forest.used_trees is not None: 

213 order = order[jnp.argsort(order >= forest.used_trees, stable=True)] 

214 return order 

215 

216 

217@named_call 

218def accept_moves_and_sample_leaves( 

219 key: Key[Array, ''], state: State, moves: Moves 

220) -> State: 

221 """ 

222 Accept or reject the proposed moves and sample the new leaf values. 

223 

224 Parameters 

225 ---------- 

226 key 

227 A jax random key. 

228 state 

229 A valid BART mcmc state. 

230 moves 

231 The proposed moves, see `propose_moves`. 

232 

233 Returns 

234 ------- 

235 A new (valid) BART mcmc state. 

236 """ 

237 keys = split(key) 

238 pso = accept_moves_parallel_stage(keys.pop(), state, moves) 

239 state, moves = accept_moves_sequential_stage(keys.pop(), pso) 

240 return accept_moves_final_stage(state, moves) 

241 

242 

243class Counts(Module): 

244 """Number of datapoints in the nodes involved in proposed moves for each tree.""" 

245 

246 lrt: UInt[Array, '*num_trees 3'] 

247 """Number of datapoints in the left child, right child, and parent 

248 (``= left + right``), stacked along the trailing axis.""" 

249 

250 

251class PreLkV(Module): 

252 """Non-sequential terms of the likelihood ratio for each tree. 

253 

254 These terms are derived from the leaf precompute terms (`PreLf`) gathered 

255 at the nodes involved in each move. The terms for the left child, right 

256 child, and their join (the parent node) are stacked along the axis right 

257 after the tree axis. Each term is, in the univariate case, the scalar 

258 

259 ``error_cov_inv^2 / (leaf_prior_cov_inv + n * error_cov_inv)``. 

260 

261 In the multivariate homoskedastic or scalar-error-scale case, this is the matrix term 

262 

263 ``error_cov_inv @ inv(leaf_prior_cov_inv + n * error_cov_inv) @ error_cov_inv``. 

264 

265 In the multivariate case with per-component error scales, this is instead 

266 

267 ``chol(leaf_prior_cov_inv + n * error_cov_inv)`` 

268 

269 ``n`` is the number of datapoints in the node, or the likelihood precision 

270 scale in the heteroskedastic case. 

271 """ 

272 

273 # `log_sqrt_term` is declared before `lrt` so its single (union-free) 

274 # annotation binds the variadic `*num_trees` axis first; otherwise the 

275 # runtime typechecker can greedily mis-bind `*num_trees` against the `k` 

276 # axis of the `... | ... k k` union (the multivariate and univariate 

277 # layouts are rank-ambiguous). 

278 log_sqrt_term: Float32[Array, '*num_trees'] 

279 """The logarithm of the square root term of the likelihood ratio.""" 

280 

281 lrt: Float32[Array, '*num_trees 3'] | Float32[Array, '*num_trees 3 k k'] 

282 """Scaled full conditional variance, scaled covariance, or precision 

283 cholesky, for the left child, right child, and their join.""" 

284 

285 

286class PreLf(Module): 

287 """Pre-computed terms used to sample leaves from their posterior. 

288 

289 These terms can be computed in parallel across trees. 

290 

291 For each tree and leaf, the terms are scalars in the univariate case 

292 (`PreLfUV`), and matrices/vectors in the multivariate case (`PreLfMV`, 

293 `PreLfMVHet`). The leaves are indexed like `bartz.mcmcstep.Forest.leaf_tree`, 

294 followed by the parent node of the move, which shares its index with its 

295 left child. 

296 

297 Abstract base: the layouts differ in rank, so they live in concrete 

298 subclasses with union-free annotations; a single class carrying a shape 

299 union would make the greedy variadic mis-bind against the ``k`` axes under 

300 the runtime typechecker. The concrete class also tags the meaning of 

301 `mean_factor`, which drives the dispatch in `precompute_likelihood_terms` 

302 and in the sequential stage. The ``num_trees`` axis is variadic so the same 

303 annotations also match a per-element layout if vmapped over trees. 

304 """ 

305 

306 mean_factor: AbstractVar[ 

307 Float32[Array, '*num_trees max_num_leaves_plus_1'] 

308 | Float32[Array, '*num_trees k k max_num_leaves_plus_1'] 

309 ] 

310 """The factor to be right-multiplied by the sum of the scaled residuals to 

311 obtain the posterior mean.""" 

312 

313 centered_leaves: AbstractVar[ 

314 Float32[Array, '*num_trees max_num_leaves_plus_1'] 

315 | Float32[Array, '*num_trees k max_num_leaves_plus_1'] 

316 ] 

317 """The mean-zero normal values to be added to the posterior mean to 

318 obtain the posterior leaf samples.""" 

319 

320 

321class PreLfUV(PreLf): 

322 """`PreLf` for the univariate case.""" 

323 

324 mean_factor: Float32[Array, '*num_trees max_num_leaves_plus_1'] 

325 """``error_cov_inv / prec``, where ``prec`` is the posterior precision of 

326 the leaf.""" 

327 

328 centered_leaves: Float32[Array, '*num_trees max_num_leaves_plus_1'] 

329 """Zero-mean normal draws with the posterior variance of each leaf.""" 

330 

331 

332class PreLfMV(PreLf): 

333 """`PreLf` for the multivariate homoskedastic or scalar-error-scale case.""" 

334 

335 mean_factor: Float32[Array, '*num_trees k k max_num_leaves_plus_1'] 

336 """``error_cov_inv @ inv(prec)``, where ``prec`` is the posterior precision 

337 of the leaf.""" 

338 

339 centered_leaves: Float32[Array, '*num_trees k max_num_leaves_plus_1'] 

340 """Zero-mean normal draws with the posterior covariance of each leaf.""" 

341 

342 logdet_prec: Float32[Array, '*num_trees max_num_leaves_plus_1'] 

343 """The log-determinant of the posterior precision of each leaf.""" 

344 

345 

346class PreLfMVHet(PreLf): 

347 """`PreLf` for the multivariate case with per-component error scales.""" 

348 

349 mean_factor: Float32[Array, '*num_trees k k max_num_leaves_plus_1'] 

350 """The lower Cholesky factor of the posterior precision of each leaf; the 

351 mean solve happens downstream in the sequential stage.""" 

352 

353 centered_leaves: Float32[Array, '*num_trees k max_num_leaves_plus_1'] 

354 """Zero-mean normal draws with the posterior covariance of each leaf.""" 

355 

356 

357class ParallelStageOut(Module): 

358 """The output of `accept_moves_parallel_stage`.""" 

359 

360 state: State 

361 """A partially updated BART mcmc state.""" 

362 

363 moves: Moves 

364 """The proposed moves, with `partial_ratio` set to `None` and 

365 `log_trans_prior_ratio` set to its final value.""" 

366 

367 # `num_trees` stays a fixed (non-variadic) axis: `ParallelStageOut` is always 

368 # built with the tree axis present (never per tree under vmap), so the union 

369 # is disambiguated by rank/dtype and needs no anchor (cf. `PreLf`). 

370 prec_trees: ( 

371 Float32[Array, 'num_trees max_num_leaves'] 

372 | UInt32[Array, 'num_trees max_num_leaves'] 

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

374 ) 

375 """The likelihood precision scale in each leaf, in the same version of 

376 each tree as the leaf indices.""" 

377 

378 prelkv: PreLkV 

379 """Object with pre-computed terms of the likelihood ratios.""" 

380 

381 prelf: PreLf 

382 """Object with pre-computed terms of the leaf samples.""" 

383 

384 

385@named_call 

386def accept_moves_parallel_stage( 

387 key: Key[Array, ''], state: State, moves: Moves 

388) -> ParallelStageOut: 

389 """ 

390 Pre-compute quantities used to accept moves, in parallel across trees. 

391 

392 Parameters 

393 ---------- 

394 key 

395 A jax random key. 

396 state 

397 A BART mcmc state. 

398 moves 

399 The proposed moves, see `propose_moves`. 

400 

401 Returns 

402 ------- 

403 An object with all that could be done in parallel. 

404 """ 

405 # apply the prunes pending from the previous step to the leaf indices, 

406 # then, where the new move is grow, modify the state like the move was 

407 # accepted; update the related caches at the leaves involved in the moves 

408 updated = update_leaf_indices_and_related_caches(state, moves) 

409 state = replace( 

410 state, 

411 forest=replace( 

412 state.forest, 

413 var_tree=moves.var_tree, 

414 leaf_indices=updated.leaf_indices, 

415 leaf_tree=adapt_leaf_trees_to_grow_indices(state.forest.leaf_tree, moves), 

416 count_tree=updated.count_tree, 

417 prec_tree=updated.prec_tree, 

418 ), 

419 ) 

420 move_counts = updated.move_counts 

421 

422 # affluence of the nodes touched by each move: whether they would be 

423 # growable as leaves (admissible rule + enough datapoints). The children 

424 # must also lie within the heap, i.e. not be at the bottom level; the 

425 # parent always does. These feed the transition ratio and the final 

426 # `affluence_tree` update. 

427 _, max_num_leaves = state.forest.var_tree.shape 

428 lrt_affluent = (moves.lrt_nodes < max_num_leaves) & moves.lrt_growable 

429 if state.forest.min_points_per_decision_node is not None: 

430 assert move_counts is not None 

431 lrt_affluent &= move_counts.lrt >= state.forest.min_points_per_decision_node 

432 moves = replace(moves, lrt_affluent=lrt_affluent) 

433 

434 # veto grove move if new leaves don't have enough datapoints 

435 if state.forest.min_points_per_leaf is not None: 

436 assert move_counts is not None 

437 moves = replace( 

438 moves, 

439 allowed=moves.allowed 

440 & jnp.all( 

441 move_counts.lrt[..., :2] >= state.forest.min_points_per_leaf, axis=-1 

442 ), 

443 ) 

444 

445 # the likelihood precision scale in each leaf is the number of datapoints 

446 # without error scales 

447 if state.prec_scale is None: 

448 assert move_counts is not None 

449 prec_trees = state.forest.count_tree 

450 parent_prec = move_counts.lrt[..., 2] 

451 else: 

452 prec_trees = state.forest.prec_tree 

453 parent_prec = updated.move_prec 

454 assert prec_trees is not None 

455 assert parent_prec is not None 

456 

457 # compute some missing information about moves 

458 moves = complete_ratio(moves, state.forest.p_nonterminal) 

459 save_ratios = state.forest.log_likelihood is not None 

460 state = replace( 

461 state, 

462 forest=replace( 

463 state.forest, 

464 grow_prop_count=jnp.sum(moves.grow), 

465 prune_prop_count=jnp.sum(moves.allowed & ~moves.grow), 

466 log_trans_prior=moves.log_trans_prior_ratio if save_ratios else None, 

467 ), 

468 ) 

469 

470 # `prec_trees` and the per-leaf residual sums are in stored `prec_scale` 

471 # units, so their common `inv_sdev_unit ** 2` factor is folded into the 

472 # error precision once here instead 

473 error_cov_inv = scaled_error_cov_inv(state) 

474 leaf_prior_cov_inv = leaf_prior_precision(state.forest) 

475 

476 prelf = precompute_leaf_terms( 

477 key, 

478 # the parent node of each move is not a leaf in the same version of the 

479 # tree as its children, so it goes after the leaves 

480 jnp.concatenate([prec_trees, parent_prec[..., None]], axis=-1), 

481 error_cov_inv, 

482 leaf_prior_cov_inv, 

483 ) 

484 prelkv = precompute_likelihood_terms( 

485 error_cov_inv, leaf_prior_cov_inv, prelf, moves 

486 ) 

487 

488 return ParallelStageOut( 

489 state=state, moves=moves, prec_trees=prec_trees, prelkv=prelkv, prelf=prelf 

490 ) 

491 

492 

493class RelatedCaches(Module): 

494 """The caches related to `bartz.mcmcstep.Forest.leaf_indices`.""" 

495 

496 count_tree: UInt32[Array, 'num_trees max_num_leaves'] | None 

497 """See `bartz.mcmcstep.Forest.count_tree`.""" 

498 

499 move_counts: Counts | None 

500 """The number of datapoints in the nodes involved in the moves, `None` if 

501 not counted.""" 

502 

503 prec_tree: ( 

504 Float32[Array, 'num_trees max_num_leaves'] 

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

506 | None 

507 ) 

508 """See `bartz.mcmcstep.Forest.prec_tree`.""" 

509 

510 move_prec: Float32[Array, ' num_trees'] | Float32[Array, 'num_trees k k'] | None 

511 """The likelihood precision scale in the parent node of each move, `None` 

512 without `prec_tree`.""" 

513 

514 

515class LeafIndicesAndRelatedCaches(RelatedCaches): 

516 """The output of `update_leaf_indices_and_related_caches`.""" 

517 

518 leaf_indices: UInt[Array, 'num_trees n'] 

519 """The leaf indices in the deeper version of each tree (post-GROW, 

520 pre-PRUNE).""" 

521 

522 

523class LeafIndicesInputs(Module): 

524 """The inputs to `update_leaf_indices_and_related_caches` that are separate for each tree.""" 

525 

526 to_prune: Bool[Array, ' num_trees'] 

527 """See `bartz.mcmcstep.Forest.to_prune`.""" 

528 

529 move_node: Int32[Array, ' num_trees'] 

530 """See `bartz.mcmcstep.Forest.move_node`.""" 

531 

532 moves: Moves 

533 """The proposed moves, see `propose_moves`.""" 

534 

535 caches: RelatedCaches 

536 """The caches to update.""" 

537 

538 

539@named_call 

540def update_leaf_indices_and_related_caches( 

541 state: State, moves: Moves 

542) -> LeafIndicesAndRelatedCaches: 

543 """ 

544 Update the leaf indices and related caches to apply the moves. 

545 

546 Apply the prunes pending from the previous step and the grow moves to the 

547 leaf indices, and to the cached number of datapoints per leaf and its 

548 version weighted by error precision scale. The trees not in use are skipped 

549 if the trees are processed in blocks, see 

550 `bartz.mcmcstep.StepConfig.parallel_block_size`. 

551 

552 Parameters 

553 ---------- 

554 state 

555 A BART mcmc state. 

556 moves 

557 The proposed moves, see `propose_moves`. 

558 

559 Returns 

560 ------- 

561 The updated leaf indices and caches, for the deeper version of each tree (post-GROW, pre-PRUNE). 

562 """ 

563 forest = state.forest # alias for brevity 

564 

565 # whether to count datapoints per leaf 

566 count = ( 

567 forest.min_points_per_decision_node is not None 

568 or forest.min_points_per_leaf is not None 

569 or state.prec_scale is None 

570 ) 

571 

572 # These two functions take all the trees, or a block of them. A tree not in 

573 # use has no pending prune and no allowed move, so they have no effect on 

574 # it. 

575 

576 def update_leaf_indices( 

577 leaf_indices: UInt[Array, 'trees n'], xs: LeafIndicesInputs 

578 ) -> UInt[Array, 'trees n']: 

579 """Apply pending prunes from last MCMC step, then apply proposed grow moves.""" 

580 leaf_indices = apply_moves_to_leaf_indices( 

581 leaf_indices, xs.to_prune, xs.move_node 

582 ) 

583 return apply_grow_to_indices(xs.moves, leaf_indices, state.X) 

584 

585 def compute_caches( 

586 leaf_indices: UInt[Array, 'trees n'], xs: LeafIndicesInputs 

587 ) -> RelatedCaches: 

588 """Update likelihood precision caches.""" 

589 caches = xs.caches 

590 if count: 

591 assert caches.count_tree is not None 

592 count_tree = apply_moves_to_leaf_sums( 

593 caches.count_tree, xs.to_prune, xs.move_node 

594 ) 

595 count_tree, move_counts = compute_count_trees( 

596 count_tree, leaf_indices, xs.moves, state.config 

597 ) 

598 caches = replace(caches, count_tree=count_tree, move_counts=move_counts) 

599 

600 if state.prec_scale is not None: 

601 assert caches.prec_tree is not None 

602 prec_tree = apply_moves_to_leaf_sums( 

603 caches.prec_tree, xs.to_prune, xs.move_node 

604 ) 

605 prec_tree, move_prec = compute_prec_trees( 

606 prec_tree, 

607 state.prec_scale, 

608 leaf_indices, 

609 xs.moves, 

610 caches.move_counts, 

611 config=state.config, 

612 ) 

613 caches = replace(caches, prec_tree=prec_tree, move_prec=move_prec) 

614 

615 return caches 

616 

617 old_caches = RelatedCaches(forest.count_tree, None, forest.prec_tree, None) 

618 xs = LeafIndicesInputs(forest.to_prune, forest.move_node, moves, old_caches) 

619 

620 def run( 

621 *, block_size: int | None 

622 ) -> tuple[UInt[Array, 'num_trees n'], RelatedCaches]: 

623 """Compute everything `block_size` trees at a time.""" 

624 return variable_length_update( 

625 update_leaf_indices, 

626 compute_caches, 

627 forest.leaf_indices, 

628 xs, 

629 forest.used_trees, 

630 block_size=block_size, 

631 ) 

632 

633 def run_default( 

634 platform: Literal['cpu', 'gpu'], 

635 ) -> tuple[UInt[Array, 'num_trees n'], RelatedCaches]: 

636 """Compute everything in blocks of the default size for the platform.""" 

637 assert forest.used_trees is not None 

638 num_trees, n = forest.leaf_indices.shape 

639 block_size = default_parallel_block_size(num_trees, n, platform) 

640 in_blocks = partial(run, block_size=block_size) 

641 if platform == 'cpu' and block_size < num_trees: 

642 # pick the faster of the two at run time; with the branches the 

643 # other way around, or with `lax.cond` on some versions of jax, xla 

644 # would copy the leaf indices, see jax issue #39449 

645 at_once = cpu_at_once_is_faster(forest.used_trees, num_trees, block_size) 

646 return lax.switch( 

647 at_once.astype(jnp.int32), (in_blocks, partial(run, block_size=None)) 

648 ) 

649 else: 

650 return in_blocks() 

651 

652 used = used_trees_mask(forest) 

653 if used is None: 

654 leaf_indices, caches = run(block_size=None) 

655 

656 else: 

657 block_size = state.config.parallel_block_size 

658 if block_size is None: 

659 leaf_indices, caches = lax.platform_dependent( 

660 cpu=partial(run_default, 'cpu'), cuda=partial(run_default, 'gpu') 

661 ) 

662 else: 

663 leaf_indices, caches = run(block_size=block_size) 

664 

665 # the caches come out zero for the trees not in use, restore them 

666 count_tree, prec_tree = tree.map( 

667 lambda new, old: jnp.where( 

668 used.reshape(-1, *[1] * (new.ndim - 1)), new, old 

669 ), 

670 (caches.count_tree, caches.prec_tree), 

671 (forest.count_tree, forest.prec_tree), 

672 ) 

673 caches = replace(caches, count_tree=count_tree, prec_tree=prec_tree) 

674 

675 return LeafIndicesAndRelatedCaches( 

676 leaf_indices=leaf_indices, 

677 count_tree=caches.count_tree, 

678 move_counts=caches.move_counts, 

679 prec_tree=caches.prec_tree, 

680 move_prec=caches.move_prec, 

681 ) 

682 

683 

684def cpu_at_once_is_faster( 

685 used_trees: Int32[Array, ''], num_trees: int, block_size: int 

686) -> Bool[Array, '']: 

687 """Tell if on cpu updating all the trees at once is faster than the blocks in use.""" 

688 used_blocks = -(-vmap_max(used_trees) // block_size) 

689 return used_blocks * parallel_min_blocks('cpu') > num_trees // block_size 

690 

691 

692@named_call 

693def apply_grow_to_indices( 

694 moves: Moves, leaf_indices: UInt[Array, 'num_trees n'], X: UInt[Array, 'p n'] 

695) -> UInt[Array, 'num_trees n']: 

696 """ 

697 Update the leaf indices to apply a grow move. 

698 

699 Parameters 

700 ---------- 

701 moves 

702 The proposed moves, see `propose_moves`. 

703 leaf_indices 

704 The index of the leaf each datapoint falls into, with the prunes 

705 pending from the previous step already applied. 

706 X 

707 The predictors matrix. 

708 

709 Returns 

710 ------- 

711 The updated leaf indices. 

712 

713 Notes 

714 ----- 

715 The datapoints that go to the left child keep the index of the leaf, see 

716 `bartz.grove.node_to_leaf_index`. 

717 """ 

718 return _apply_grow_to_indices(moves, leaf_indices, X) 

719 

720 

721@partial(vmap, in_axes=(0, 0, None)) 

722def _apply_grow_to_indices( 

723 moves: Moves, leaf_indices: UInt[Array, ' n'], X: UInt[Array, 'p n'] 

724) -> UInt[Array, ' n']: 

725 """Implement `apply_grow_to_indices`.""" 

726 left, right = moves.lr_leaves.astype(leaf_indices.dtype) 

727 x: UInt[Array, ' n'] = X[moves.grow_var, :] 

728 go_right = moves.grow & (x >= moves.grow_split) 

729 return jnp.where(go_right & (leaf_indices == left), right, leaf_indices) 

730 

731 

732def append_total(lr: Shaped[Array, '*k_k 2']) -> Shaped[Array, '*k_k 3']: 

733 """Stack (left, right) values with their total, left + right.""" 

734 total = lr[..., 0] + lr[..., 1] 

735 return jnp.concatenate([lr, total[..., None]], axis=-1) 

736 

737 

738def set_leaf_pair( 

739 leaf_tree: Float32[Array, '*k max_num_leaves'], 

740 value: Float32[Array, '*k 1'], 

741 where: Bool[Array, ''], 

742 indices: Int32[Array, ' 2'], 

743) -> Float32[Array, '*k max_num_leaves']: 

744 """Set the leaves at two indices to a value, if `where`.""" 

745 # on gpu a scatter is a kernel of its own, while xla merges the selects 

746 # with the operations around them; on cpu the scatter is faster with deep 

747 # trees 

748 return lax.platform_dependent( 

749 leaf_tree, 

750 value, 

751 where, 

752 indices, 

753 cpu=set_leaf_pair_scatter, 

754 default=set_leaf_pair_select, 

755 ) 

756 

757 

758def set_leaf_pair_scatter( 

759 leaf_tree: Float32[Array, '*k max_num_leaves'], 

760 value: Float32[Array, '*k 1'], 

761 where: Bool[Array, ''], 

762 indices: Int32[Array, ' 2'], 

763) -> Float32[Array, '*k max_num_leaves']: 

764 """Implement `set_leaf_pair` with a scatter.""" 

765 *_, max_num_leaves = leaf_tree.shape 

766 return leaf_tree.at[..., jnp.where(where, indices, max_num_leaves)].set(value) 

767 

768 

769def set_leaf_pair_select( 

770 leaf_tree: Float32[Array, '*k max_num_leaves'], 

771 value: Float32[Array, '*k 1'], 

772 where: Bool[Array, ''], 

773 indices: Int32[Array, ' 2'], 

774) -> Float32[Array, '*k max_num_leaves']: 

775 """Implement `set_leaf_pair` with elementwise selects.""" 

776 *_, max_num_leaves = leaf_tree.shape 

777 index = jnp.arange(max_num_leaves) 

778 first, second = indices 

779 return jnp.where(where & ((index == first) | (index == second)), value, leaf_tree) 

780 

781 

782def _compute_count_or_prec_trees( 

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

784 trees: UInt32[Array, 'num_trees max_num_leaves'] 

785 | Float32[Array, 'num_trees max_num_leaves'] 

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

787 leaf_indices: UInt[Array, 'num_trees n'], 

788 moves: Moves, 

789 counts: Counts | None, 

790 *, 

791 config: StepConfig, 

792) -> ( 

793 tuple[UInt32[Array, 'num_trees max_num_leaves'], UInt32[Array, 'num_trees 3']] 

794 | tuple[Float32[Array, 'num_trees max_num_leaves'], Float32[Array, 'num_trees 3']] 

795 | tuple[ 

796 Float32[Array, 'num_trees k k max_num_leaves'], 

797 Float32[Array, 'num_trees k k 3'], 

798 ] 

799): 

800 """Implement `compute_count_trees` and `compute_prec_trees`.""" 

801 

802 def all_trees() -> ( 

803 tuple[UInt32[Array, 'num_trees max_num_leaves'], UInt32[Array, 'num_trees 3']] 

804 | tuple[ 

805 Float32[Array, 'num_trees max_num_leaves'], Float32[Array, 'num_trees 3'] 

806 ] 

807 | tuple[ 

808 Float32[Array, 'num_trees k k max_num_leaves'], 

809 Float32[Array, 'num_trees k k 3'], 

810 ] 

811 ): 

812 compute = vmap( 

813 partial(_compute_count_or_prec_tree, config=config), 

814 in_axes=(None, 0, 0, 0, 0), 

815 ) 

816 return compute(prec_scale, trees, leaf_indices, moves, counts) 

817 

818 # the trees are batched on cpu to bound the temporaries of the reduction, 

819 # which the popcount count does not produce 

820 popcount = prec_scale is None and isinstance( 

821 config.count_reduction_config, PopcountReduction | AutoOneHotOrPopcountReduction 

822 ) 

823 if config.prec_count_num_trees is None or popcount: 

824 return all_trees() 

825 

826 batch_size = config.prec_count_num_trees 

827 

828 def compute( 

829 args: tuple[ 

830 UInt32[Array, ' max_num_leaves'] 

831 | Float32[Array, ' max_num_leaves'] 

832 | Float32[Array, 'k k max_num_leaves'], 

833 UInt[Array, ' n'], 

834 Moves, 

835 Counts | None, 

836 ], 

837 ) -> ( 

838 tuple[UInt32[Array, ' max_num_leaves'], UInt32[Array, ' 3']] 

839 | tuple[Float32[Array, ' max_num_leaves'], Float32[Array, ' 3']] 

840 | tuple[Float32[Array, 'k k max_num_leaves'], Float32[Array, 'k k 3']] 

841 ): 

842 tree, leaf_indices, moves, counts = args 

843 return _compute_count_or_prec_tree( 

844 prec_scale, tree, leaf_indices, moves, counts, config=config 

845 ) 

846 

847 def tree_batches() -> ( 

848 tuple[UInt32[Array, 'num_trees max_num_leaves'], UInt32[Array, 'num_trees 3']] 

849 | tuple[ 

850 Float32[Array, 'num_trees max_num_leaves'], Float32[Array, 'num_trees 3'] 

851 ] 

852 | tuple[ 

853 Float32[Array, 'num_trees k k max_num_leaves'], 

854 Float32[Array, 'num_trees k k 3'], 

855 ] 

856 ): 

857 # sliced_map instead of lax.map because under the chain vmap lax.map's 

858 # reshape of the tree axis becomes a transpose of `leaf_indices` that 

859 # xla materializes in full (cf. `SeqStageInAllTrees.leaf_indices`) 

860 return sliced_map( 

861 compute, (trees, leaf_indices, moves, counts), batch_size=batch_size 

862 ) 

863 

864 # the tree batching bounds the reduction temporaries on cpu; on gpu those 

865 # fuse anyway 

866 return lax.platform_dependent(cpu=tree_batches, cuda=all_trees) 

867 

868 

869def _compute_count_or_prec_tree( 

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

871 tree: UInt32[Array, ' max_num_leaves'] 

872 | Float32[Array, ' max_num_leaves'] 

873 | Float32[Array, 'k k max_num_leaves'], 

874 leaf_indices: UInt[Array, ' n'], 

875 moves: Moves, 

876 counts: Counts | None, 

877 *, 

878 config: StepConfig, 

879) -> ( 

880 tuple[UInt32[Array, ' max_num_leaves'], UInt32[Array, ' 3']] 

881 | tuple[Float32[Array, ' max_num_leaves'], Float32[Array, ' 3']] 

882 | tuple[Float32[Array, 'k k max_num_leaves'], Float32[Array, 'k k 3']] 

883): 

884 """Update the cached count or precision tree for a single tree.""" 

885 *_, max_num_leaves = tree.shape 

886 left, right = moves.lr_leaves 

887 

888 # the cached tree is valid at the leaves, and the move only changes the 

889 # values at the leaves it involves, so update them alone. The total is 

890 # cached: at the left child if the move grows, because it takes over the 

891 # index of its parent, split in the children if the move prunes. 

892 cached = tree.at[..., moves.lr_leaves].get(mode='fill', fill_value=0) 

893 cached_total = jnp.where( 

894 moves.grow, cached[..., 0], cached[..., 0] + cached[..., 1] 

895 ) 

896 

897 if prec_scale is None: 

898 # count only the right child and derive the left one. This is exact in 

899 # integers, and the one-bin reduction fuses better than a two-bin one. 

900 right_count = config.count_reduction_config._reduce( # noqa: SLF001 

901 1, 

902 leaf_indices, 

903 size=max_num_leaves, 

904 subset=right[None], 

905 dtype=jnp.uint32, 

906 data_sharded=config.data_sharded, 

907 ).squeeze(-1) 

908 lr = jnp.stack([cached_total - right_count, right_count]) 

909 total = cached_total 

910 

911 elif counts is not None and config.one_bin_prec_reduction: 

912 # like the counts, reduce into one child alone and derive the other. 

913 # In floating point the derived child carries the rounding error of 

914 # the parent's sum, so derive the child with more datapoints, whose 

915 # precision is at least half the parent's divided by the spread of 

916 # the datapoints' precisions. On prune the children are cached leaves, 

917 # so the reduction, computed anyway for all the trees, is discarded. 

918 left_fewer = counts.lrt[0] <= counts.lrt[1] 

919 fresh = config.prec_reduction_config._reduce( # noqa: SLF001 

920 prec_scale, 

921 leaf_indices, 

922 size=max_num_leaves, 

923 subset=jnp.where(left_fewer, left, right)[None], 

924 dtype=jnp.float32, 

925 data_sharded=config.data_sharded, 

926 ).squeeze(-1) 

927 derived = cached_total - fresh 

928 grown = jnp.where( 

929 left_fewer, 

930 jnp.stack([fresh, derived], axis=-1), 

931 jnp.stack([derived, fresh], axis=-1), 

932 ) 

933 lr = jnp.where(moves.grow, grown, cached) 

934 total = cached_total 

935 

936 else: 

937 # reduce into both children of the move; neither is derived by 

938 # difference, because in floating point that would lose precision on a 

939 # small leaf next to a large one 

940 lr = config.prec_reduction_config._reduce( # noqa: SLF001 

941 prec_scale, 

942 leaf_indices, 

943 size=max_num_leaves, 

944 subset=moves.lr_leaves, 

945 dtype=jnp.float32, 

946 data_sharded=config.data_sharded, 

947 ) 

948 total = lr[..., 0] + lr[..., 1] 

949 

950 # the total goes apart from the cache, where the parent node shares its 

951 # element with the left child 

952 tree = tree.at[..., moves.lr_leaves].set(lr) 

953 return tree, jnp.concatenate([lr, total[..., None]], axis=-1) 

954 

955 

956@named_call 

957def apply_moves_to_leaf_sums( 

958 trees: UInt32[Array, 'num_trees max_num_leaves'] 

959 | Float32[Array, 'num_trees max_num_leaves'] 

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

961 to_prune: Bool[Array, ' num_trees'], 

962 move_node: Int32[Array, ' num_trees'], 

963) -> ( 

964 UInt32[Array, 'num_trees max_num_leaves'] 

965 | Float32[Array, 'num_trees max_num_leaves'] 

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

967): 

968 """ 

969 Apply the prunes pending from the previous step to per-leaf sums. 

970 

971 Parameters 

972 ---------- 

973 trees 

974 The sum of something over the datapoints in each leaf, see 

975 `bartz.mcmcstep.Forest.count_tree`. 

976 to_prune 

977 Whether the last move on each tree ended in a prune yet to be applied. 

978 move_node 

979 The node the last move on each tree operated on. 

980 

981 Returns 

982 ------- 

983 The updated sums, with the right child of a pruned node moved into the left one, that shares its index with the node. 

984 """ 

985 return _apply_moves_to_leaf_sums(trees, to_prune, move_node) 

986 

987 

988@vmap 

989def _apply_moves_to_leaf_sums( 

990 tree: Shaped[Array, '*k_k max_num_leaves'], 

991 to_prune: Bool[Array, ''], 

992 move_node: Int32[Array, ''], 

993) -> Shaped[Array, '*k_k max_num_leaves']: 

994 """Implement `apply_moves_to_leaf_sums`.""" 

995 *_, max_num_leaves = tree.shape 

996 lr_leaves = jnp.stack([node_to_leaf_index(move_node), move_node]) 

997 lr = tree[..., lr_leaves] 

998 total = lr[..., 0] + lr[..., 1] 

999 merged = jnp.stack([total, jnp.zeros_like(total)], axis=-1) 

1000 return tree.at[..., jnp.where(to_prune, lr_leaves, max_num_leaves)].set(merged) 

1001 

1002 

1003@named_call 

1004def compute_count_trees( 

1005 count_trees: UInt32[Array, 'num_trees max_num_leaves'], 

1006 leaf_indices: UInt[Array, 'num_trees n'], 

1007 moves: Moves, 

1008 config: StepConfig, 

1009) -> tuple[UInt32[Array, 'num_trees max_num_leaves'], Counts]: 

1010 """ 

1011 Update the cached number of datapoints per leaf at the moves' nodes. 

1012 

1013 Parameters 

1014 ---------- 

1015 count_trees 

1016 The cached number of points in each leaf; valid at the leaves of the 

1017 pre-move trees. 

1018 leaf_indices 

1019 The index of the leaf each datapoint falls into, with the deeper version 

1020 of the tree (post-GROW, pre-PRUNE). 

1021 moves 

1022 The proposed moves, see `propose_moves`. 

1023 config 

1024 The MCMC configuration. 

1025 

1026 Returns 

1027 ------- 

1028 count_trees : UInt32[Array, 'num_trees max_num_leaves'] 

1029 The updated cache, valid at the leaves of the deeper version of the trees. 

1030 counts : Counts 

1031 The counts of the number of points in the leaves grown or pruned by the 

1032 moves. 

1033 """ 

1034 count_trees, lrt = _compute_count_or_prec_trees( 

1035 None, count_trees, leaf_indices, moves, None, config=config 

1036 ) 

1037 return count_trees, Counts(lrt=lrt) 

1038 

1039 

1040@named_call 

1041def compute_prec_trees( 

1042 prec_trees: Float32[Array, 'num_trees max_num_leaves'] 

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

1044 prec_scale: Float[Array, ' n'] | Float[Array, 'k k n'], 

1045 leaf_indices: UInt[Array, 'num_trees n'], 

1046 moves: Moves, 

1047 counts: Counts | None, 

1048 *, 

1049 config: StepConfig, 

1050) -> ( 

1051 tuple[Float32[Array, 'num_trees max_num_leaves'], Float32[Array, ' num_trees']] 

1052 | tuple[ 

1053 Float32[Array, 'num_trees k k max_num_leaves'], Float32[Array, 'num_trees k k'] 

1054 ] 

1055): 

1056 """ 

1057 Update the cached per-leaf likelihood precision scale at the moves' nodes. 

1058 

1059 Parameters 

1060 ---------- 

1061 prec_trees 

1062 The cached likelihood precision scale in each leaf; valid at the leaves 

1063 of the pre-move trees. 

1064 prec_scale 

1065 The scale of the precision of the error on each datapoint. 

1066 leaf_indices 

1067 The index of the leaf each datapoint falls into, with the deeper version 

1068 of the tree (post-GROW, pre-PRUNE). 

1069 moves 

1070 The proposed moves, see `propose_moves`. 

1071 counts 

1072 The datapoint counts at the moves' nodes, see `compute_count_trees`, or 

1073 `None` if they are not tracked. If given, they speed up the update. 

1074 config 

1075 The MCMC configuration. 

1076 

1077 Returns 

1078 ------- 

1079 prec_trees : Float32[Array, 'num_trees max_num_leaves'] | Float32[Array, 'num_trees k k max_num_leaves'] 

1080 The updated cache, valid at the leaves of the deeper version of the trees. 

1081 parent_prec : Float32[Array, ' num_trees'] | Float32[Array, 'num_trees k k'] 

1082 The likelihood precision scale in the node each move operates on. 

1083 """ 

1084 prec_trees, lrt = _compute_count_or_prec_trees( 

1085 prec_scale, prec_trees, leaf_indices, moves, counts, config=config 

1086 ) 

1087 return prec_trees, lrt[..., 2] 

1088 

1089 

1090@partial(vmap, in_axes=(0, None)) 

1091def complete_ratio(moves: Moves, p_nonterminal: Float32[Array, ' heap_size']) -> Moves: 

1092 """ 

1093 Complete non-likelihood MH ratio calculation. 

1094 

1095 This function adds the probability of choosing a prune move over the grow 

1096 move in the inverse transition, and the prior odds that the modified node 

1097 is nonterminal with terminal children. 

1098 

1099 Parameters 

1100 ---------- 

1101 moves 

1102 The proposed moves. Must have already been updated to keep into account 

1103 the thresholds on the number of datapoints per node, this happens in 

1104 `accept_moves_parallel_stage`. 

1105 p_nonterminal 

1106 The a priori probability of each node being nonterminal conditional on 

1107 its ancestors, including at the maximum depth where it should be zero. 

1108 

1109 Returns 

1110 ------- 

1111 The updated moves, with `partial_ratio=None` and `log_trans_prior_ratio` set. 

1112 """ 

1113 assert moves.lrt_affluent is not None 

1114 

1115 # can the children be grown by the proposal? `lrt_affluent` already folds 

1116 # in the `min_points_per_decision_node` threshold, because the grow 

1117 # proposal draws from the pool of leaves that pass it. This enters only the 

1118 # transition probability. 

1119 

1120 # p_prune if grow 

1121 other_growable_leaves = moves.num_growable >= 2 

1122 grow_again_allowed = other_growable_leaves | jnp.any(moves.lrt_affluent[:2]) 

1123 grow_p_prune = jnp.where(grow_again_allowed, 0.5, 1.0) 

1124 

1125 # p_prune if prune 

1126 prune_p_prune = jnp.where(moves.num_growable, 0.5, 1) 

1127 

1128 # select p_prune 

1129 p_prune = jnp.where(moves.grow, grow_p_prune, prune_p_prune) 

1130 

1131 # prior odds of the node being nonterminal, times the prior probability of 

1132 # both children being terminal. The children terminality uses the 

1133 # admissibility ignoring counts, because the count thresholds restrict the 

1134 # support of the prior rather than the conditional non-terminal 

1135 # probabilities, so they cancel in the prior ratio between two trees in 

1136 # the support. The fill value avoids a 0 and then an inf in the log if the 

1137 # move is not allowed and the indices are out of bounds. 

1138 pnt = p_nonterminal.at[moves.lrt_nodes].get(mode='fill', fill_value=0.5) 

1139 prior_ratio = pnt[2] / (1 - pnt[2]) * jnp.prod(1 - pnt[:2] * moves.lrt_growable[:2]) 

1140 

1141 assert moves.partial_ratio is not None 

1142 return replace( 

1143 moves, 

1144 log_trans_prior_ratio=jnp.log(moves.partial_ratio * prior_ratio * p_prune), 

1145 partial_ratio=None, 

1146 ) 

1147 

1148 

1149@named_call 

1150def adapt_leaf_trees_to_grow_indices( 

1151 leaf_trees: Float[Array, 'num_trees max_num_leaves'] 

1152 | Float[Array, 'num_trees k max_num_leaves'], 

1153 moves: Moves, 

1154) -> ( 

1155 Float[Array, 'num_trees max_num_leaves'] 

1156 | Float[Array, 'num_trees k max_num_leaves'] 

1157): 

1158 """ 

1159 Modify leaves such that post-grow indices work on the original tree. 

1160 

1161 The value of the leaf to grow is copied to what would be its right child if 

1162 the grow move was accepted; the left one takes over its index. 

1163 

1164 Parameters 

1165 ---------- 

1166 leaf_trees 

1167 The leaf values. 

1168 moves 

1169 The proposed moves, see `propose_moves`. 

1170 

1171 Returns 

1172 ------- 

1173 The modified leaf values. 

1174 """ 

1175 return _adapt_leaf_trees_to_grow_indices(leaf_trees, moves) 

1176 

1177 

1178@vmap 

1179def _adapt_leaf_trees_to_grow_indices( 

1180 leaf_trees: Float[Array, ' max_num_leaves'] | Float[Array, ' k max_num_leaves'], 

1181 moves: Moves, 

1182) -> Float[Array, ' max_num_leaves'] | Float[Array, ' k max_num_leaves']: 

1183 """Implement `adapt_leaf_trees_to_grow_indices`.""" 

1184 *_, max_num_leaves = leaf_trees.shape 

1185 left, right = moves.lr_leaves 

1186 return leaf_trees.at[..., jnp.where(moves.grow, right, max_num_leaves)].set( 

1187 leaf_trees[..., left] 

1188 ) 

1189 

1190 

1191def _logdet_from_chol(L: Float32[Array, '... k k']) -> Float32[Array, '...']: 

1192 """Compute logdet of A = LL' via Cholesky (sum of log of diag^2).""" 

1193 diags: Float32[Array, '... k'] = jnp.diagonal(L, axis1=-2, axis2=-1) 

1194 return 2.0 * jnp.sum(jnp.log(diags), axis=-1) 

1195 

1196 

1197def compute_B( 

1198 error_cov_inv: Float32[Array, 'k k'], 

1199 resid: Float32[Array, 'k k max_num_leaves_plus_1'] | Float32[Array, 'k k 3'], 

1200) -> Float32[Array, 'k max_num_leaves_plus_1'] | Float32[Array, 'k 3']: 

1201 """Compute the leaf score from the leaf precision-scaled sum of residuals.""" 

1202 return jnp.einsum('ab,ab...->a...', error_cov_inv, resid) 

1203 

1204 

1205# keep the leaf axis trailing, faster for the unrolled matvec 

1206@partial(vmap, in_axes=-1, out_axes=-1) 

1207def solve_leaf( 

1208 L: Float32[Array, 'k k'], b: Float32[Array, ' k'] 

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

1210 """Compute ``(L L^T)^-1 b``, the leaf posterior mean from its score.""" 

1211 y = solve_triangular(L, b[:, None], lower=True) 

1212 return solve_triangular(L, y, lower=True, trans='T').squeeze(-1) 

1213 

1214 

1215def _precompute_leaf_terms_uv( 

1216 key: Key[Array, ''], 

1217 prec_trees: Float32[Array, 'num_trees max_num_leaves_plus_1'] 

1218 | UInt32[Array, 'num_trees max_num_leaves_plus_1'], 

1219 error_cov_inv: Float32[Array, ''], 

1220 leaf_prior_cov_inv: Float32[Array, ''], 

1221 z: Float32[Array, 'num_trees max_num_leaves_plus_1'] | None = None, 

1222) -> PreLfUV: 

1223 prec_lk = prec_trees * error_cov_inv 

1224 var_post = jnp.reciprocal(prec_lk + leaf_prior_cov_inv) 

1225 if z is None: 

1226 z = random.normal(key, prec_trees.shape, error_cov_inv.dtype) 

1227 return PreLfUV( 

1228 mean_factor=var_post * error_cov_inv, 

1229 # | mean = mean_lk * prec_lk * var_post 

1230 # | resid_tree = mean_lk * prec_tree --> 

1231 # | --> mean_lk = resid_tree / prec_tree (kind of) 

1232 # | mean_factor = 

1233 # | = mean / resid_tree = 

1234 # | = resid_tree / prec_tree * prec_lk * var_post / resid_tree = 

1235 # | = 1 / prec_tree * prec_tree / sigma2 * var_post = 

1236 # | = var_post / sigma2 

1237 centered_leaves=z * jnp.sqrt(var_post), 

1238 ) 

1239 

1240 

1241def _precompute_leaf_terms_mv( 

1242 key: Key[Array, ''], 

1243 prec_trees: Float32[Array, 'num_trees max_num_leaves_plus_1'] 

1244 | UInt32[Array, 'num_trees max_num_leaves_plus_1'], 

1245 error_cov_inv: Float32[Array, 'k k'], 

1246 leaf_prior_cov_inv: Float32[Array, 'k k'], 

1247 z: Float32[Array, 'num_trees k max_num_leaves_plus_1'] | None = None, 

1248) -> PreLfMV: 

1249 num_trees, max_num_leaves_plus_1 = prec_trees.shape 

1250 k, _ = error_cov_inv.shape 

1251 if z is None: 1251 ↛ 1254line 1251 didn't jump to line 1254 because the condition on line 1251 was always true

1252 z = random.normal(key, (num_trees, k, max_num_leaves_plus_1)) 

1253 

1254 def per_leaf( 

1255 prec: Float32[Array, ''] | UInt32[Array, ''], z: Float32[Array, ' k'] 

1256 ) -> tuple[Float32[Array, 'k k'], Float32[Array, ' k'], Float32[Array, '']]: 

1257 L_prec = chol_with_gersh(leaf_prior_cov_inv + prec * error_cov_inv) 

1258 Y = solve_triangular(L_prec, error_cov_inv, lower=True) 

1259 mean_factor = solve_triangular(L_prec, Y, trans='T', lower=True).mT 

1260 centered = solve_triangular(L_prec, z[:, None], trans='T', lower=True).squeeze( 

1261 -1 

1262 ) 

1263 # only a few leaves per tree end up using their logdet, but reducing 

1264 # right away is lighter on memory than storing diagonals for later 

1265 return mean_factor, centered, _logdet_from_chol(L_prec) 

1266 

1267 # vmap over trees then over leaves; the leaf axis is trailing in both 

1268 # `prec_trees`/`z` (in_axes) and the stored output (out_axes=-1) 

1269 return PreLfMV(*vmap(vmap(per_leaf, in_axes=(0, -1), out_axes=-1))(prec_trees, z)) 

1270 

1271 

1272def _precompute_leaf_terms_mv_het( 

1273 key: Key[Array, ''], 

1274 prec_trees: Float32[Array, 'num_trees k k max_num_leaves_plus_1'], 

1275 error_cov_inv: Float32[Array, 'k k'], 

1276 leaf_prior_cov_inv: Float32[Array, 'k k'], 

1277 z: Float32[Array, 'num_trees k max_num_leaves_plus_1'] | None = None, 

1278) -> PreLfMVHet: 

1279 num_trees, k, _, max_num_leaves_plus_1 = prec_trees.shape 

1280 if z is None: 1280 ↛ 1283line 1280 didn't jump to line 1283 because the condition on line 1280 was always true

1281 z = random.normal(key, (num_trees, k, max_num_leaves_plus_1)) 

1282 

1283 def per_leaf( 

1284 prec: Float32[Array, 'k k'], z: Float32[Array, ' k'] 

1285 ) -> tuple[Float32[Array, 'k k'], Float32[Array, ' k']]: 

1286 # mean_factor stores the precision cholesky itself; the mean solve happens 

1287 # downstream in `accept_move_and_sample_leaves` 

1288 L_prec = chol_with_gersh(leaf_prior_cov_inv + error_cov_inv * prec) 

1289 centered = solve_triangular(L_prec, z[:, None], trans='T', lower=True).squeeze( 

1290 -1 

1291 ) 

1292 return L_prec, centered 

1293 

1294 # vmap over trees then over leaves; the leaf axis is trailing in both 

1295 # `prec_trees`/`z` (in_axes=-1) and the stored output (out_axes=-1) 

1296 return PreLfMVHet( 

1297 *vmap(vmap(per_leaf, in_axes=(-1, -1), out_axes=-1))(prec_trees, z) 

1298 ) 

1299 

1300 

1301@named_call 

1302def precompute_leaf_terms( 

1303 key: Key[Array, ''], 

1304 prec_trees: Float32[Array, 'num_trees max_num_leaves_plus_1'] 

1305 | UInt32[Array, 'num_trees max_num_leaves_plus_1'] 

1306 | Float32[Array, 'num_trees k k max_num_leaves_plus_1'], 

1307 error_cov_inv: Float32[Array, ''] | Float32[Array, 'k k'], 

1308 leaf_prior_cov_inv: Float32[Array, ''] | Float32[Array, 'k k'], 

1309 z: Float32[Array, 'num_trees max_num_leaves_plus_1'] 

1310 | Float32[Array, 'num_trees k max_num_leaves_plus_1'] 

1311 | None = None, 

1312) -> PreLf: 

1313 """ 

1314 Pre-compute terms used to sample leaves from their posterior. 

1315 

1316 Handles both univariate and multivariate cases based on the shape of the 

1317 input arrays. 

1318 

1319 Parameters 

1320 ---------- 

1321 key 

1322 A jax random key. 

1323 prec_trees 

1324 The likelihood precision scale in each leaf, followed by the one in the 

1325 parent node of the move. 

1326 error_cov_inv 

1327 The inverse error variance (univariate) or the inverse of error 

1328 covariance matrix (multivariate). If `prec_scale` is set, this is the 

1329 global error precision factor, with the squared `inv_sdev_unit` folded in 

1330 (see `bartz.mcmcstep.State.inv_sdev_unit`). 

1331 leaf_prior_cov_inv 

1332 The inverse prior variance of each leaf (univariate) or the inverse of 

1333 prior covariance matrix of each leaf (multivariate). 

1334 z 

1335 Optional standard normal noise to use for sampling the centered leaves. 

1336 This is intended for testing purposes only. 

1337 

1338 Returns 

1339 ------- 

1340 Pre-computed terms for leaf sampling. 

1341 """ 

1342 if error_cov_inv.ndim == 0: 

1343 return _precompute_leaf_terms_uv( 

1344 key, prec_trees, error_cov_inv, leaf_prior_cov_inv, z 

1345 ) 

1346 elif prec_trees.ndim == 4: 

1347 return _precompute_leaf_terms_mv_het( 

1348 key, prec_trees, error_cov_inv, leaf_prior_cov_inv, z 

1349 ) 

1350 else: 

1351 return _precompute_leaf_terms_mv( 

1352 key, prec_trees, error_cov_inv, leaf_prior_cov_inv, z 

1353 ) 

1354 

1355 

1356@vmap 

1357def _gather_lrt( 

1358 leaf_values: Float32[Array, '*k_k max_num_leaves_plus_1'], 

1359 lr_leaves: Int32[Array, ' 2'], 

1360) -> Float32[Array, ' 3 *k_k']: 

1361 """Gather per-tree leaf values at the left child, right child, and parent.""" 

1362 lrt = jnp.concatenate([leaf_values[..., lr_leaves], leaf_values[..., -1:]], axis=-1) 

1363 return jnp.moveaxis(lrt, -1, 0) 

1364 

1365 

1366def _precompute_likelihood_terms_uv( 

1367 error_cov_inv: Float32[Array, ''], 

1368 leaf_prior_cov_inv: Float32[Array, ''], 

1369 prelf: PreLfUV, 

1370 lr_leaves: Int32[Array, 'num_trees 2'], 

1371) -> PreLkV: 

1372 # mean_factor is error_cov_inv / prec, complete the sandwich 

1373 lrt = error_cov_inv * _gather_lrt(prelf.mean_factor, lr_leaves) 

1374 # the same value with the prior-only precision, computed with the same 

1375 # operations as in `_precompute_leaf_terms_uv` such that it matches `lrt` 

1376 # bitwise on empty nodes and the ratio is exactly 1 without data 

1377 prior_lrt = error_cov_inv * (jnp.reciprocal(leaf_prior_cov_inv) * error_cov_inv) 

1378 log_sqrt_term = jnp.log(lrt[..., 0] * lrt[..., 1] / (prior_lrt * lrt[..., 2])) / 2 

1379 return PreLkV(lrt=lrt, log_sqrt_term=log_sqrt_term) 

1380 

1381 

1382def _precompute_likelihood_terms_mv( 

1383 error_cov_inv: Float32[Array, 'k k'], 

1384 leaf_prior_cov_inv: Float32[Array, 'k k'], 

1385 prelf: PreLfMV, 

1386 lr_leaves: Int32[Array, 'num_trees 2'], 

1387) -> PreLkV: 

1388 logdet_prior = _logdet_from_chol(chol_with_gersh(leaf_prior_cov_inv)) 

1389 logdet_prec = _gather_lrt(prelf.logdet_prec, lr_leaves) 

1390 log_sqrt_term = (logdet_prior + logdet_prec @ jnp.array([-1.0, -1.0, 1.0])) / 2 

1391 

1392 # mean_factor is error_cov_inv @ inv(prec), complete the sandwich 

1393 mean_factor = _gather_lrt(prelf.mean_factor, lr_leaves) # (num_trees, 3, k, k) 

1394 return PreLkV(lrt=mean_factor @ error_cov_inv, log_sqrt_term=log_sqrt_term) 

1395 

1396 

1397def _precompute_likelihood_terms_mv_het( 

1398 leaf_prior_cov_inv: Float32[Array, 'k k'], 

1399 prelf: PreLfMVHet, 

1400 lr_leaves: Int32[Array, 'num_trees 2'], 

1401) -> PreLkV: 

1402 logdet_prior = _logdet_from_chol(chol_with_gersh(leaf_prior_cov_inv)) 

1403 

1404 # mean_factor is the precision cholesky itself 

1405 L = _gather_lrt(prelf.mean_factor, lr_leaves) # (num_trees, 3, k, k) 

1406 log_sqrt_term = ( 

1407 logdet_prior + _logdet_from_chol(L) @ jnp.array([-1.0, -1.0, 1.0]) 

1408 ) / 2 

1409 return PreLkV(lrt=L, log_sqrt_term=log_sqrt_term) 

1410 

1411 

1412@named_call 

1413def precompute_likelihood_terms( 

1414 error_cov_inv: Float32[Array, ''] | Float32[Array, 'k k'], 

1415 leaf_prior_cov_inv: Float32[Array, ''] | Float32[Array, 'k k'], 

1416 prelf: PreLf, 

1417 moves: Moves, 

1418) -> PreLkV: 

1419 """ 

1420 Pre-compute terms used in the likelihood ratio of the acceptance step. 

1421 

1422 The likelihood ratio terms are mostly a subset of the leaf sampling terms, 

1423 so they are derived from `prelf`, gathered at the nodes involved in the 

1424 moves. 

1425 

1426 Parameters 

1427 ---------- 

1428 error_cov_inv 

1429 The inverse error variance (univariate) or the inverse of the error 

1430 covariance matrix (multivariate). If `prec_scale` is set, this is the 

1431 global error precision factor, with the squared `inv_sdev_unit` folded in 

1432 (see `bartz.mcmcstep.State.inv_sdev_unit`). 

1433 leaf_prior_cov_inv 

1434 The inverse prior variance of each leaf (univariate) or the inverse of 

1435 prior covariance matrix of each leaf (multivariate). 

1436 prelf 

1437 The pre-computed terms of the leaf sampling, see `precompute_leaf_terms`. 

1438 moves 

1439 The proposed moves, see `propose_moves`. 

1440 

1441 Returns 

1442 ------- 

1443 Pre-computed terms of the likelihood ratio, one per tree. 

1444 """ 

1445 if isinstance(prelf, PreLfUV): 

1446 return _precompute_likelihood_terms_uv( 

1447 error_cov_inv, leaf_prior_cov_inv, prelf, moves.lr_leaves 

1448 ) 

1449 elif isinstance(prelf, PreLfMVHet): 

1450 return _precompute_likelihood_terms_mv_het( 

1451 leaf_prior_cov_inv, prelf, moves.lr_leaves 

1452 ) 

1453 else: 

1454 assert isinstance(prelf, PreLfMV) 

1455 return _precompute_likelihood_terms_mv( 

1456 error_cov_inv, leaf_prior_cov_inv, prelf, moves.lr_leaves 

1457 ) 

1458 

1459 

1460@named_call 

1461def accept_moves_sequential_stage( 

1462 key: Key[Array, ''], pso: ParallelStageOut 

1463) -> tuple[State, Moves]: 

1464 """ 

1465 Accept/reject the moves one tree at a time. 

1466 

1467 This is the most performance-sensitive function because it contains all and 

1468 only the parts of the algorithm that can not be parallelized across trees. 

1469 

1470 Parameters 

1471 ---------- 

1472 key 

1473 A jax random key, used to draw the order in which to visit the trees 

1474 with `random_tree_order` if `StepConfig.random_tree_scan` is set. 

1475 pso 

1476 The output of `accept_moves_parallel_stage`. 

1477 

1478 Returns 

1479 ------- 

1480 state : State 

1481 A partially updated BART mcmc state. 

1482 moves : Moves 

1483 The accepted/rejected moves, with `acc` and `to_prune` set. 

1484 """ 

1485 # wrap together all per-tree inputs, but `leaf_indices` 

1486 num_trees, _ = pso.state.forest.leaf_indices.shape 

1487 pts = SeqStageInPerTree( 

1488 pso.state.forest.leaf_tree, 

1489 pso.prec_trees, 

1490 pso.moves, 

1491 minimal_unsigned_arange(num_trees), 

1492 pso.prelkv, 

1493 pso.prelf, 

1494 ) 

1495 

1496 # Permute the per-tree stuff from storage order to scan order. Permuting 

1497 # up-front is more efficient than indexing the arrays with the permutation 

1498 # indices in the loop because of xla quirks. 

1499 order = None 

1500 if pso.state.config.random_tree_scan: 

1501 order = random_tree_order(key, pso.state.forest) 

1502 pts = tree.map(lambda x: x[order, ...], pts) 

1503 

1504 # wrap together all inputs that are not per tree 

1505 at = SeqStageInAllTrees( 

1506 pso.state.X, 

1507 # `leaf_indices` is per-tree, but it's passed all at once from here as 

1508 # a workaround to avoid copies created by xla 

1509 pso.state.forest.leaf_indices, 

1510 pso.state.config.resid_reduction_config, 

1511 pso.state.config.data_sharded, 

1512 pso.state.prec_scale, 

1513 pso.state.forest.log_likelihood is not None, 

1514 scaled_error_cov_inv(pso.state) if isinstance(pso.prelf, PreLfMVHet) else None, 

1515 pso.state.forest.leaf_unit, 

1516 pso.state.resid_unit, 

1517 pso.state.resid_eff_scale, 

1518 pso.state.config.leaf_quantization, 

1519 ) 

1520 

1521 # With a fixed number of trees, the loop over them has fixed length and is 

1522 # unrolled as configured. Otherwise it goes in blocks, which are fully 

1523 # unrolled, so that only the loop over blocks checks its condition. 

1524 used_trees = pso.state.forest.used_trees 

1525 unroll = pso.state.config.sequential_unroll if used_trees is None else True 

1526 block_size = pso.state.config.sequential_block_size 

1527 

1528 # Invoke the loop over trees differently depending on the device type. Both 

1529 # the cpu and cuda branch are traced by jax, but only one is compiled by 

1530 # xla. 

1531 resid, pertree_out = lax.platform_dependent( 

1532 pso.state.resid, 

1533 at, 

1534 pts, 

1535 used_trees, 

1536 # On cpu, loop over chains instead of vmapping over them, for two 

1537 # reasons: 1) It's substantially faster in general. We observed 

1538 # empirically that, with vmapped chains, the running time scales 

1539 # super-linearly with number of chains at high n, which is weird. At 

1540 # low n no substantial difference. I guess bad xla:cpu code generation. 

1541 # 2) With random scan order, it's even slower, which we attributed to 

1542 # the materialization of copies of the rows of `leaf_indices` instead 

1543 # of fusing the reads into their users. Here xla:cpu can fuse a slice 

1544 # but not a gather. 

1545 cpu=sequential_vmap( 

1546 partial( 

1547 loop_over_trees, 

1548 unroll=unroll, 

1549 block_size=2 if block_size is None else block_size, 

1550 ), 

1551 # This is our own custom `sequential_vmap`, not 

1552 # `jax.custom_batching.sequential_vmap`, to add the `in_place` 

1553 # parameter, that here we use to avoid an extra copy of a 

1554 # single-chain `leaf_indices` by not slicing over it. The 

1555 # copy-on-slice happens because a slice that's used as loop input 

1556 # (here the loop is the one over trees, while the loop over chains 

1557 # created by the batching rule of `sequential_vmap` is the one 

1558 # taking the slice) is materialized because it can't be fused 

1559 # across the loop boundary. 

1560 in_place=lambda _resid, at, _pts, _used_trees: at.leaf_indices, 

1561 ), 

1562 cuda=partial( 

1563 loop_over_trees, 

1564 unroll=unroll, 

1565 # the gpu takes larger blocks (4 instead of 2) because it checks 

1566 # the loop condition from the host. Higher than 2 is not reliable 

1567 # on cpu, sometimes it's much slower. Probably bad xla:cpu as 

1568 # usual. 

1569 block_size=4 if block_size is None else block_size, 

1570 ), 

1571 ) 

1572 

1573 # permute back output arrays with a tree axis to storage order 

1574 if order is not None: 

1575 inverse = jnp.argsort(order) 

1576 pertree_out = tree.map(lambda y: y[inverse, ...], pertree_out) 

1577 

1578 # store the results in `state` and `moves`, then return 

1579 state = replace( 

1580 pso.state, 

1581 resid=resid, 

1582 forest=replace( 

1583 pso.state.forest, 

1584 leaf_tree=pertree_out.leaf_tree, 

1585 log_likelihood=pertree_out.log_lk_ratio, 

1586 ), 

1587 ) 

1588 moves = replace(pso.moves, acc=pertree_out.acc, to_prune=pertree_out.to_prune) 

1589 

1590 return state, moves 

1591 

1592 

1593class SeqStageInAllTrees(Module): 

1594 """The inputs to `accept_move_and_sample_leaves` that are shared by all trees.""" 

1595 

1596 X: UInt[Array, 'p n'] 

1597 """The predictors.""" 

1598 

1599 leaf_indices: UInt[Array, 'num_trees n'] | InPlace 

1600 """The leaf indices for the largest version of each tree compatible with 

1601 the move. Kept whole here and sliced per tree with 

1602 `SeqStageInPerTree.tree_index`, instead of consumed as scan xs, because 

1603 the scan batching rules move the chain axis of closed-over values to the 

1604 front, matching the storage layout, while the xs rule would transpose it 

1605 to after the tree axis. When looping over the chains, a view of the leaf 

1606 indices of all the chains, see `accept_moves_sequential_stage`.""" 

1607 

1608 resid_reduction_config: ReductionConfig 

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

1610 

1611 data_sharded: bool = field(static=True) 

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

1613 

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

1615 """The scale of the precision of the error on each datapoint. If None, it 

1616 is assumed to be 1.""" 

1617 

1618 save_ratios: bool = field(static=True) 

1619 """Whether to save the acceptance ratios.""" 

1620 

1621 error_cov_inv: Float32[Array, 'k k'] | None 

1622 """The global error precision scale, with the squared `inv_sdev_unit` folded 

1623 in (see `bartz.mcmcstep.State.inv_sdev_unit`). Set only in the 

1624 multivariate case with per-component error scales, where the sequential 

1625 stage needs it to compute the leaf scores.""" 

1626 

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

1628 """The storage unit of the leaf values, see `bartz.mcmcstep.Forest.leaf_unit`.""" 

1629 

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

1631 """The storage unit of the residuals, see `bartz.mcmcstep.State.resid_unit`.""" 

1632 

1633 resid_eff_scale: Float32[Array, ''] | Float32[Array, ' k'] 

1634 """The measured scale of the residuals, see `bartz.mcmcstep.State.resid_eff_scale`.""" 

1635 

1636 leaf_quantization: Int32[Array, ''] | None 

1637 """Leaf quantization setting, see `bartz.mcmcstep.StepConfig`.""" 

1638 

1639 

1640class SeqStageInPerTree(Module): 

1641 """The inputs to `accept_move_and_sample_leaves` that are separate for each tree.""" 

1642 

1643 # Although consumed one tree at a time by `lax.scan`, this object is only 

1644 # ever constructed in the stacked (batched) form fed to the scan, so 

1645 # `num_trees` stays a fixed (non-variadic) leading axis disambiguated by 

1646 # rank/dtype (cf. `ParallelStageOut`); the per-tree slices reach `loop` via 

1647 # scan, which does not re-run `__init__`. 

1648 leaf_tree: ( 

1649 Float[Array, 'num_trees max_num_leaves'] 

1650 | Float[Array, 'num_trees k max_num_leaves'] 

1651 ) 

1652 """The leaf values of the trees.""" 

1653 

1654 prec_tree: ( 

1655 Float32[Array, 'num_trees max_num_leaves'] 

1656 | UInt32[Array, 'num_trees max_num_leaves'] 

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

1658 ) 

1659 """The likelihood precision scale in each leaf, in the same version of 

1660 each tree as the leaf indices.""" 

1661 

1662 move: Moves 

1663 """The proposed move, see `propose_moves`.""" 

1664 

1665 tree_index: UInt[Array, ' num_trees'] 

1666 """The index of the tree, used to slice `SeqStageInAllTrees.leaf_indices`.""" 

1667 

1668 prelkv: PreLkV 

1669 """The pre-computed terms of the likelihood ratio which are specific to the tree.""" 

1670 

1671 prelf: PreLf 

1672 """The pre-computed terms of the leaf sampling which are specific to the tree.""" 

1673 

1674 

1675class SeqStageOutPerTree(Module): 

1676 """The outputs of `accept_move_and_sample_leaves` that are separate for each tree.""" 

1677 

1678 # Constructed one tree at a time, then stacked along a leading tree axis by 

1679 # the loop over trees. `acc` comes first to fix `num_trees` before the 

1680 # union in `leaf_tree` is checked, else its first alternative would match a 

1681 # multivariate tree with `num_trees` set to `k`. 

1682 acc: Bool[Array, '*num_trees'] 

1683 """Whether the move was accepted.""" 

1684 

1685 to_prune: Bool[Array, '*num_trees'] 

1686 """Whether, to reflect the acceptance status of the move, the state should 

1687 be updated by pruning the leaves involved in the move.""" 

1688 

1689 leaf_tree: ( 

1690 Float[Array, '*num_trees max_num_leaves'] 

1691 | Float[Array, '*num_trees k max_num_leaves'] 

1692 ) 

1693 """The new leaf values of the tree.""" 

1694 

1695 log_lk_ratio: Float32[Array, '*num_trees'] | None 

1696 """The logarithm of the likelihood ratio for the move. `None` if not to be 

1697 saved.""" 

1698 

1699 

1700def loop_over_trees( 

1701 resid: Float[Array, ' n'] | Float[Array, ' k n'], 

1702 at: SeqStageInAllTrees, 

1703 pts: SeqStageInPerTree, 

1704 used_trees: Int32[Array, ''] | None, 

1705 *, 

1706 unroll: int | bool, 

1707 block_size: int, 

1708) -> tuple[Float[Array, ' n'] | Float[Array, ' k n'], SeqStageOutPerTree]: 

1709 """Apply `accept_move_and_sample_leaves` to the trees in order. 

1710 

1711 The loop is a `variable_length_scan` over the first `used_trees` trees. 

1712 """ 

1713 

1714 def loop( 

1715 resid: Float[Array, ' n'] | Float[Array, ' k n'], 

1716 pt: SeqStageInPerTree, 

1717 use: Bool[Array, ''] | None, 

1718 ) -> tuple[Float[Array, ' n'] | Float[Array, ' k n'], SeqStageOutPerTree]: 

1719 return accept_move_and_sample_leaves(resid, at, pt, use) 

1720 

1721 return variable_length_scan( 

1722 loop, resid, pts, used_trees, block_size=block_size, unroll=unroll 

1723 ) 

1724 

1725 

1726@named_call 

1727def accept_move_and_sample_leaves( 

1728 resid: Float[Array, ' n'] | Float[Array, ' k n'], 

1729 at: SeqStageInAllTrees, 

1730 pt: SeqStageInPerTree, 

1731 use: Bool[Array, ''] | None = None, 

1732) -> tuple[Float[Array, ' n'] | Float[Array, ' k n'], SeqStageOutPerTree]: 

1733 """ 

1734 Accept or reject a proposed move and sample the new leaf values. 

1735 

1736 Parameters 

1737 ---------- 

1738 resid 

1739 The residuals (data minus forest value), in units of `at.resid_unit` 

1740 and a possibly narrow dtype (see `State.resid`). The reduction over the 

1741 residuals runs in these units; the per-leaf sums are scaled back to data 

1742 units afterwards. 

1743 at 

1744 The inputs that are the same for all trees. 

1745 pt 

1746 The inputs that are separate for each tree. 

1747 use 

1748 If `False`, leave the residuals unchanged, and the other outputs are to 

1749 be discarded. `None` is equivalent to `True`. 

1750 

1751 Returns 

1752 ------- 

1753 resid : Float[Array, 'n'] | Float[Array, ' k n'] 

1754 The updated residuals, in the same stored units and dtype as the input. 

1755 out : SeqStageOutPerTree 

1756 The other outputs. 

1757 """ 

1758 leaf_indices = at.leaf_indices[pt.tree_index, :] 

1759 

1760 # sum residuals in each leaf, in tree proposed by grow move 

1761 if at.prec_scale is None: 

1762 scaled_resid = resid 

1763 else: 

1764 scaled_resid = resid * at.prec_scale 

1765 

1766 *_, max_num_leaves = pt.leaf_tree.shape 

1767 

1768 resid_tree = sum_resid( 

1769 scaled_resid, 

1770 leaf_indices, 

1771 max_num_leaves, 

1772 at.resid_reduction_config, 

1773 at.data_sharded, 

1774 ) 

1775 

1776 # the residuals are stored and reduced in units of `resid_unit` (and a 

1777 # possibly narrow dtype) for bandwidth; the float32 per-leaf sums are scaled 

1778 # back to data units here, after the reduction and before everything else. 

1779 # with error scales, the sums keep the stored `prec_scale` units, whose 

1780 # `inv_sdev_unit ** 2` factor is folded into the error precision instead 

1781 resid_tree *= at.resid_unit[..., None] 

1782 

1783 # convert the starting tree to data units; multiplying by the float32 

1784 # scale also takes care of upcasting narrow leaf dtypes 

1785 prev_leaf_tree = at.leaf_unit[..., None] * pt.leaf_tree 

1786 

1787 # subtract starting tree from function 

1788 resid_tree += pt.prec_tree * prev_leaf_tree 

1789 

1790 # sum residuals in parent node modified by move and compute likelihood; 

1791 # the parent goes after the leaves, where `prelf` has its terms 

1792 assert pt.move.lr_leaves.dtype == jnp.int32 

1793 resid_lrt = append_total(resid_tree[..., pt.move.lr_leaves]) 

1794 resid_tree = jnp.concatenate([resid_tree, resid_lrt[..., 2:]], axis=-1) 

1795 

1796 log_lk_ratio = compute_likelihood_ratio(resid_lrt, pt.prelkv, at.error_cov_inv) 

1797 

1798 # calculate accept/reject ratio; the ratio is filled in by `complete_ratio` 

1799 assert pt.move.log_trans_prior_ratio is not None 

1800 log_ratio = pt.move.log_trans_prior_ratio + log_lk_ratio 

1801 log_ratio = jnp.where(pt.move.grow, log_ratio, -log_ratio) 

1802 if not at.save_ratios: 

1803 log_lk_ratio = None 

1804 

1805 # determine whether to accept the move 

1806 acc = pt.move.allowed & (pt.move.logu <= log_ratio) 

1807 

1808 # compute leaves posterior and sample leaves 

1809 if at.error_cov_inv is not None: 

1810 # multivariate w/ per-component error scales 

1811 b_tree = compute_B(at.error_cov_inv, resid_tree) 

1812 mean_post = solve_leaf(pt.prelf.mean_factor, b_tree) 

1813 elif resid.ndim > 1: 

1814 # multivariate homoskedastic or scalar error scales 

1815 mean_post = jnp.einsum('kil,kl->il', pt.prelf.mean_factor, resid_tree) 

1816 else: 

1817 # univariate 

1818 mean_post = resid_tree * pt.prelf.mean_factor 

1819 leaf_tree = mean_post + pt.prelf.centered_leaves 

1820 

1821 # split the parent off the leaves; if it ends up a leaf, copy its value 

1822 # to the indices of its children, such that the leaf indices point to the 

1823 # correct leaf. The left one is its own index, while the mirroring on the 

1824 # right one persists into the output state, where it keeps the 

1825 # not-yet-pruned `leaf_indices` valid to evaluate the trees 

1826 to_prune = acc ^ pt.move.grow 

1827 leaf_tree = set_leaf_pair( 

1828 leaf_tree[..., :max_num_leaves], 

1829 leaf_tree[..., max_num_leaves:], 

1830 to_prune, 

1831 pt.move.lr_leaves, 

1832 ) 

1833 

1834 # round the new leaves to the storage units and dtype; the residuals are 

1835 # then updated with the rounded values to stay consistent with the trees 

1836 leaf_tree = leaf_tree / at.leaf_unit[..., None] 

1837 if at.leaf_quantization is not None: 

1838 # quantize the leaves such that the residual updates below are mostly 

1839 # exact. the target grid is the spacing of `resid.dtype` values of 

1840 # magnitude 2^leaf_quantization in units of the measured residual 

1841 # scale, so 2^(leaf_quantization - nmant) * resid_eff_scale in data 

1842 # units; dividing by leaf_unit converts it to the leaf units 

1843 # `leaf_tree` is in here. the scales are powers of two, so the quantum 

1844 # is one too and the leaf storage dtype's own (coarser) rounding below 

1845 # preserves multiples of it. 

1846 nmant = jnp.finfo(resid.dtype).nmant 

1847 quantum = (at.resid_eff_scale / at.leaf_unit) * 2.0 ** ( 

1848 at.leaf_quantization - nmant 

1849 ) 

1850 leaf_tree = jnp.round(leaf_tree / quantum[..., None]) * quantum[..., None] 

1851 # round to the storage dtype explicitly before converting: xla's 

1852 # excess-precision optimization (on by default) may otherwise elide the 

1853 # narrowing conversion in the `leaf_delta` computation below, updating the 

1854 # residuals with unrounded leaves while the trees store rounded ones 

1855 finfo = jnp.finfo(pt.leaf_tree.dtype) 

1856 leaf_tree = lax.reduce_precision(leaf_tree, finfo.nexp, finfo.nmant) 

1857 leaf_tree = leaf_tree.astype(pt.leaf_tree.dtype) 

1858 

1859 # replace old tree with new tree in function values; the per-leaf data-unit 

1860 # delta is converted back to the stored residual units and dtype *before* the 

1861 # scatter, so the n-sized update stays in the narrow `resid` storage 

1862 leaf_delta = prev_leaf_tree - at.leaf_unit[..., None] * leaf_tree 

1863 # `resid_unit` is a power of 2, so its reciprocal is exact 

1864 inv_resid_unit = jnp.reciprocal(at.resid_unit) 

1865 if use is not None: 

1866 # the conversion factor zeroes the delta of a tree not in use, instead 

1867 # of an elementwise select that xla on gpu would repeat for each 

1868 # datapoint 

1869 inv_resid_unit = jnp.where(use, inv_resid_unit, 0.0) 

1870 delta = (leaf_delta * inv_resid_unit[..., None]).astype(resid.dtype) 

1871 # on cpu, materialize the per-leaf delta, else xla fuses its computation 

1872 # into the gather and repeats it for each datapoint; on gpu that is cheaper 

1873 # than the extra kernel launch 

1874 delta = cpu_barrier(delta) 

1875 resid += delta[..., leaf_indices] 

1876 

1877 out = SeqStageOutPerTree( 

1878 acc=acc, to_prune=to_prune, leaf_tree=leaf_tree, log_lk_ratio=log_lk_ratio 

1879 ) 

1880 return resid, out 

1881 

1882 

1883@named_call 

1884def sum_resid( 

1885 scaled_resid: Float[Array, ' n'] | Float[Array, 'k n'] | Float[Array, 'k k n'], 

1886 leaf_indices: UInt[Array, ' n'], 

1887 max_num_leaves: int, 

1888 reduction_config: ReductionConfig, 

1889 data_sharded: bool, 

1890) -> ( 

1891 Float32[Array, ' {max_num_leaves}'] 

1892 | Float32[Array, 'k {max_num_leaves}'] 

1893 | Float32[Array, 'k k {max_num_leaves}'] 

1894): 

1895 """ 

1896 Sum the residuals in each leaf. 

1897 

1898 Parameters 

1899 ---------- 

1900 scaled_resid 

1901 The residuals (data minus forest value) multiplied by the error 

1902 precision scale. 

1903 leaf_indices 

1904 The leaf indices of the tree (in which leaf each data point falls into). 

1905 max_num_leaves 

1906 The size of the leaf arrays, see `bartz.mcmcstep.Forest.leaf_tree`. 

1907 reduction_config 

1908 How to sum the residuals in each leaf. 

1909 data_sharded 

1910 Whether the data axis is sharded; if true, the result is psum-reduced 

1911 across the ``'data'`` axis of the enclosing `shard_map`. 

1912 

1913 Returns 

1914 ------- 

1915 The per-leaf sum, with the same leading dimensions as ``scaled_resid`` and a trailing axis over the leaves. 

1916 """ 

1917 return reduction_config._reduce( # noqa: SLF001 

1918 scaled_resid, 

1919 leaf_indices, 

1920 size=max_num_leaves, 

1921 dtype=jnp.float32, 

1922 data_sharded=data_sharded, 

1923 ) 

1924 

1925 

1926def _compute_likelihood_ratio_uv( 

1927 resid_lrt: Float32[Array, ' 3'], prelkv: PreLkV 

1928) -> Float32[Array, '']: 

1929 # quadratic form r * v * r for each of the (left, right, total) terms 

1930 qf = resid_lrt * resid_lrt * prelkv.lrt 

1931 exp_term = 0.5 * (qf @ jnp.array([1.0, 1.0, -1.0])) 

1932 return prelkv.log_sqrt_term + exp_term 

1933 

1934 

1935def _compute_likelihood_ratio_mv( 

1936 resid_lrt: Float32[Array, 'k 3'], prelkv: PreLkV 

1937) -> Float32[Array, '']: 

1938 # quadratic form r' M r for each of the (left, right, total) terms 

1939 qf = jnp.einsum('it,tij,jt->t', resid_lrt, prelkv.lrt, resid_lrt) 

1940 exp_term = 0.5 * (qf @ jnp.array([1.0, 1.0, -1.0])) 

1941 return prelkv.log_sqrt_term + exp_term 

1942 

1943 

1944def _compute_likelihood_ratio_mv_het( 

1945 resid_lrt: Float32[Array, 'k k 3'], 

1946 error_cov_inv: Float32[Array, 'k k'], 

1947 prelkv: PreLkV, 

1948) -> Float32[Array, '']: 

1949 b = compute_B(error_cov_inv, resid_lrt) # (k, 3) 

1950 y = solve_triangular(prelkv.lrt, b.T[..., None], lower=True).squeeze(-1) # (3, k) 

1951 qf = jnp.einsum('ti,ti->t', y, y) 

1952 exp_term = 0.5 * (qf @ jnp.array([1.0, 1.0, -1.0])) 

1953 return prelkv.log_sqrt_term + exp_term 

1954 

1955 

1956@named_call 

1957def compute_likelihood_ratio( 

1958 resid_lrt: (Float32[Array, ' 3'] | Float32[Array, 'k 3'] | Float32[Array, 'k k 3']), 

1959 prelkv: PreLkV, 

1960 error_cov_inv: Float32[Array, 'k k'] | None, 

1961) -> Float32[Array, '']: 

1962 """ 

1963 Compute the likelihood ratio of a grow move. 

1964 

1965 Parameters 

1966 ---------- 

1967 resid_lrt 

1968 The sum of the residuals (scaled by error precision scale) of the 

1969 datapoints falling in the left child, right child, and parent node 

1970 involved in the move, stacked along the trailing axis. 

1971 prelkv 

1972 The pre-computed terms of the likelihood ratio, see 

1973 `precompute_likelihood_terms`. 

1974 error_cov_inv 

1975 The global error precision scale, with the squared `inv_sdev_unit` folded 

1976 in (see `bartz.mcmcstep.State.inv_sdev_unit`). Set only in the 

1977 multivariate case with per-component error scales. 

1978 

1979 Returns 

1980 ------- 

1981 The log-likelihood ratio log P(data | new tree) - log P(data | old tree). 

1982 """ 

1983 if error_cov_inv is not None: 

1984 return _compute_likelihood_ratio_mv_het(resid_lrt, error_cov_inv, prelkv) 

1985 elif resid_lrt.ndim > 1: 

1986 return _compute_likelihood_ratio_mv(resid_lrt, prelkv) 

1987 else: 

1988 return _compute_likelihood_ratio_uv(resid_lrt, prelkv) 

1989 

1990 

1991@named_call 

1992def accept_moves_final_stage(state: State, moves: Moves) -> State: 

1993 """ 

1994 Post-process the mcmc state after accepting/rejecting the moves. 

1995 

1996 This function is separate from `accept_moves_sequential_stage` to signal it 

1997 can work in parallel across trees. 

1998 

1999 The prunes are not applied to `bartz.mcmcstep.Forest.leaf_indices` here; 

2000 they are recorded in `to_prune`/`move_node` and applied at the beginning of 

2001 the next step. 

2002 

2003 Parameters 

2004 ---------- 

2005 state 

2006 A partially updated BART mcmc state. 

2007 moves 

2008 The proposed moves (see `propose_moves`) as updated by 

2009 `accept_moves_sequential_stage`. 

2010 

2011 Returns 

2012 ------- 

2013 The fully updated BART mcmc state. 

2014 """ 

2015 assert moves.acc is not None 

2016 assert moves.to_prune is not None 

2017 return replace( 

2018 state, 

2019 forest=replace( 

2020 state.forest, 

2021 grow_acc_count=jnp.sum(moves.acc & moves.grow), 

2022 prune_acc_count=jnp.sum(moves.acc & ~moves.grow), 

2023 to_prune=moves.to_prune, 

2024 move_node=moves.lrt_nodes[..., 2], 

2025 tree_life=update_tree_life(state.forest.tree_life, moves), 

2026 split_tree=apply_moves_to_split_trees(state.forest.split_tree, moves), 

2027 affluence_tree=apply_moves_to_affluence_trees( 

2028 state.forest.affluence_tree, moves 

2029 ), 

2030 ), 

2031 ) 

2032 

2033 

2034def update_tree_life( 

2035 tree_life: Int32[Array, ' num_trees'], moves: Moves 

2036) -> Int32[Array, ' num_trees']: 

2037 """Age the trees by one step, resetting those just pruned to a lone root.""" 

2038 assert moves.acc is not None 

2039 pruned_to_root = moves.acc & ~moves.grow & (moves.lrt_nodes[:, 2] == 1) 

2040 return jnp.where(pruned_to_root, 0, tree_life + 1) 

2041 

2042 

2043@named_call 

2044def apply_moves_to_leaf_indices( 

2045 leaf_indices: UInt[Array, 'num_trees n'], 

2046 to_prune: Bool[Array, ' num_trees'], 

2047 move_node: Int32[Array, ' num_trees'], 

2048) -> UInt[Array, 'num_trees n']: 

2049 """ 

2050 Apply the prunes pending from the previous step to the leaf indices. 

2051 

2052 Parameters 

2053 ---------- 

2054 leaf_indices 

2055 The index of the leaf each datapoint falls into, in the largest version 

2056 of each tree compatible with the last moves (see 

2057 `Forest.leaf_indices`). 

2058 to_prune 

2059 Whether the last move on each tree ended in a prune yet to be applied. 

2060 move_node 

2061 The node the last move on each tree operated on. 

2062 

2063 Returns 

2064 ------- 

2065 The updated leaf indices. 

2066 """ 

2067 return _apply_moves_to_leaf_indices(leaf_indices, to_prune, move_node) 

2068 

2069 

2070@vmap 

2071def _apply_moves_to_leaf_indices( 

2072 leaf_indices: UInt[Array, ' n'], 

2073 to_prune: Bool[Array, ''], 

2074 move_node: Int32[Array, ''], 

2075) -> UInt[Array, ' n']: 

2076 """Implement `apply_moves_to_leaf_indices`.""" 

2077 # the left child shares its index with the node 

2078 left = node_to_leaf_index(move_node).astype(leaf_indices.dtype) 

2079 right = move_node.astype(leaf_indices.dtype) 

2080 return jnp.where(to_prune & (leaf_indices == right), left, leaf_indices) 

2081 

2082 

2083@named_call 

2084def apply_moves_to_split_trees( 

2085 split_tree: UInt[Array, 'num_trees max_num_leaves'], moves: Moves 

2086) -> UInt[Array, 'num_trees max_num_leaves']: 

2087 """ 

2088 Update the split trees to match the accepted move. 

2089 

2090 Parameters 

2091 ---------- 

2092 split_tree 

2093 The cutpoints of the decision nodes in the initial trees. 

2094 moves 

2095 The proposed moves (see `propose_moves`), as updated by 

2096 `accept_moves_sequential_stage`. 

2097 

2098 Returns 

2099 ------- 

2100 The updated split trees. 

2101 """ 

2102 return _apply_moves_to_split_trees(split_tree, moves) 

2103 

2104 

2105@vmap 

2106def _apply_moves_to_split_trees( 

2107 split_tree: UInt[Array, ' max_num_leaves'], moves: Moves 

2108) -> UInt[Array, ' max_num_leaves']: 

2109 """Implement `apply_moves_to_split_trees`.""" 

2110 assert moves.to_prune is not None 

2111 # a single scatter serves both cases: an accepted grow writes the new 

2112 # cutpoint, while pruning (accepted prune or rejected grow) zeroes the node 

2113 return split_tree.at[ 

2114 jnp.where(moves.grow | moves.to_prune, moves.lrt_nodes[2], split_tree.size) 

2115 ].set(jnp.where(moves.to_prune, 0, moves.grow_split).astype(split_tree.dtype)) 

2116 

2117 

2118@named_call 

2119def apply_moves_to_affluence_trees( 

2120 affluence_tree: Bool[Array, 'num_trees max_num_leaves'], moves: Moves 

2121) -> Bool[Array, 'num_trees max_num_leaves']: 

2122 """ 

2123 Update the affluence trees to match the accepted move. 

2124 

2125 The affluence tree marks the growable leaves; this restores that invariant 

2126 after the move by re-marking only the nodes it touched, starting from the 

2127 clean pre-move mask. 

2128 

2129 Parameters 

2130 ---------- 

2131 affluence_tree 

2132 The mask of the growable leaves in the initial trees. 

2133 moves 

2134 The proposed moves (see `propose_moves`), as updated by 

2135 `accept_moves_sequential_stage`. 

2136 

2137 Returns 

2138 ------- 

2139 The updated affluence trees. 

2140 """ 

2141 return _apply_moves_to_affluence_trees(affluence_tree, moves) 

2142 

2143 

2144@vmap 

2145def _apply_moves_to_affluence_trees( 

2146 affluence_tree: Bool[Array, ' max_num_leaves'], moves: Moves 

2147) -> Bool[Array, ' max_num_leaves']: 

2148 """Implement `apply_moves_to_affluence_trees`.""" 

2149 assert moves.to_prune is not None 

2150 assert moves.lrt_affluent is not None 

2151 # GROW: node becomes internal, children become leaves with their affluence. 

2152 # PRUNE (accepted prune or rejected grow): node becomes a leaf with its 

2153 # affluence, children are deleted. Either way all three nodes are written: 

2154 # the mask keeps the affluence of the nodes that become leaves and zeroes 

2155 # the rest. If no move is applied (a rejected prune), the indices resolve 

2156 # to `size` and the writes drop. 

2157 becomes_leaf = moves.to_prune ^ jnp.array([True, True, False]) 

2158 return affluence_tree.at[ 

2159 jnp.where(moves.grow | moves.to_prune, moves.lrt_nodes, affluence_tree.size) 

2160 ].set(moves.lrt_affluent & becomes_leaf) 

2161 

2162 

2163@jit 

2164def _sample_wishart_bartlett( 

2165 key: Key[Array, ''], 

2166 df: Float32[Array, ''] | float, 

2167 scale_inv: Float32[Array, 'k k'], 

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

2169 """ 

2170 Sample a precision matrix W ~ Wishart(df, scale_inv^-1) using Bartlett decomposition. 

2171 

2172 Parameters 

2173 ---------- 

2174 key 

2175 A JAX random key 

2176 df 

2177 Degrees of freedom 

2178 scale_inv 

2179 Scale matrix of the corresponding Inverse Wishart distribution 

2180 

2181 Returns 

2182 ------- 

2183 A sample from Wishart(df, scale) 

2184 """ 

2185 keys = split(key) 

2186 

2187 # Diagonal elements: A_ii ~ sqrt(chi^2(df - i)), with chi^2(k) = Gamma(k/2, scale=2). 

2188 # sqrt(2 * Gamma) = sqrt(2) * exp(loggamma / 2), folding the sqrt into the exp. 

2189 k, _ = scale_inv.shape 

2190 df_vector = df - jnp.arange(k) 

2191 diag_A = jnp.sqrt(2.0) * jnp.exp(loggamma(keys.pop(), df_vector / 2.0) / 2.0) 

2192 

2193 off_diag_A = random.normal(keys.pop(), (k, k)) 

2194 A = jnp.tril(off_diag_A, -1) + jnp.diag(diag_A) 

2195 L = chol_with_gersh(scale_inv, absolute_eps=True) 

2196 T = solve_triangular(L, A, lower=True, trans='T') 

2197 

2198 return T @ T.T 

2199 

2200 

2201def sample_wishart_posterior( 

2202 key: Key[Array, ''], 

2203 prior: Wishart, 

2204 count: Int32[Array, ''] | Int32[Array, ' k'], 

2205 scatter: Float32[Array, ''] | Float32[Array, ' k'] | Float32[Array, 'k k'], 

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

2207 """Draw a precision matrix from its conjugate posterior. 

2208 

2209 Parameters 

2210 ---------- 

2211 key 

2212 A jax random key. 

2213 prior 

2214 The prior on the precision; `Wishart.nu` and `Wishart.rate` must be set. 

2215 count 

2216 The number of observations. It can vary per component only with a 

2217 `DiagWishart` prior. Fractional counts are not supported. 

2218 scatter 

2219 The sum of the outer products of the observations: the full matrix with 

2220 a dense `Wishart` prior, only its diagonal with a `DiagWishart`, a 

2221 scalar sum of squares in the univariate case. 

2222 

2223 Returns 

2224 ------- 

2225 A draw from the posterior, with the same shape as `Wishart.rate`. 

2226 """ 

2227 assert prior.nu is not None 

2228 assert prior.rate is not None 

2229 

2230 if prior.rate.ndim == 2 and not isinstance(prior, DiagWishart): 

2231 assert scatter.shape == prior.rate.shape 

2232 return _sample_wishart_bartlett(key, prior.nu + count, prior.rate + scatter) 

2233 else: 

2234 # independent gamma per component; the variance df matches the inverse 

2235 # wishart marginals 

2236 marginal_nu = prior.inv_wishart_marginal_nu 

2237 assert marginal_nu is not None 

2238 alpha = marginal_nu / 2 + count / 2 

2239 

2240 kshape = prior.rate.shape[:1] 

2241 assert scatter.shape == kshape 

2242 rate = jnp.diagonal(prior.rate) if kshape else prior.rate 

2243 beta = rate / 2 + scatter / 2 

2244 

2245 # draw the gamma from the first of a split, mirroring the Bartlett 

2246 # sampler in the dense path so the two branches coincide at k=1 

2247 keys = split(key) 

2248 prec = jnp.exp(loggamma(keys.pop(), alpha, kshape)) / beta 

2249 if kshape: 

2250 prec = jnp.diag(prec) 

2251 return prec 

2252 

2253 

2254def step_resid_eff_scale( 

2255 state: State, 

2256 norm2: Float32[Array, ''] | Float32[Array, ' k'], 

2257 prec_sum: Float32[Array, ''] | Float32[Array, ' k'], 

2258) -> State: 

2259 """Update `State.resid_eff_scale` with the measured scale of the residuals. 

2260 

2261 Parameters 

2262 ---------- 

2263 state 

2264 A BART MCMC state. 

2265 norm2 

2266 The squared (precision-scaled, masked) norm of the residuals in data units. 

2267 prec_sum 

2268 The sum of the precision scales (unmasked-datapoint count without 

2269 error scales), matching the scaling of `norm2`. 

2270 

2271 Returns 

2272 ------- 

2273 The state with `resid_eff_scale` set to the residual rms rounded to a power of two. 

2274 """ 

2275 scale = round_to_pow2(jnp.sqrt(norm2 / prec_sum)) 

2276 # keep the previous scale if the residuals vanish 

2277 scale = jnp.where(scale == 0, state.resid_eff_scale, scale) 

2278 return replace(state, resid_eff_scale=scale) 

2279 

2280 

2281def _step_error_cov_inv_mv(key: Key[Array, ''], state: State) -> State: 

2282 # keep the residuals in their stored (narrow) dtype and resid_unit units; 

2283 # the reduction accumulates in float32 and its (k, k) result is rescaled to 

2284 # data units, so no n-sized float32 array is ever materialized 

2285 resid = state.resid 

2286 if state.inv_sdev_scale is not None: 

2287 resid *= state.inv_sdev_scale 

2288 

2289 # unit of the stored precision-scaled residuals: `resid` is in `resid_unit` 

2290 # units and `inv_sdev_scale` in `inv_sdev_unit` units (1 without error 

2291 # scales, per-component with 2-D `inv_sdev_scale`) 

2292 scale = state.resid_unit * state.inv_sdev_unit 

2293 

2294 rrt = jnp.einsum( 

2295 'an,bn->ab', resid, resid, preferred_element_type=jnp.float32 

2296 ) * jnp.outer(scale, scale) 

2297 if state.config.data_sharded: 

2298 rrt = lax.psum(rrt, 'data') 

2299 

2300 # we take the max as a way to take any of the in this case equal values in 

2301 # n_non_missing 

2302 count = jnp.max(state.n_non_missing) 

2303 

2304 prec = sample_wishart_posterior(key, state.error_cov_inv, count, rrt) 

2305 state = step_resid_eff_scale(state, jnp.diagonal(rrt), state.sum_diag_prec_scale) 

2306 return replace(state, error_cov_inv=replace(state.error_cov_inv, value=prec)) 

2307 

2308 

2309def _step_error_cov_inv_diag(key: Key[Array, ''], state: State) -> State: 

2310 """Per-component inverse-gamma update for univariate, mixed, and partial-missing paths.""" 

2311 # keep the residuals in their stored (narrow) dtype and resid_unit units; 

2312 # the reduction accumulates in float32 and its small result is rescaled to 

2313 # data units, so no n-sized float32 array is ever materialized 

2314 resid = state.resid 

2315 if state.inv_sdev_scale is not None: 

2316 resid *= state.inv_sdev_scale 

2317 

2318 # `resid` is stored in `resid_unit` units and `inv_sdev_scale` in 

2319 # `inv_sdev_unit` units (1 without error scales) 

2320 norm2 = jnp.einsum( 

2321 '...n,...n->...', resid, resid, preferred_element_type=jnp.float32 

2322 ) * jnp.square(state.resid_unit * state.inv_sdev_unit) 

2323 if state.config.data_sharded: 

2324 norm2 = lax.psum(norm2, 'data') 

2325 

2326 prec = sample_wishart_posterior( 

2327 key, state.error_cov_inv, state.n_non_missing, norm2 

2328 ) 

2329 if state.binary_indices is not None: 

2330 # the binary components have unit error variance, they have no prior 

2331 prec = prec.at[state.binary_indices, state.binary_indices].set( 

2332 1.0, unique_indices=True 

2333 ) 

2334 state = step_resid_eff_scale(state, norm2, state.sum_diag_prec_scale) 

2335 return replace(state, error_cov_inv=replace(state.error_cov_inv, value=prec)) 

2336 

2337 

2338@named_call 

2339def step_error_cov_inv(key: Key[Array, ''], state: State) -> State: 

2340 """MCMC-update the inverse error covariance, if it has a prior.""" 

2341 if state.error_cov_inv.nu is None: 

2342 return state 

2343 elif state.error_cov_inv.value.ndim == 2 and not isinstance( 

2344 state.error_cov_inv, DiagWishart 

2345 ): 

2346 return _step_error_cov_inv_mv(key, state) 

2347 else: 

2348 return _step_error_cov_inv_diag(key, state) 

2349 

2350 

2351def leaf_scatter( 

2352 forest: Forest, 

2353) -> tuple[Int32[Array, ''], Float32[Array, ''] | Float32[Array, 'k k']]: 

2354 """Count the leaves of the trees in use and sum their outer products. 

2355 

2356 Parameters 

2357 ---------- 

2358 forest 

2359 The forest, with no chain axis. 

2360 

2361 Returns 

2362 ------- 

2363 count : Int32[Array, ''] 

2364 The total number of leaves over the trees in use. 

2365 scatter : Float32[Array, ''] | Float32[Array, 'k k'] 

2366 The sum over the leaves of the outer product of the values, in data units. 

2367 """ 

2368 # the value on the dangling right child of a pruned node mirrors the 

2369 # parent's, so mask on the actual leaves only 

2370 is_leaf = is_leaf_used(forest.split_tree) 

2371 used = used_trees_mask(forest) 

2372 if used is not None: 

2373 is_leaf &= used[:, None] 

2374 count = jnp.sum(is_leaf) 

2375 leaf_tree = forest.leaf_tree 

2376 if leaf_tree.ndim == 3: 

2377 scatter = jnp.einsum( 

2378 'tan,tbn,tn->ab', 

2379 leaf_tree, 

2380 leaf_tree, 

2381 is_leaf, 

2382 preferred_element_type=jnp.float32, 

2383 ) 

2384 scatter *= jnp.outer(forest.leaf_unit, forest.leaf_unit) 

2385 else: 

2386 scatter = jnp.einsum( 

2387 'tn,tn,tn->', 

2388 leaf_tree, 

2389 leaf_tree, 

2390 is_leaf, 

2391 preferred_element_type=jnp.float32, 

2392 ) 

2393 scatter *= jnp.square(forest.leaf_unit) 

2394 return count, scatter 

2395 

2396 

2397@named_call 

2398def step_sum_trees_prior_cov_inv(key: Key[Array, ''], state: State) -> State: 

2399 """MCMC-update the sum of trees prior precision from its conjugate posterior, if it has a prior.""" 

2400 prior = state.forest.sum_trees_prior_cov_inv 

2401 if prior.nu is None: 

2402 return state 

2403 else: 

2404 count, scatter = leaf_scatter(state.forest) 

2405 # the precision of a leaf is the one of the sum times the trees in use 

2406 scatter *= num_used_trees(state.forest) 

2407 prec = sample_wishart_posterior(key, prior, count, scatter) 

2408 return replace( 

2409 state, 

2410 forest=replace( 

2411 state.forest, sum_trees_prior_cov_inv=replace(prior, value=prec) 

2412 ), 

2413 ) 

2414 

2415 

2416@named_call 

2417def step_z(key: Key[Array, ''], state: State) -> State: 

2418 """ 

2419 MCMC-update the latent variable for binary regression, if any. 

2420 

2421 Parameters 

2422 ---------- 

2423 key 

2424 A jax random key. 

2425 state 

2426 A BART MCMC state. 

2427 

2428 Returns 

2429 ------- 

2430 The updated BART MCMC state. 

2431 """ 

2432 if state.z is None: 

2433 return state 

2434 

2435 inv_sdev = state.inv_sdev_scale 

2436 inv_sdev_unit = state.inv_sdev_unit 

2437 err_scale = state.error_scale 

2438 if state.binary_indices is not None: 

2439 resid_unit = state.resid_unit[state.binary_indices] 

2440 resid = state.resid[state.binary_indices, :] 

2441 binary_y = state.y[state.binary_indices, :] != 0 

2442 # per-component scales (2-D) are restricted to the binary components; 

2443 # a scalar-per-datapoint scale (1-D) is shared and broadcasts as-is 

2444 if inv_sdev is not None and inv_sdev.ndim > 1: 

2445 inv_sdev = inv_sdev[state.binary_indices, :] 

2446 inv_sdev_unit = inv_sdev_unit[state.binary_indices] 

2447 if err_scale is not None and err_scale.ndim > 1: 

2448 err_scale = err_scale[state.binary_indices, :] 

2449 else: 

2450 resid_unit = state.resid_unit 

2451 resid = state.resid 

2452 binary_y = state.y != 0 

2453 

2454 trees_plus_offset = state.z - resid * resid_unit[..., None] 

2455 if state.config.data_sharded: 

2456 # decorrelate the seed across data shards; the seed is replicated 

2457 # because the trees and most of the algorithm are replicated 

2458 key = random.fold_in(key, lax.axis_index('data')) 

2459 

2460 if err_scale is None: 

2461 # homoskedastic probit: the latent error has unit scale. A missingness 

2462 # mask (without error scales) needs no handling here: masked points are 

2463 # dropped from the likelihood, so their latent is sampled like any other. 

2464 resid = truncated_normal_onesided(key, (), ~binary_y, -trees_plus_offset) 

2465 else: 

2466 # heteroskedastic probit: the latent error has per-datapoint scale 

2467 # `err_scale`, so threshold in standardized units, then rescale. 

2468 assert inv_sdev is not None 

2469 # masked datapoints draw garbage, but every consumer of `resid` scales 

2470 # it by the (zero) `inv_sdev`, so the value is irrelevant as long as finite 

2471 resid = err_scale * truncated_normal_onesided( 

2472 key, (), ~binary_y, -trees_plus_offset * inv_sdev * inv_sdev_unit[..., None] 

2473 ) 

2474 z = trees_plus_offset + resid 

2475 

2476 resid = (resid / resid_unit[..., None]).astype(state.resid.dtype) 

2477 if state.binary_indices is not None: 

2478 resid = state.resid.at[state.binary_indices, :].set(resid, unique_indices=True) 

2479 

2480 return replace(state, z=z, resid=resid) 

2481 

2482 

2483# the log of a magnitude beyond which random fluctuations of the size of its 

2484# square root are below float32 resolution 

2485LOG_HUGE = 20 * math.log(10) 

2486 

2487 

2488class S(Module): 

2489 """Split probabilities, with the largest ones singled out.""" 

2490 

2491 log_s: Float32[Array, ' p'] 

2492 """The log split probabilities normalized over the selectable variables, 

2493 -inf for the others.""" 

2494 

2495 log_top: Float32[Array, ' m'] 

2496 """The largest log split probabilities.""" 

2497 

2498 top_bit: UInt32[Array, ' p'] 

2499 """``2^i`` for the variable with the i-th largest split probability, 0 for 

2500 the others.""" 

2501 

2502 log_rest: Float32[Array, ''] 

2503 """The log total split probability of the variables not in `log_top`.""" 

2504 

2505 rest_ratio: Float32[Array, ' p'] 

2506 """The split probability of each variable relative to the total of the 

2507 variables not in `log_top`, 0 for those in `log_top`.""" 

2508 

2509 @classmethod 

2510 def from_log_s( 

2511 cls, log_s: Float32[Array, ' p'], selectable: Bool[Array, ' p'], num_top: int 

2512 ) -> 'S': 

2513 """Normalize `log_s` and single out its `num_top` largest values.""" 

2514 # mask and normalize log_s, all -inf if no variable is selectable 

2515 log_s = log_softmax(log_s, where=selectable) 

2516 

2517 # find the top probabilities 

2518 (p,) = log_s.shape 

2519 num_top = min(num_top, p) 

2520 log_top, top_vars = lax.top_k(log_s, num_top) 

2521 

2522 # index the top probabilities as bit positions 

2523 assert num_top <= 32 # the bits fit in uint32 

2524 top_bit = ( 

2525 jnp.zeros(p, jnp.uint32) 

2526 .at[top_vars] 

2527 .set(jnp.uint32(1) << jnp.arange(num_top, dtype=jnp.uint32)) 

2528 ) 

2529 

2530 # compute the total probability of other values 

2531 log_rest_s = log_s.at[top_vars].set(-jnp.inf) 

2532 log_rest = logsumexp(log_rest_s) 

2533 

2534 # 0 for the top and unselectable variables, also when there are no others 

2535 rest_ratio = jnp.where( 

2536 jnp.isneginf(log_rest_s), 0.0, jnp.exp(log_rest_s - log_rest) 

2537 ) 

2538 

2539 return cls( 

2540 log_s=log_s, 

2541 log_top=log_top, 

2542 top_bit=top_bit, 

2543 log_rest=log_rest, 

2544 rest_ratio=rest_ratio, 

2545 ) 

2546 

2547 

2548def log_blocked_mass_tree( 

2549 key: Key[Array, ''], 

2550 var_tree: UInt[Array, ' max_num_leaves'], 

2551 split_tree: UInt[Array, ' max_num_leaves'], 

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

2553 s: S, 

2554) -> tuple[Int32[Array, ' max_num_leaves//2'], Float32[Array, ' max_num_leaves//2']]: 

2555 """Data-augmentation mass blocked by a single tree, per blocking node. 

2556 

2557 At each internal node, draws the latent augmentation weight ``lambda / e`` 

2558 (``lambda`` exponential, ``e`` the eligible split probability mass at the 

2559 node), to add to every variable ineligible at that node. A node makes its 

2560 splitting variable ineligible in the subtrees of the children where it 

2561 exhausts the cutpoints, so the mass blocked for a variable is the sum, over 

2562 the nodes splitting on it, of the weights in those subtrees. 

2563 

2564 Parameters 

2565 ---------- 

2566 key 

2567 Random key for sampling. 

2568 var_tree 

2569 The splitting axes of the tree. 

2570 split_tree 

2571 The splitting points of the tree. 

2572 max_split 

2573 The maximum split index for each variable. 

2574 s 

2575 Split probabilities normalized over selectable variables, with the 

2576 largest ones singled out. 

2577 

2578 Returns 

2579 ------- 

2580 var : Int32[Array, ' max_num_leaves//2'] 

2581 The splitting variable of each node in the upper half of the heap, `p` 

2582 at non-internal nodes. 

2583 log_mass : Float32[Array, ' max_num_leaves//2'] 

2584 The log of the mass the node blocks for its variable. 

2585 """ 

2586 (max_num_leaves,) = split_tree.shape 

2587 max_depth = max_num_leaves.bit_length() - 1 

2588 p = max_split.size 

2589 nodes = jnp.arange(max_num_leaves) 

2590 split = split_tree.astype(jnp.int32) 

2591 is_internal = split_tree.astype(bool) 

2592 

2593 # Range [lo, hi) of cutpoints still available for each node's own splitting 

2594 # variable, given the constraints inherited from the ancestors. 

2595 lo, hi = vmap(split_range, in_axes=(None, None, None, 0, 0))( 

2596 var_tree, split_tree, max_split, nodes, var_tree 

2597 ) 

2598 

2599 # An internal node exhausts its own variable for a child when its cutpoint 

2600 # sits at the matching end of the available range, so the variable becomes 

2601 # ineligible throughout that child's subtree. Row 0 is the left child (low 

2602 # end lo), row 1 the right child (high end hi - 1). 

2603 blocks = is_internal & (split == jnp.stack([lo, hi - 1])) 

2604 

2605 # A node can block at most its own splitting variable, so the per-variable 

2606 # totals are recovered from these per-node blocks via top-down/bottom-up 

2607 # accumulation over depth levels, rather than scanning each node's ancestors. 

2608 

2609 # Ineligible mass per node: the s-mass of the variables blocked along the 

2610 # path from the root. Each variable is blocked at exactly one node per path, 

2611 # so summing the per-node increments top-down reproduces the per-node sum 

2612 # over distinct ineligible variables. The variables with the largest 

2613 # split probabilities are tracked as bits instead, as subtracting their 

2614 # mass from 1 would cancel. As the bits do not repeat along a path, summing 

2615 # them is the same as or-ing them. 

2616 parent = nodes >> 1 

2617 side = nodes & 1 # 0 if the node is a left child, 1 if a right child 

2618 parent_blocks = blocks[side, parent] 

2619 # var_tree[parent] is a valid index wherever parent_blocks holds (the parent 

2620 # is then internal); elsewhere the clamped gather is masked away 

2621 parent_var = var_tree[parent] 

2622 ineligible_mass = jnp.where(parent_blocks, s.rest_ratio[parent_var], 0.0) 

2623 ineligible_top = jnp.where(parent_blocks, s.top_bit[parent_var], 0) 

2624 for level in range(1, max_depth): 

2625 lhs, rhs = 1 << level, 1 << (level + 1) 

2626 parent_mass = jnp.repeat(ineligible_mass[lhs >> 1 : rhs >> 1], 2) 

2627 ineligible_mass = ineligible_mass.at[lhs:rhs].add(parent_mass) 

2628 parent_top = jnp.repeat(ineligible_top[lhs >> 1 : rhs >> 1], 2) 

2629 ineligible_top = ineligible_top.at[lhs:rhs].add(parent_top) 

2630 

2631 # on cpu, materialize the accumulation and the eligible mass below, else xla 

2632 # fuses their computations into their many uses and repeats them 

2633 ineligible_mass, ineligible_top = cpu_barrier((ineligible_mass, ineligible_top)) 

2634 

2635 # Eligible mass per node, in log space: the largest split probabilities not 

2636 # ineligible, plus the others minus the ineligible ones. It is positive at 

2637 # internal nodes (the split variable is eligible), the clip only guards 

2638 # against round-off. The sum is shifted by the largest term; this is faster 

2639 # on cpu than a chain of logaddexp. 

2640 log_rest = s.log_rest + jnp.log1p(-jnp.minimum(ineligible_mass, 1.0)) 

2641 (num_top,) = s.log_top.shape 

2642 is_eligible = tuple(((ineligible_top >> i) & 1) == 0 for i in range(num_top)) 

2643 log_max = log_rest 

2644 for i in range(num_top): 

2645 log_max = jnp.where(is_eligible[i], jnp.maximum(log_max, s.log_top[i]), log_max) 

2646 log_max = jnp.where(jnp.isneginf(log_max), 0.0, log_max) 

2647 eligible = jnp.exp(log_rest - log_max) 

2648 for i in range(num_top): 

2649 eligible += jnp.where(is_eligible[i], jnp.exp(s.log_top[i] - log_max), 0.0) 

2650 log_eligible = cpu_barrier(log_max + jnp.log(eligible)) 

2651 

2652 # Per-node augmentation weight lambda_b / e_b, zero at non-internal nodes. The 

2653 # eligible mass can be tiny, so the weights and their sums below are in log 

2654 # space, as they can exceed the float32 range. 

2655 log_weight = jnp.log(random.exponential(key, (max_num_leaves,))) - log_eligible 

2656 log_weight = jnp.where(is_internal, log_weight, -jnp.inf) 

2657 

2658 # Subtree weight: total weight of each node's internal descendants and itself, 

2659 # accumulated bottom-up. The children of the deepest decision level are leaves 

2660 # and contribute nothing. 

2661 log_subtree_weight = log_weight 

2662 for level in range(max_depth - 2, -1, -1): 

2663 lhs, rhs = 1 << level, 1 << (level + 1) 

2664 children = log_subtree_weight[2 * lhs : 2 * rhs].reshape(-1, 2) 

2665 children = jnp.logaddexp(children[:, 0], children[:, 1]) 

2666 log_subtree_weight = log_subtree_weight.at[lhs:rhs].set( 

2667 jnp.logaddexp(log_subtree_weight[lhs:rhs], children) 

2668 ) 

2669 

2670 # A variable blocked by node b at one of its children is ineligible in that 

2671 # whole child subtree, so it accumulates the subtree weight. Only the upper 

2672 # half of nodes have internal children (the deepest decision nodes block 

2673 # into leaves, contributing nothing); their children are exactly 

2674 # subtree_weight reshaped into [left, right] pairs. 

2675 half = max_num_leaves // 2 

2676 children = jnp.where( 

2677 blocks[:, :half], log_subtree_weight.reshape(-1, 2).T, -jnp.inf 

2678 ) 

2679 log_mass = jnp.logaddexp(*children) 

2680 # int32 such that the out-of-bounds index p does not wrap around 

2681 var = jnp.where(is_internal[:half], var_tree[:half], jnp.int32(p)) 

2682 return var, log_mass 

2683 

2684 

2685def scatter_logaddexp( 

2686 size: int, indices: Integer[Array, ' n'], values: Float32[Array, ' n'] 

2687) -> Float32[Array, ' {size}']: 

2688 """Accumulate `values` at `indices` with `jnp.logaddexp`, ignoring indices out of bounds.""" 

2689 # jnp.logaddexp.at would also do this, but its implementation is much worse, 

2690 # it uses a lax.scan along the reduction axis 

2691 peak = jnp.full(size, -jnp.inf).at[indices].max(values, mode='drop') 

2692 peak_at = peak.at[indices].get(mode='fill', fill_value=-jnp.inf) 

2693 terms = jnp.where(jnp.isneginf(values), 0.0, jnp.exp(values - peak_at)) 

2694 total = jnp.zeros(size).at[indices].add(terms, mode='drop') 

2695 return jnp.where(jnp.isneginf(peak), -jnp.inf, peak + jnp.log(total)) 

2696 

2697 

2698def sample_s_augmentation(key: Key[Array, ''], forest: Forest) -> Float32[Array, ' p']: 

2699 """Sample the data-augmentation counts for the exact full conditional of `s`. 

2700 

2701 At each internal node, the variables with no available cutpoint given the 

2702 ancestors (plus the globally blocked ones) cannot be split on, so the plain 

2703 Dirichlet update for `s` is only approximate. This samples, for each 

2704 variable, the number of ineligible draws discarded before each realized 

2705 split, to be added to the variable usage counts. 

2706 

2707 Parameters 

2708 ---------- 

2709 key 

2710 Random key for sampling. 

2711 forest 

2712 The forest, providing the trees and the current `log_s`. 

2713 

2714 Returns 

2715 ------- 

2716 The log of the discarded-draws count for each variable. 

2717 """ 

2718 assert forest.sparsity.log_s is not None 

2719 keys = split(key) 

2720 (num_trees, max_num_leaves) = forest.var_tree.shape 

2721 

2722 # split probabilities normalized over the selectable (non-blocked) variables, 

2723 # with the largest ones singled out. A node has less than max_depth 

2724 # ineligible variables, one per ancestor. If some are not among the 

2725 # largest, their mass is subtracted from the total of the others, and at 

2726 # least max_depth + 1 of the 2 max_depth largest are eligible, each larger 

2727 # than all the others: so the relative error of the eligible mass is about 

2728 # float32 eps times p / (max_depth + 1). 

2729 max_depth = max_num_leaves.bit_length() - 1 

2730 s = S.from_log_s(forest.sparsity.log_s, forest.max_split > 0, 2 * max_depth) 

2731 

2732 # blocked_mass[j] = sum over internal nodes where j is ineligible of 

2733 # lambda_b / e_b, with lambda_b ~ Exponential(1); accumulated over the nodes 

2734 # of all the trees at once, as a total per tree would take p values 

2735 var, log_mass = vmap(log_blocked_mass_tree, in_axes=(0, 0, 0, None, None))( 

2736 keys.pop(num_trees), forest.var_tree, forest.split_tree, forest.max_split, s 

2737 ) 

2738 (p,) = forest.max_split.shape 

2739 log_blocked_mass = scatter_logaddexp(p, var.reshape(-1), log_mass.reshape(-1)) 

2740 

2741 # the per-node discarded-draw counts are negative-multinomial, with no 

2742 # closed form when summed over nodes, but their Gamma-Poisson mixture does: 

2743 # A_j | {lambda_b} ~ Poisson(s_j * blocked_mass[j]), independent across j. 

2744 # The counts can be huge, so they are in log space. Above 10^20, their 

2745 # relative fluctuations are below float32 resolution, so the count is its 

2746 # mean. 

2747 log_rate = s.log_s + log_blocked_mass 

2748 huge = log_rate > LOG_HUGE 

2749 rate = jnp.exp(jnp.where(huge, 0.0, log_rate)) 

2750 count = poisson(keys.pop(), rate, dtype=jnp.float32) 

2751 return jnp.where(huge, log_rate, jnp.log(count)) 

2752 

2753 

2754@named_call 

2755def step_s(key: Key[Array, ''], state: State) -> State: 

2756 """ 

2757 Update `log_s` using Dirichlet sampling. 

2758 

2759 The prior is s ~ Dirichlet(theta/p, ..., theta/p), and the posterior 

2760 is s ~ Dirichlet(theta/p + varcount, ..., theta/p + varcount), where 

2761 varcount is the count of how many times each variable is used in the 

2762 current forest. The variables with ``max_split == 0`` are excluded, also 

2763 from the count `p`, and get arbitrary values. 

2764 

2765 Parameters 

2766 ---------- 

2767 key 

2768 Random key for sampling. 

2769 state 

2770 The current BART state. 

2771 

2772 Returns 

2773 ------- 

2774 Updated BART state with re-sampled `log_s`. 

2775 

2776 Notes 

2777 ----- 

2778 By default this full conditional is approximate, because it ignores the 

2779 decision rules forbidden by the ancestors of each node. If 

2780 ``state.config.augment`` is set, the forbidden rules are accounted for 

2781 exactly with the data augmentation of `sample_s_augmentation`. 

2782 """ 

2783 assert state.forest.sparsity.theta is not None 

2784 

2785 # reserve the Dirichlet draw key first and unconditionally, so it does not 

2786 # depend on whether augmentation is on; then the two modes draw identically 

2787 # when there are no forbidden rules, since the augmentation is exactly zero 

2788 keys = split(key) 

2789 log_s_key = keys.pop() 

2790 

2791 # histogram current variable usage 

2792 (p,) = state.forest.max_split.shape 

2793 varcount = var_histogram( 

2794 p, state.forest.var_tree, state.forest.split_tree, sum_batch_axis=-1 

2795 ) 

2796 

2797 # the Dirichlet posterior concentration, optionally completed with the exact 

2798 # accounting of forbidden rules via data augmentation, in log space as the 

2799 # augmentation counts can be huge 

2800 p_eff = count_selectable(state.forest.max_split > 0) 

2801 log_alpha = jnp.log(state.forest.sparsity.theta / p_eff + varcount) 

2802 if state.config.augment: 

2803 log_alpha = jnp.logaddexp( 

2804 log_alpha, sample_s_augmentation(keys.pop(), state.forest) 

2805 ) 

2806 

2807 # sample from the Dirichlet posterior and update the forest with the new s; 

2808 # above 10^20, the relative fluctuations of Gamma(alpha) are below float32 

2809 # resolution, so log Gamma(alpha) is log(alpha) 

2810 huge = log_alpha > LOG_HUGE 

2811 alpha = jnp.exp(jnp.where(huge, 0.0, log_alpha)) 

2812 log_s = jnp.where(huge, log_alpha, loggamma(log_s_key, alpha)) 

2813 return replace( 

2814 state, 

2815 forest=replace( 

2816 state.forest, sparsity=replace(state.forest.sparsity, log_s=log_s) 

2817 ), 

2818 ) 

2819 

2820 

2821@named_call 

2822def step_theta( 

2823 key: Key[Array, ''], state: State, *, num_grid: int | None = None 

2824) -> State: 

2825 """ 

2826 Update `theta`. 

2827 

2828 The prior is theta / (theta + rho) ~ Beta(a, b). 

2829 

2830 Parameters 

2831 ---------- 

2832 key 

2833 Random key for sampling. 

2834 state 

2835 The current BART state. 

2836 num_grid 

2837 The number of bins of the grid used to sample ``log(theta / rho)``. If 

2838 not specified, it grows with the number of predictors, see Notes. 

2839 

2840 Returns 

2841 ------- 

2842 Updated BART state with re-sampled `theta`. 

2843 

2844 Notes 

2845 ----- 

2846 The draw is from an approximation of the full conditional of ``v = 

2847 log(theta / rho)``, which interpolates its logarithm linearly between the 

2848 edges of the bins of an evenly spaced grid over the range of `v` allowed by 

2849 `Sparsity.log_theta_range`. The full conditional of `v` gets 

2850 narrower with the number of predictors `p`, roughly with standard deviation 

2851 ``1 / sqrt(p)``, so by default the number of bins is ``320 sqrt(p)``, clipped 

2852 to [1000, 10000]. Beyond that, the approximation is accurate only to 

2853 within a bin. 

2854 """ 

2855 forest = state.forest 

2856 assert forest.sparsity.log_s is not None 

2857 assert forest.sparsity.rho is not None 

2858 assert forest.sparsity.a is not None 

2859 assert forest.sparsity.b is not None 

2860 assert forest.sparsity.log_theta_range is not None 

2861 

2862 if num_grid is None: 2862 ↛ 2866line 2862 didn't jump to line 2866 because the condition on line 2862 was always true

2863 (p,) = forest.max_split.shape 

2864 num_grid = min(max(round(320 * p**0.5), 1000), 10_000) 

2865 

2866 keys = split(key) 

2867 

2868 # log_p(v) is the exact full conditional log pdf of v 

2869 log_p = partial( 

2870 _log_p_v, 

2871 log_s=forest.sparsity.log_s, 

2872 selectable=forest.max_split > 0, 

2873 a=forest.sparsity.a, 

2874 b=forest.sparsity.b, 

2875 rho=forest.sparsity.rho, 

2876 ) 

2877 

2878 # the mass of each bin, under the log-linear interpolation of the density 

2879 grid_range = forest.sparsity.log_theta_range 

2880 width = 2 * grid_range / num_grid 

2881 edges = jnp.linspace(-grid_range, grid_range, num_grid + 1) 

2882 # on cpu, materialize the log density, else xla fuses its computation into 

2883 # its two uses per bin below and repeats it 

2884 log_p_edges = cpu_barrier(log_p(edges)) 

2885 rise = jnp.diff(log_p_edges) # change of the log density across each bin 

2886 log_pmf = log_p_edges[:-1] + jnp.log(width) + log_expm1_ratio(rise) 

2887 

2888 # where the log density overflows to -inf, the interpolated density is 0 

2889 # across the bin, while the arithmetic above would give nan 

2890 void = jnp.isneginf(log_p_edges[:-1]) | jnp.isneginf(log_p_edges[1:]) 

2891 rise = jnp.where(void, 0.0, rise) 

2892 log_pmf = jnp.where(void, -jnp.inf, log_pmf) 

2893 

2894 # on cpu, materialize log_pmf, else xla fuses its computation into each of 

2895 # the two reductions in `categorical` and repeats it 

2896 log_pmf = cpu_barrier(log_pmf) 

2897 

2898 # draw a bin, then a point within it 

2899 i = categorical(keys.pop(), log_pmf) 

2900 v = edges[i] + width * sample_unit_exponential(keys.pop(), rise[i]) 

2901 

2902 theta = forest.sparsity.rho * jnp.exp(v) 

2903 return replace( 

2904 state, forest=replace(forest, sparsity=replace(forest.sparsity, theta=theta)) 

2905 ) 

2906 

2907 

2908def log_expm1_ratio(x: Float32[Array, '*shape']) -> Float32[Array, '*shape']: 

2909 """Compute ``log((exp(x) - 1) / x)``, the log mass of ``exp(x t) dt`` on ``[0, 1]``.""" 

2910 # (e^x - 1) / x = e^x (1 - e^-x) / x, use the form with a negative exponent 

2911 abs_x = jnp.abs(x) 

2912 small = abs_x < 1e-4 

2913 safe_abs_x = jnp.where(small, 1.0, abs_x) 

2914 log_ratio_neg = jnp.where( 

2915 small, -abs_x / 2, jnp.log(-jnp.expm1(-safe_abs_x)) - jnp.log(safe_abs_x) 

2916 ) 

2917 return jnp.maximum(x, 0.0) + log_ratio_neg 

2918 

2919 

2920def sample_unit_exponential( 

2921 key: Key[Array, ''], x: Float32[Array, ''] 

2922) -> Float32[Array, '']: 

2923 """Sample `t` in ``[0, 1]`` with density proportional to ``exp(x t)``.""" 

2924 u = random.uniform(key) 

2925 small = jnp.abs(x) < 1e-4 

2926 x = jnp.where(small, 1.0, x) # avoid non-finite intermediates in the `small` case 

2927 # invert the cdf (e^(x t) - 1) / (e^x - 1), written such that the 

2928 # exponential can not overflow 

2929 t_negative = jnp.log1p(u * jnp.expm1(jnp.minimum(x, 0.0))) / x 

2930 t_positive = 1 + jnp.log(u + (1 - u) * jnp.exp(-jnp.maximum(x, 0.0))) / x 

2931 t = jnp.where(x > 0, t_positive, t_negative) 

2932 return jnp.where(small, u, jnp.clip(t, 0.0, 1.0)) 

2933 

2934 

2935def _log_p_v( 

2936 v: Float32[Array, '*shape'], 

2937 *, 

2938 log_s: Float32[Array, ' p'], 

2939 selectable: Bool[Array, ' p'], 

2940 a: Float32[Array, ''], 

2941 b: Float32[Array, ''], 

2942 rho: Float32[Array, ''], 

2943) -> Float32[Array, '*shape']: 

2944 """Compute the unnormalized full conditional of ``v = log(theta / rho)``. 

2945 

2946 With ``lambda = theta / (theta + rho)``, the Beta(a, b) prior density of 

2947 `lambda`, times the Jacobian ``dlambda / dv = lambda (1 - lambda)``, gives 

2948 the prior density of `v`, proportional to ``lambda^a (1 - lambda)^b``. The 

2949 likelihood is the Dirichlet density of ``s = softmax(log_s)`` over the 

2950 `p_eff` `selectable` variables, with concentration ``theta / p_eff``. 

2951 """ 

2952 log_lambda = -jnp.logaddexp(0.0, -v) 

2953 log1m_lambda = -jnp.logaddexp(0.0, v) 

2954 p_eff = count_selectable(selectable) 

2955 log_c = jnp.log(rho / p_eff) + v # c = theta / p_eff 

2956 c = jnp.exp(log_c) 

2957 theta = p_eff * c 

2958 

2959 # log of the Dirichlet density, Gamma(theta) / Gamma(c)^p prod(s)^c, up to 

2960 # factors constant in theta. Expanding the log-gammas with Stirling's 

2961 # formula, the terms of order theta log theta cancel exactly, leaving minus 

2962 # theta times the divergence -log p - mean(log s) >= 0 of s from uniform, 

2963 # computed from the unnormalized log_s. This avoids cancellations in float32. 

2964 r_theta, r_c = stirling_remainder(jnp.stack([theta, c])) 

2965 deviation = log_mean_exp_deviation(log_s, selectable) 

2966 log_lk = (p_eff - 1) / 2 * log_c - theta * deviation + r_theta - p_eff * r_c 

2967 

2968 return a * log_lambda + b * log1m_lambda + log_lk 

2969 

2970 

2971def count_selectable(selectable: Bool[Array, ' p']) -> Int32[Array, '']: 

2972 """Count the true entries, but at least 1 to be safe as divisor.""" 

2973 return jnp.maximum(jnp.count_nonzero(selectable), 1) 

2974 

2975 

2976def log_mean_exp_deviation( 

2977 x: Float32[Array, ' p'], where: Bool[Array, ' p'] 

2978) -> Float32[Array, '']: 

2979 """Compute ``log(mean(exp(x - mean(x))))`` over `where` without cancellation, 0 if empty.""" 

2980 num = count_selectable(where) 

2981 

2982 def mean(y: Float32[Array, ' p']) -> Float32[Array, '']: 

2983 # not jnp.mean, which gives nan if `where` is all false 

2984 return jnp.sum(y, where=where) / num 

2985 

2986 x -= mean(x) 

2987 # shift only if exp(x) could overflow, else expm1 retains the precision 

2988 shift = jnp.maximum(jnp.max(x, where=where, initial=-jnp.inf) - 30.0, 0.0) 

2989 # the result is invariant to shifting x, so remove the residual mean that 

2990 # the centering leaves due to rounding 

2991 return shift + jnp.log1p(mean(jnp.expm1(x - shift))) - mean(x) 

2992 

2993 

2994def stirling_remainder(z: Float32[Array, '*shape']) -> Float32[Array, '*shape']: 

2995 """Compute ``log Gamma(z) - (z - 1/2) log z + z - log(2 pi) / 2``, for ``z > 0``.""" 

2996 # use the recurrence r(z) = r(z + 1) + (z + 1/2) log(1 + 1/z) - 1 to bring 

2997 # the argument where the asymptotic series is accurate 

2998 shift = 4 

2999 steps = stirling_step(z) 

3000 for k in range(1, shift): 

3001 steps += stirling_step_series(z + k) 

3002 return jnp.where( 

3003 z >= shift, 

3004 stirling_series(jnp.maximum(z, shift)), 

3005 stirling_series(z + shift) + steps, 

3006 ) 

3007 

3008 

3009def stirling_series(z: Float32[Array, '*shape']) -> Float32[Array, '*shape']: 

3010 """Asymptotic series of `stirling_remainder`, accurate in float32 for ``z >= 4``.""" 

3011 inv = jnp.reciprocal(z) 

3012 inv2 = jnp.square(inv) 

3013 coefs = (1 / 12, -1 / 360, 1 / 1260, -1 / 1680, 1 / 1188, -691 / 360360, 1 / 156) 

3014 series = 0.0 

3015 for coef in reversed(coefs): 

3016 series = coef + inv2 * series 

3017 return inv * series 

3018 

3019 

3020def stirling_step(w: Float32[Array, '*shape']) -> Float32[Array, '*shape']: 

3021 """Compute ``(w + 1/2) log(1 + 1/w) - 1``, for ``w > 0``.""" 

3022 # below w = 1/2 the cancellation in the direct formula is mild 

3023 direct = (w + 0.5) * jnp.log1p(jnp.reciprocal(w)) - 1 

3024 series = stirling_step_series(jnp.maximum(w, 0.5), num_terms=14) 

3025 return jnp.where(w >= 0.5, series, direct) 

3026 

3027 

3028def stirling_step_series( 

3029 w: Float32[Array, '*shape'], num_terms: int = 8 

3030) -> Float32[Array, '*shape']: 

3031 """Compute ``(w + 1/2) log(1 + 1/w) - 1`` without cancellation. 

3032 

3033 The default `num_terms` is accurate for ``w >= 1``, 14 for ``w >= 1/2``. 

3034 """ 

3035 # with x = 1 / (2 w + 1), it's atanh(x) / x - 1 = sum_k x^2k / (2k + 1) 

3036 x2 = jnp.square(jnp.reciprocal(2 * w + 1)) 

3037 series = x2 / (2 * num_terms + 1) 

3038 for k in range(num_terms - 1, 0, -1): 

3039 series = x2 * (1 / (2 * k + 1) + series) 

3040 return series 

3041 

3042 

3043@named_call 

3044def step_sparse(key: Key[Array, ''], state: State) -> State: 

3045 """ 

3046 Update the sparsity parameters. 

3047 

3048 This invokes `step_s`, and then `step_theta` only if the parameters of 

3049 the theta prior are defined. 

3050 

3051 Parameters 

3052 ---------- 

3053 key 

3054 Random key for sampling. 

3055 state 

3056 The current BART state. 

3057 

3058 Returns 

3059 ------- 

3060 Updated BART state with re-sampled `log_s` and `theta`. 

3061 """ 

3062 if state.config.sparse_on_at is not None: 

3063 state = lax.cond( 

3064 state.config.steps_done < state.config.sparse_on_at, 

3065 lambda _key, state: state, 

3066 _step_sparse, 

3067 key, 

3068 state, 

3069 ) 

3070 return state 

3071 

3072 

3073def _step_sparse(key: Key[Array, ''], state: State) -> State: 

3074 keys = split(key) 

3075 state = step_s(keys.pop(), state) 

3076 if state.forest.sparsity.rho is not None: 

3077 state = step_theta(keys.pop(), state) 

3078 return state 

3079 

3080 

3081@named_call 

3082def step_config(state: State) -> State: 

3083 config = state.config 

3084 config = replace(config, steps_done=config.steps_done + 1) 

3085 return replace(state, config=config)