Coverage for src/bartz/bcf/_step.py: 99%
91 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-30 12:50 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-30 12:50 +0000
1# bartz/src/bartz/bcf/_step.py
2#
3# Copyright (c) 2026, The Bartz Contributors
4#
5# This file is part of bartz.
6#
7# Permission is hereby granted, free of charge, to any person obtaining a copy
8# of this software and associated documentation files (the "Software"), to deal
9# in the Software without restriction, including without limitation the rights
10# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11# copies of the Software, and to permit persons to whom the Software is
12# furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice shall be included in all
15# copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23# SOFTWARE.
25"""Implement `step_bcf`."""
27from dataclasses import replace
28from typing import cast
30import jax.numpy as jnp
31from equinox import tree_at
32from jax import lax, named_call, random, vmap
33from jax.nn import sigmoid
34from jax.scipy.special import log_ndtr
35from jaxtyping import Array, Float, Float32, Key, UInt
37from bartz._jaxext import (
38 float32_matmuls,
39 forbid_x64,
40 jit,
41 sliced_map,
42 split,
43 truncated_normal_onesided,
44)
45from bartz.bcf._state import BCFState, coding_basis, swap_mu_tau_forests
46from bartz.mcmcstep import Forest, StepConfig, step
47from bartz.mcmcstep._state import split_key_for_chains, vmap_chains
48from bartz.mcmcstep._step import step_sum_trees_prior_cov_inv, step_trees, sum_resid
51def recompute_prec_trees(
52 forest: Forest, prec_scale: Float[Array, ' n'], config: StepConfig
53) -> Float32[Array, 'num_trees max_num_leaves']:
54 """
55 Rebuild `Forest.prec_tree` from scratch for a new `prec_scale`.
57 Like the incremental update in `step`, the result is valid at the leaves of
58 the largest version of each tree compatible with the last move.
60 Parameters
61 ----------
62 forest
63 The forest whose per-leaf precision cache is stale.
64 prec_scale
65 The new per-datapoint precision scale.
66 config
67 The MCMC configuration, for the reduction settings.
69 Returns
70 -------
71 The per-leaf sums of `prec_scale`.
72 """
73 _, max_num_leaves = forest.leaf_tree.shape
75 def one_tree(leaf_indices: UInt[Array, ' n']) -> Float32[Array, ' max_num_leaves']:
76 # the sum over all bins has the shape of the residual reduction, so use
77 # its settings rather than the ones tuned for the two-bin `prec_tree` update
78 return sum_resid(
79 prec_scale,
80 leaf_indices,
81 max_num_leaves,
82 config.resid_reduction_config,
83 config.data_sharded,
84 )
86 xs = forest.leaf_indices
88 def all_trees() -> Float32[Array, 'num_trees max_num_leaves']:
89 return vmap(one_tree)(xs)
91 if config.prec_count_num_trees is None: 91 ↛ 96line 91 didn't jump to line 96 because the condition on line 91 was always true
92 return all_trees()
94 else:
96 def tree_batches(
97 batch_size: int = config.prec_count_num_trees,
98 ) -> Float32[Array, 'num_trees max_num_leaves']:
99 return sliced_map(one_tree, xs, batch_size=batch_size)
101 # like `compute_prec_trees`, batch the trees on cpu to bound the reduction
102 # temporaries
103 return lax.platform_dependent(cpu=tree_batches, cuda=all_trees)
106@named_call
107def step_mu(key: Key[Array, ''], state: BCFState) -> BCFState:
108 """Update the prognostic forest and the prior precision of its sum of trees."""
109 # `step` rebuilds the state with `replace`, so it preserves the subclass.
110 # WORKAROUND(python<3.12): type `step` as generic over the state subclass
111 # (PEP 695) instead of casting here, since a TypeVar renders badly in the
112 # html documentation.
113 return cast(BCFState, step(key, state))
116@named_call
117def step_tau_0(key: Key[Array, ''], state: BCFState) -> BCFState:
118 """Update the treatment effect intercept."""
119 # `resid` is stored scaled: ``resid_unit * resid = data residual``, whereas
120 # `tau_0`, `tau_X`, `b`, `error_cov_inv` and `tau_0_prior_cov_inv` are
121 # on the data scale (matching `_bcf.predict`). Convert `resid` in and out of data
122 # units so the scalar Gibbs updates here and in `step_b` are
123 # unit-consistent for any `resid_unit` (no-op when it is 1).
125 if state.tau_0_prior_cov_inv is None:
126 return state
128 else:
129 b_z = coding_basis(state.b, state.trt)
131 # partial residual removing current tau_0 effect, on the data scale
132 partial_resid = state.resid * state.resid_unit + state.tau_0 * b_z
134 # determine full conditional of tau_0
135 prec = (
136 jnp.sum(jnp.square(b_z)) * state.error_cov_inv.value
137 + state.tau_0_prior_cov_inv
138 )
139 mean = jnp.sum(b_z * partial_resid) * state.error_cov_inv.value / prec
141 # sample tau_0 from full conditional
142 tau_0_new = mean + random.normal(key) * lax.rsqrt(prec)
144 # update state to reflect new tau_0
145 return replace(
146 state,
147 tau_0=tau_0_new,
148 resid=state.resid - b_z * (tau_0_new - state.tau_0) / state.resid_unit,
149 )
152@named_call
153def step_tau(key: Key[Array, ''], state: BCFState) -> BCFState:
154 """Update the treatment effect forest and the prior precision of its sum of trees."""
155 keys = split(key)
157 b_z = coding_basis(state.b, state.trt)
159 # Target for tau is (Y - mu - b_z * tau_0) / b_z.
160 # Its residual is target - tau = (Y - mu - b_z*tau_0 - b_z*tau) / b_z
161 b_z_zero = jnp.abs(b_z) < 1e-10
162 b_z_safe = jnp.where(b_z_zero, 1.0, b_z)
163 mu_resid = state.resid
164 initial_resid_tau = jnp.where(b_z_zero, 0.0, mu_resid / b_z_safe)
166 # Swap the tau forest into the forest slot and run only the tree and prior
167 # precision steps on it; the mu forest rides along in `forest_tau`
168 # and is swapped back at the end. The other sub-steps of `step` (latent
169 # outcome, error precision, sparsity, step counter) belong to the mu phase
170 # alone.
171 mu_prec_scale = state.prec_scale
172 state = replace(
173 swap_mu_tau_forests(state), resid=initial_resid_tau, prec_scale=jnp.square(b_z)
174 )
176 # WORKAROUND(python<3.12): drop the casts like in `step_mu`
177 state = cast(BCFState, step_trees(keys.pop(), state))
178 state = cast(BCFState, step_sum_trees_prior_cov_inv(keys.pop(), state))
180 # Update tau_X! (the residual difference is scaled, bring it to data units)
181 if state.tau_X is not None:
182 state = replace(
183 state,
184 tau_X=state.tau_X + (initial_resid_tau - state.resid) * state.resid_unit,
185 )
187 # Swap the forests back and restore the mu-side fields
188 return replace(
189 swap_mu_tau_forests(state),
190 resid=jnp.where(b_z_zero, mu_resid, state.resid * b_z_safe),
191 prec_scale=mu_prec_scale,
192 )
195# The prior on the adaptive coding weights excludes |b| < B_GAP. Near b = 0 the
196# tau forest's working residual ``resid / b_z`` is large, and the running
197# update of `BCFState.tau_X` loses precision as 1 / |b|.
198B_GAP = 0.01
201def sample_gapped_normal(
202 key: Key[Array, ''],
203 mean: Float32[Array, ' k'],
204 prec: Float32[Array, ' k'],
205 gap: float,
206) -> Float32[Array, ' k']:
207 """Sample N(mean, 1 / prec) conditional on |x| >= gap, elementwise."""
208 keys = split(key)
209 sd = lax.rsqrt(prec)
211 # standardized edges of the gap
212 lo = (-gap - mean) / sd
213 hi = (gap - mean) / sd
215 # pick a side with probability proportional to its mass. The log masses
216 # cancel if both sides are far tails, so the choice degrades for sd < 1e-3 gap
217 log_mass_left = log_ndtr(lo)
218 log_mass_right = log_ndtr(-hi)
219 right = random.bernoulli(keys.pop(), sigmoid(log_mass_right - log_mass_left))
221 # sample within the side
222 z = truncated_normal_onesided(keys.pop(), (), ~right, jnp.where(right, hi, lo))
223 return mean + sd * z
226@named_call
227def step_b(key: Key[Array, ''], state: BCFState) -> BCFState:
228 """Update the adaptive coding weights."""
229 if state.b_prior_cov_inv is None:
230 return state
232 else:
233 assert state.tau_X is not None
235 b_z = coding_basis(state.b, state.trt)
237 # partial residual removing current b effect, on the data scale (see
238 # `step_tau_0` about units)
239 tau_full = state.tau_0 + state.tau_X
240 partial_resid = state.resid * state.resid_unit + tau_full * b_z
242 # determine full conditional of b, one Gibbs update per treatment group
243 groups = jnp.stack([~state.trt, state.trt])
244 prec = (
245 jnp.sum(jnp.square(tau_full) * groups, axis=1) * state.error_cov_inv.value
246 + state.b_prior_cov_inv
247 )
248 mean = (
249 jnp.sum(tau_full * partial_resid * groups, axis=1)
250 * state.error_cov_inv.value
251 / prec
252 )
254 # sample b from full conditional, truncated away from 0
255 b_new = sample_gapped_normal(key, mean, prec, B_GAP)
256 b_z_new = coding_basis(b_new, state.trt)
258 # update state to reflect new b
259 state = replace(
260 state,
261 b=b_new,
262 resid=state.resid - tau_full * (b_z_new - b_z) / state.resid_unit,
263 )
265 # the tau precision scale b_z^2 changed on every datapoint, so the
266 # incrementally maintained per-leaf cache of the tau forest is stale
267 # everywhere
268 tau_side = swap_mu_tau_forests(state)
269 return tree_at(
270 lambda s: s.forest_tau.prec_tree,
271 state,
272 recompute_prec_trees(tau_side.forest, jnp.square(b_z_new), tau_side.config),
273 )
276@jit(donate_argnums=(1,))
277@forbid_x64
278@split_key_for_chains
279@vmap_chains
280@float32_matmuls
281def step_bcf(key: Key[Array, ''], state: BCFState) -> BCFState:
282 """
283 Do one BCF MCMC step.
285 Parameters
286 ----------
287 key
288 A jax random key.
289 state
290 A BCF MCMC state, as created by `init_bcf`.
292 Returns
293 -------
294 The new BCF MCMC state.
296 Notes
297 -----
298 The memory of the input state is re-used for the output state, so the input
299 state can not be used any more after calling `step_bcf`. All this applies
300 outside of `jax.jit`.
302 To run the full MCMC, pass `step_bcf` to `bartz.mcmcloop.run_mcmc` as
303 ``step``, with `BCFBurninTrace` and `BCFMainTrace` as trace types.
304 """
305 keys = split(key, 4)
306 state = step_mu(keys.pop(), state)
307 state = step_tau_0(keys.pop(), state)
308 state = step_tau(keys.pop(), state)
309 return step_b(keys.pop(), state)