Coverage for src/bartz/mcmcloop/_callback.py: 92%

294 statements  

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

1# bartz/src/bartz/mcmcloop/_callback.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"""Progress-reporting callbacks for `run_mcmc`.""" 

26 

27import math 

28from collections.abc import Callable 

29from dataclasses import dataclass, replace 

30from functools import partial, wraps 

31from secrets import randbits 

32from threading import get_ident 

33from typing import Any, Literal, TypeVar 

34from warnings import warn 

35 

36import numpy 

37from equinox import Module, field 

38from jax import debug, eval_shape, lax, random, tree 

39from jax import numpy as jnp 

40from jax.nn import log_softmax, logmeanexp 

41from jaxtyping import Array, Bool, Float32, Int32, Integer, PyTree 

42from tqdm.auto import tqdm 

43 

44from bartz._jaxext import forbid_x64, get_cpu_thread_count 

45from bartz._typing import kwdict 

46from bartz.grove import forest_mean_leaves 

47from bartz.mcmcloop._loop import Callback, _replicate 

48from bartz.mcmcstep import State 

49from bartz.mcmcstep._state import used_trees_mask 

50from bartz.npz import serializable 

51 

52 

53@serializable 

54class CallbackTuple(Callback): 

55 """Callback that runs a sequence of callbacks in order. 

56 

57 Each callback receives the state as (possibly) updated by the preceding 

58 ones, so their effects compose left to right. 

59 """ 

60 

61 callbacks: tuple[Callback, ...] 

62 """The callbacks to run, in order.""" 

63 

64 def __call__(self, *, state: State, **kwargs: Any) -> tuple[State, 'CallbackTuple']: 

65 """Invoke each callback in turn, threading the state through them.""" 

66 new_callbacks = [] 

67 for i, callback in enumerate(self.callbacks): 

68 # decorrelate the keys by position, so a callback keeps its key if 

69 # other callbacks are appended after it 

70 kw = dict(kwargs, key=random.fold_in(kwargs['key'], i)) 

71 rt = callback(state=state, **kw) 

72 if rt is None: 

73 new_callbacks.append(callback) 

74 else: 

75 state, new_callback = rt 

76 new_callbacks.append(new_callback) 

77 return state, replace(self, callbacks=tuple(new_callbacks)) 

78 

79 

80class StatsReport(Module): 

81 """Forest diagnostics produced by `StatsAccumulator.report` for one report.""" 

82 

83 move_acc: Float32[Array, ''] 

84 """Fraction of the trees in use on which a grow or prune move was accepted.""" 

85 

86 mean_leaves: Float32[Array, ''] 

87 """Mean number of leaves per tree in use.""" 

88 

89 mean_tree_life: Float32[Array, ''] 

90 """Mean of `bartz.mcmcstep.Forest.tree_life` over the trees in use and the 

91 chains.""" 

92 

93 steps_done: Int32[Array, ''] 

94 """Number of MCMC steps done, the maximum possible tree life.""" 

95 

96 var_perplexity: Float32[Array, ''] | None 

97 """Perplexity of the split-variable distribution, an effective number of 

98 predictors, or `None` when variable selection is off.""" 

99 

100 p_eff: Int32[Array, ''] | None 

101 """Number of predictors with decision rules, or `None` when variable selection is off.""" 

102 

103 n_samples: Int32[Array, ''] | None 

104 """Number of iterations averaged over, or `None` when not averaging.""" 

105 

106 num_chains: int | None = field(static=True) 

107 """Number of chains averaged over, or `None` when single-chain.""" 

108 

109 max_leaves: int = field(static=True) 

110 """Maximum possible number of leaves per tree.""" 

111 

112 

113@serializable 

114class StatsAccumulator(Module): 

115 """Running average of the forest diagnostics shown during the MCMC. 

116 

117 When enabled, it sums the per-iteration statistics so a report shows their 

118 average over the iterations since the previous report. When disabled it 

119 carries no running state and a report shows the latest iteration only. 

120 """ 

121 

122 sums: dict[str, Float32[Array, '']] | None 

123 """Running sums of the averaged statistics, or `None` when disabled.""" 

124 

125 count: Int32[Array, ''] 

126 """Number of iterations accumulated since the last reset.""" 

127 

128 @classmethod 

129 def initial(cls, state: State, *, enabled: bool) -> 'StatsAccumulator': 

130 """Create a zeroed accumulator, inert unless `enabled`.""" 

131 if enabled: 

132 # only the structure is needed, so avoid computing the statistics 

133 shapes = eval_shape(cls._avg_stats, state) 

134 sums = tree.map(lambda s: jnp.zeros(s.shape, s.dtype), shapes) 

135 else: 

136 sums = None 

137 return cls(sums=sums, count=jnp.int32(0)) 

138 

139 def update(self, state: State) -> 'StatsAccumulator': 

140 """Add the latest iteration's statistics; no-op when disabled.""" 

141 if self.sums is None: 

142 return self 

143 else: 

144 sums = tree.map(jnp.add, self.sums, self._avg_stats(state)) 

145 return replace(self, sums=sums, count=self.count + 1) 

146 

147 def reset_if(self, cond: bool | Bool[Array, '']) -> 'StatsAccumulator': 

148 """Zero the running sums where `cond` holds; no-op when disabled.""" 

149 if self.sums is None: 

150 return self 

151 else: 

152 sums = tree.map(lambda s: jnp.where(cond, 0, s), self.sums) 

153 return replace(self, sums=sums, count=jnp.where(cond, 0, self.count)) 

154 

155 def report(self, state: State) -> StatsReport: 

156 """Statistics to display: the windowed average if enabled, else the latest.""" 

157 if self.sums is None: 

158 averaged: kwdict = self._avg_stats(state) 

159 n_samples = None 

160 else: 

161 averaged = tree.map(lambda s: s / self.count, self.sums) 

162 n_samples = self.count 

163 forest = state.forest 

164 return StatsReport( 

165 **averaged, 

166 **self._constant_stats(state), 

167 mean_tree_life=jnp.mean(forest.tree_life, where=used_trees_mask(forest)), 

168 steps_done=state.config.steps_done, 

169 n_samples=n_samples, 

170 ) 

171 

172 @staticmethod 

173 def _avg_stats(state: State) -> dict[str, Float32[Array, ''] | None]: 

174 """Per-iteration diagnostics that are averaged over the report window.""" 

175 forest = state.forest 

176 used = used_trees_mask(forest) 

177 num_acc = forest.grow_acc_count.sum() + forest.prune_acc_count.sum() 

178 if used is None: 

179 num_used = forest.split_tree[..., 0].size 

180 else: 

181 num_used = jnp.count_nonzero(used) 

182 

183 log_s = forest.sparsity.log_s 

184 if log_s is None: 

185 var_perplexity = None 

186 else: 

187 var_perplexity = StatsAccumulator._var_perplexity( 

188 log_s, forest.max_split > 0 

189 ) 

190 

191 return dict( 

192 move_acc=num_acc / num_used, 

193 mean_leaves=forest_mean_leaves(forest.split_tree, where=used), 

194 var_perplexity=var_perplexity, 

195 ) 

196 

197 @staticmethod 

198 def _constant_stats(state: State) -> dict[str, int | Int32[Array, ''] | None]: 

199 """Per-iteration diagnostics shown as-is, constant over the run.""" 

200 forest = state.forest 

201 if forest.sparsity.log_s is None: 

202 p_eff = None 

203 else: 

204 p_eff = jnp.count_nonzero(forest.max_split) 

205 return dict( 

206 num_chains=state.num_chains(), 

207 max_leaves=forest.split_tree.shape[-1], 

208 p_eff=p_eff, 

209 ) 

210 

211 @staticmethod 

212 def _var_perplexity( 

213 log_s: Float32[Array, '*chains p'], selectable: Bool[Array, ' p'] 

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

215 """Effective number of predictors used for splitting across all chains. 

216 

217 Perplexity (exponential of the Shannon entropy) of the split-variable 

218 distribution ``s = softmax(log_s)`` over the `selectable` predictors, 

219 pooled (averaged) over chains. It is 1 when all chains concentrate on a 

220 single shared predictor and the number of `selectable` predictors when 

221 the pooled distribution is uniform; in general a pooled distribution 

222 spread evenly over ``k`` predictors gives ``k``, and 0 if there are no 

223 `selectable` predictors. Chains are pooled before taking the entropy 

224 because predictions average over all chains, so a predictor used by any 

225 chain counts as used. 

226 """ 

227 *_, p = log_s.shape 

228 # normalize each chain 

229 log_prob = log_softmax(log_s, where=selectable) 

230 per_chain = log_prob.reshape(-1, p) 

231 # mix over chains 

232 log_pool = logmeanexp(per_chain, axis=0) 

233 prob = jnp.exp(log_pool) 

234 # the where avoids the 0 * -inf = nan term where a probability is 0, the 

235 # same guard `jax.scipy.special.entr` uses, but reusing the log we have 

236 entropy = -jnp.sum(prob * jnp.where(prob, log_pool, 1.0)) 

237 return jnp.where(jnp.any(selectable), jnp.exp(entropy), 0.0) 

238 

239 

240@serializable 

241class PrintCallback(Callback): 

242 """Progress-printing callback for `run_mcmc`, create it with `from_state`. 

243 

244 The callback prints a dot on every iteration, and a longer report 

245 periodically. 

246 """ 

247 

248 dot_every: Int32[Array, ''] | None 

249 """A dot is printed every `dot_every` MCMC iterations, `None` to disable.""" 

250 

251 report_every: Int32[Array, ''] | None 

252 """A one line report is printed every `report_every` MCMC iterations, 

253 `None` to disable.""" 

254 

255 accumulator: StatsAccumulator 

256 """Running average of the reported statistics, inert unless averaging.""" 

257 

258 @classmethod 

259 @forbid_x64 

260 def from_state( 

261 cls, 

262 state: State, 

263 *, 

264 dot_every: int | Integer[Array, ''] | None = 1, 

265 report_every: int | Integer[Array, ''] | None = 100, 

266 average: bool = True, 

267 ) -> 'PrintCallback': 

268 """ 

269 Prepare a progress-printing callback for `run_mcmc`. 

270 

271 Parameters 

272 ---------- 

273 state 

274 The MCMC state to use the callback with, used to determine device 

275 sharding. 

276 dot_every 

277 A dot is printed every `dot_every` MCMC iterations, `None` to disable. 

278 report_every 

279 A one line report is printed every `report_every` MCMC iterations, 

280 `None` to disable. 

281 average 

282 If `True`, the reported statistics are averaged over the iterations 

283 since the previous report; if `False`, they reflect the current 

284 iteration only. Ignored when `report_every` is `None`. 

285 

286 Returns 

287 ------- 

288 A callback to pass as the `callback` argument of `run_mcmc`. 

289 

290 Examples 

291 -------- 

292 >>> run_mcmc(key, state, ..., callback=PrintCallback.from_state(state, ...)) 

293 """ 

294 callback = cls( 

295 dot_every=None if dot_every is None else jnp.int32(dot_every), 

296 report_every=None if report_every is None else jnp.int32(report_every), 

297 accumulator=StatsAccumulator.initial( 

298 state, enabled=average and report_every is not None 

299 ), 

300 ) 

301 return tree.map(partial(_replicate, mesh=state.config.mesh), callback) 

302 

303 def __call__( 

304 self, 

305 *, 

306 state: State, 

307 burnin: Bool[Array, ''], 

308 i_total: Int32[Array, ''], 

309 n_burn: Int32[Array, ''], 

310 n_save: Int32[Array, ''], 

311 n_skip: Int32[Array, ''], 

312 **_: Any, 

313 ) -> tuple[State, 'PrintCallback']: 

314 """Print a dot and/or a report periodically during the MCMC.""" 

315 report_every = self.report_every 

316 dot_every = self.dot_every 

317 it = i_total + 1 

318 

319 accumulator = self.accumulator.update(state) 

320 

321 def get_cond(every: Int32[Array, ''] | None) -> bool | Bool[Array, '']: 

322 return False if every is None else it % every == 0 

323 

324 report_cond = get_cond(report_every) 

325 dot_cond = get_cond(dot_every) 

326 

327 def line_report_branch() -> None: 

328 if report_every is None: 328 ↛ 329line 328 didn't jump to line 329 because the condition on line 328 was never true

329 return 

330 if dot_every is None: 330 ↛ 331line 330 didn't jump to line 331 because the condition on line 330 was never true

331 print_newline = False 

332 else: 

333 print_newline = it % report_every > it % dot_every 

334 debug.callback( 

335 _print_report, 

336 accumulator.report(state), 

337 print_dot=dot_cond, 

338 print_newline=print_newline, 

339 burnin=burnin, 

340 it=it, 

341 n_iters=n_burn + n_save * n_skip, 

342 ) 

343 

344 def just_dot_branch() -> None: 

345 if dot_every is None: 345 ↛ 346line 345 didn't jump to line 346 because the condition on line 345 was never true

346 return 

347 # terminate the dot line on the final iteration so subsequent output 

348 # doesn't continue on the same line as the dots 

349 last_iter = it == n_burn + n_save * n_skip 

350 lax.cond( 

351 last_iter, 

352 lambda: debug.callback(lambda: print('.', flush=True)), # noqa: T201 

353 lambda: debug.callback(lambda: print('.', end='', flush=True)), # noqa: T201 

354 ) 

355 # logging can't do in-line printing so we use print 

356 

357 lax.switch( 

358 2 * report_cond + dot_cond, # switch clamps 3 to 2 

359 (lambda: None, just_dot_branch, line_report_branch), 

360 ) 

361 

362 accumulator = accumulator.reset_if(report_cond) 

363 return state, replace(self, accumulator=accumulator) 

364 

365 

366@serializable 

367class TqdmCallback(Callback): 

368 """`tqdm` progress-bar callback for `run_mcmc`, create it with `from_state`. 

369 

370 The callback shows a progress bar that advances with the MCMC iterations, 

371 optionally annotated with the proposal acceptance statistics. 

372 """ 

373 

374 bar_id: Int32[Array, ''] 

375 """Handle identifying the bar in the module-level `tqdm` bar registry.""" 

376 

377 update_every: Int32[Array, ''] 

378 """The bar position is refreshed every `update_every` MCMC iterations.""" 

379 

380 report_every: Int32[Array, ''] | None 

381 """The acceptance statistics are refreshed every `report_every` MCMC 

382 iterations, `None` to omit them.""" 

383 

384 accumulator: StatsAccumulator 

385 """Running average of the reported statistics, inert unless averaging.""" 

386 

387 @classmethod 

388 @forbid_x64 

389 def from_state( 

390 cls, 

391 state: State, 

392 *, 

393 update_every: int = 1, 

394 report_every: int | None = 100, 

395 average: bool = True, 

396 **tqdm_kwargs: Any, 

397 ) -> 'TqdmCallback': 

398 """ 

399 Prepare a `tqdm` progress-bar callback for `run_mcmc`. 

400 

401 Parameters 

402 ---------- 

403 state 

404 The MCMC state to use the callback with, used to determine device 

405 sharding. 

406 update_every 

407 The bar position is refreshed every `update_every` MCMC iterations, 

408 and at the first one (`tqdm` further throttles the actual redraw rate 

409 on its own). 

410 report_every 

411 The acceptance statistics shown next to the bar are refreshed every 

412 `report_every` MCMC iterations, `None` to omit them. 

413 average 

414 If `True`, the statistics shown are averaged over the iterations since 

415 the previous refresh; if `False`, they reflect the current iteration 

416 only. Ignored when `report_every` is `None`. 

417 **tqdm_kwargs 

418 Additional keyword arguments forwarded to the `tqdm.tqdm` constructor, 

419 e.g., ``desc``, ``file``, or ``disable``. 

420 

421 Returns 

422 ------- 

423 A callback to pass as the `callback` argument of `run_mcmc`. 

424 

425 Notes 

426 ----- 

427 Works with chains sharded across multiple devices, and with concurrent 

428 runs in separate threads. If the run is interrupted (e.g. with ^C), the 

429 bar is left as-is; the next `from_state` call in the same thread closes 

430 it, so a subsequent run starts from a clean line. 

431 

432 The callback drives a single bar for a single `run_mcmc` call: it is 

433 not reusable nor resumable, and in a further `run_mcmc` call it shows 

434 no bar. Create a new one for each call. 

435 

436 Examples 

437 -------- 

438 >>> run_mcmc(key, state, ..., callback=TqdmCallback.from_state(state, ...)) 

439 """ 

440 _close_stale_bars() # clean up after any previous run that was interrupted 

441 # random, to avoid clashes with the ids of callbacks saved in other 

442 # processes 

443 bar_id = randbits(31) 

444 _TQDM_REGISTRY[bar_id] = _TqdmEntry(tqdm_kwargs, get_ident()) 

445 

446 callback = cls( 

447 bar_id=jnp.int32(bar_id), 

448 update_every=jnp.int32(update_every), 

449 report_every=None if report_every is None else jnp.int32(report_every), 

450 accumulator=StatsAccumulator.initial( 

451 state, enabled=average and report_every is not None 

452 ), 

453 ) 

454 return tree.map(partial(_replicate, mesh=state.config.mesh), callback) 

455 

456 def __call__( 

457 self, 

458 *, 

459 state: State, 

460 i_total: Int32[Array, ''], 

461 n_burn: Int32[Array, ''], 

462 n_save: Int32[Array, ''], 

463 n_skip: Int32[Array, ''], 

464 **_: Any, 

465 ) -> tuple[State, 'TqdmCallback']: 

466 """Advance a `tqdm` progress bar during the MCMC.""" 

467 it = i_total + 1 

468 n_iters = n_burn + n_save * n_skip 

469 bar_id = self.bar_id 

470 last = it == n_iters 

471 

472 accumulator = self.accumulator.update(state) 

473 

474 # The callbacks are unordered: `ordered=True` is unsupported with more 

475 # than one device, and we need this to work with chains sharded across 

476 # devices. `_tqdm_update` is therefore robust to out-of-order 

477 # invocations, and does both the report and the advance in a single 

478 # callback, so the last report can't arrive after the bar is closed. 

479 report_every = self.report_every 

480 if report_every is None: 480 ↛ 481line 480 didn't jump to line 481 because the condition on line 480 was never true

481 report_cond = False 

482 else: 

483 report_cond = (it % report_every == 0) | last 

484 advance_cond = (it == 1) | (it % self.update_every == 0) | last 

485 

486 def advance_branch() -> None: 

487 debug.callback(_tqdm_update, bar_id, it, n_iters, None) 

488 

489 def report_branch() -> None: 

490 report = accumulator.report(state) 

491 debug.callback(_tqdm_update, bar_id, it, n_iters, report) 

492 

493 lax.switch( 

494 2 * report_cond + advance_cond, # switch clamps 3 to 2 

495 (lambda: None, advance_branch, report_branch), 

496 ) 

497 accumulator = accumulator.reset_if(report_cond) 

498 

499 return state, replace(self, accumulator=accumulator) 

500 

501 

502T = TypeVar('T') 

503 

504 

505def _convert_jax_arrays_in_args(func: Callable[..., T]) -> Callable[..., T]: 

506 """Remove jax arrays from a function arguments. 

507 

508 Converts all `jax.Array` instances in the arguments to either Python scalars 

509 or numpy arrays. 

510 """ 

511 

512 def convert_jax_arrays(pytree: PyTree) -> PyTree: 

513 def convert_jax_array(val: object) -> object: 

514 if not isinstance(val, Array): 514 ↛ 515line 514 didn't jump to line 515 because the condition on line 514 was never true

515 return val 

516 elif val.shape: 516 ↛ 517line 516 didn't jump to line 517 because the condition on line 516 was never true

517 return numpy.array(val) 

518 else: 

519 return val.item() 

520 

521 return tree.map(convert_jax_array, pytree) 

522 

523 @wraps(func) 

524 def new_func(*args: Any, **kw: Any) -> T: 

525 args = convert_jax_arrays(args) 

526 kw = convert_jax_arrays(kw) 

527 return func(*args, **kw) 

528 

529 return new_func 

530 

531 

532@_convert_jax_arrays_in_args 

533# convert all jax arrays in arguments because operations on them could lead to 

534# deadlock with the main thread 

535def _print_report( 

536 report: StatsReport, 

537 *, 

538 print_dot: bool, 

539 print_newline: bool, 

540 burnin: bool, 

541 it: int, 

542 n_iters: int, 

543) -> None: 

544 """Print the report for `PrintCallback`.""" 

545 # determine prefix 

546 if print_dot: 546 ↛ 548line 546 didn't jump to line 548 because the condition on line 546 was always true

547 prefix = '.\n' 

548 elif print_newline: 

549 prefix = '\n' 

550 else: 

551 prefix = '' 

552 

553 # determine suffix in parentheses: what the statistics are averaged over 

554 avg_over = [] 

555 if report.num_chains is not None: 

556 avg_over.append(f'{report.num_chains} chains') 

557 if report.n_samples is not None: 557 ↛ 559line 557 didn't jump to line 559 because the condition on line 557 was always true

558 avg_over.append(f'{report.n_samples} samples') 

559 msgs = [] 

560 if avg_over: 560 ↛ 562line 560 didn't jump to line 562 because the condition on line 560 was always true

561 msgs.append('avg. ' + ' x '.join(avg_over)) 

562 if burnin: 562 ↛ 563line 562 didn't jump to line 563 because the condition on line 562 was never true

563 msgs.append('burnin') 

564 suffix = f' ({", ".join(msgs)})' if msgs else '' 

565 

566 # variable-selection concentration, only shown when it is enabled 

567 if report.var_perplexity is None: 

568 var_msg = '' 

569 else: 

570 var_msg = f'var: {report.var_perplexity:.1f}/{report.p_eff}, ' 

571 

572 print( # noqa: T201, see PrintCallback for why not logging 

573 f'{prefix}It {it}/{n_iters}, ' 

574 f'move acc: {report.move_acc:.0%}, ' 

575 f'{var_msg}' 

576 f'leaves: {report.mean_leaves:.1f}/{report.max_leaves}, ' 

577 f'tree life: {report.mean_tree_life:.0f}/{report.steps_done}{suffix}' 

578 ) 

579 

580 

581@dataclass(frozen=True) 

582class _TqdmEntry: 

583 """An entry in the `tqdm` bar registry.""" 

584 

585 kwargs: dict[str, Any] 

586 """Keyword arguments to construct the bar with, from `TqdmCallback.from_state`.""" 

587 

588 thread: int 

589 """Identifier of the thread that called `TqdmCallback.from_state`.""" 

590 

591 bar: tqdm | None = None 

592 """The bar, created lazily on the first callback invocation, `None` until then.""" 

593 

594 

595# tqdm carries Python state that cannot live in a jax pytree, so the bars are 

596# kept here and referenced from the jax loop through the integer handle stored 

597# in `TqdmCallback.bar_id` (a traceable scalar, so the loop pytree stays 

598# stable across runs and is not recompiled). 

599_TQDM_REGISTRY: dict[int, _TqdmEntry] = {} 

600 

601# tqdm's default layout, but without the ': ' that `format_meter` forces after a 

602# non-empty description; the label is set as a `{desc}` ending in a space instead 

603_TQDM_BAR_FORMAT = ( 

604 '{desc}{percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} ' 

605 '[{elapsed}<{remaining}, {rate_fmt}{postfix}]' 

606) 

607 

608 

609def _close_stale_bars() -> None: 

610 """Close and drop the bars left open by previous (e.g. interrupted) runs.""" 

611 # spare the bars of other threads, which may be running, and the unstarted 

612 # ones, which may belong to callbacks yet to be passed to `run_mcmc` 

613 thread = get_ident() 

614 # iterate over a copy because the progress callbacks may modify the registry 

615 for bar_id, entry in _TQDM_REGISTRY.copy().items(): 

616 if entry.bar is not None and entry.thread == thread: 

617 entry.bar.close() 

618 _TQDM_REGISTRY.pop(bar_id, None) 

619 

620 

621def _get_or_create_bar(bar_id: int, n_iters: int) -> tqdm | None: 

622 """Return the bar for `bar_id`, creating it on first use, `None` if finished.""" 

623 entry = _TQDM_REGISTRY.get(bar_id) 

624 if entry is None: 624 ↛ 626line 624 didn't jump to line 626 because the condition on line 624 was never true

625 # the bar was already closed (the loop finished, possibly out of order) 

626 return None 

627 if entry.bar is None: 

628 bar = tqdm( 

629 **{ 

630 'total': n_iters, 

631 'bar_format': _TQDM_BAR_FORMAT, 

632 'desc': 'train ', 

633 **entry.kwargs, 

634 } 

635 ) 

636 _TQDM_REGISTRY[bar_id] = replace(entry, bar=bar) 

637 return bar 

638 return entry.bar 

639 

640 

641@_convert_jax_arrays_in_args 

642# convert all jax arrays in arguments, see _print_report for why 

643def _tqdm_update( 

644 bar_id: int, it: int, n_iters: int, report: StatsReport | None 

645) -> None: 

646 """Set the statistics postfix if `report` is given, then advance the bar.""" 

647 if report is not None: 

648 _tqdm_report(report, bar_id, n_iters) 

649 _tqdm_advance(bar_id, it, n_iters) 

650 

651 

652def _tqdm_advance(bar_id: int, it: int, n_iters: int) -> None: 

653 """Advance the bar towards absolute position `it`, closing it at the end.""" 

654 bar = _get_or_create_bar(bar_id, n_iters) 

655 if bar is None: 655 ↛ 656line 655 didn't jump to line 656 because the condition on line 655 was never true

656 return 

657 bar.update(max(0, it - bar.n)) # forward-only: callbacks may arrive out of order 

658 if it >= n_iters: 

659 bar.close() 

660 _TQDM_REGISTRY.pop(bar_id, None) # may race with `_close_stale_bars` 

661 

662 

663def _tqdm_report(report: StatsReport, bar_id: int, n_iters: int) -> None: 

664 """Set the acceptance-statistics postfix of the bar.""" 

665 bar = _get_or_create_bar(bar_id, n_iters) 

666 if bar is None: 666 ↛ 667line 666 didn't jump to line 667 because the condition on line 666 was never true

667 return 

668 # keep this terse so the bar stays narrow, e.g. '4c100s ac30% le2.6/32 tl101/2000' 

669 msgs = [] 

670 avg_over = '' 

671 if report.num_chains is not None: 

672 avg_over += f'{report.num_chains}c' 

673 if report.n_samples is not None: 

674 avg_over += f'{report.n_samples}s' 

675 if avg_over: 

676 msgs.append(avg_over) 

677 msgs.append(f'ac{report.move_acc:.0%}') 

678 if report.var_perplexity is not None: 

679 msgs.append(f'va{report.var_perplexity:.1f}/{report.p_eff}') 

680 msgs.append(f'le{report.mean_leaves:.1f}/{report.max_leaves}') 

681 msgs.append(f'tl{report.mean_tree_life:.0f}/{report.steps_done}') 

682 bar.set_postfix_str(' '.join(msgs)) 

683 

684 

685@serializable 

686class CheckPlatformCallback(Callback): 

687 """Check the given platform matches the actual platform at runtime.""" 

688 

689 platform: Literal['cpu', 'gpu'] = field(static=True) 

690 """The expected platform.""" 

691 

692 def __call__(self, *, i_total: Int32[Array, ''], **_: Any) -> None: 

693 """Check the platform on the first iteration, raise on mismatch.""" 

694 

695 def check() -> None: 

696 lax.platform_dependent( 

697 cpu=partial(_check_platform, 'cpu', self.platform), 

698 cuda=partial(_check_platform, 'gpu', self.platform), 

699 ) 

700 

701 lax.cond(i_total == 0, check, lambda: None) 

702 

703 

704def _check_platform(actual_platform: str, expected_platform: str) -> None: 

705 """Raise from a debug callback if the platform differs from expected.""" 

706 

707 def raise_if_mismatch() -> None: 

708 if actual_platform != expected_platform: 

709 msg = ( 

710 f'`Bart` deduced the platform as {expected_platform!r}, ' 

711 'but the MCMC is running on ' 

712 f'{actual_platform!r}, so the automatic deduction was wrong; please ' 

713 'tell `Bart` what the correct platform is by setting the `devices` ' 

714 'argument.' 

715 ) 

716 raise RuntimeError(msg) 

717 

718 debug.callback(raise_if_mismatch) 

719 

720 

721@serializable 

722class CheckNumTreesCallback(Callback): 

723 """Warn if the number of trees is slow on the platform the MCMC runs on. 

724 

725 On cpu, fewer trees (times chains) than threads slow down each MCMC step, 

726 unless there are few datapoints. No number of trees is slow on gpu. 

727 """ 

728 

729 def __call__(self, *, state: State, i_total: Int32[Array, ''], **_: Any) -> None: 

730 """Check the number of trees on the first iteration, warn if slow.""" 

731 warn_if_few = partial(_warn_if_few_trees, state.forest.leaf_indices.shape) 

732 

733 def check() -> None: 

734 lax.cond(i_total == 0, partial(debug.callback, warn_if_few), lambda: None) 

735 

736 # the platform is picked outermost to leave nothing in the loop on gpu 

737 lax.platform_dependent(cpu=check, default=lambda: None) 

738 

739 

740def _warn_if_few_trees(leaf_indices_shape: tuple[int, ...]) -> None: 

741 """Warn if the trees (times chains) are fewer than the cpu threads.""" 

742 *chains, num_trees, n = leaf_indices_shape 

743 num_chains = math.prod(chains) 

744 trees = num_chains * num_trees 

745 threads = get_cpu_thread_count() 

746 assert threads is not None # there is a cpu backend if this runs 

747 # xla:cpu does not vectorize a loop over the datapoints of fewer trees than 

748 # threads, unless there are few enough datapoints that it does not split 

749 # them across threads 

750 if 1 < trees < threads and n >= 2**11: 

751 msg = ( 

752 f'There are fewer trees (times chains) than cpu threads ({trees} < ' 

753 f'{threads}), which slows down each MCMC step on cpu. Use at least ' 

754 f'{-(-threads // num_chains)} trees to avoid this, possibly with ' 

755 '`used_trees` to keep the additional ones out of the model.' 

756 ) 

757 warn(msg)