Coverage for src/bartz/mcmcstep/_axes.py: 97%

85 statements  

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

1# bartz/src/bartz/mcmcstep/_axes.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. 

24 

25"""Batch-axis bookkeeping: `field` markers and the chain/data/sample resolvers. 

26 

27Module dataclasses tag their array fields with chain/data/sample axis positions 

28via `field`; the resolvers here read those markers off a pytree to build the 

29`in_axes`/`out_axes` for `jax.vmap` and the axis positions used when reshaping. 

30""" 

31 

32import os 

33from collections.abc import Callable, Hashable 

34from dataclasses import fields 

35from typing import Any, TypeVar 

36 

37from equinox import Module as EquinoxModule 

38from jax import tree 

39from jaxtyping import PyTree, Shaped 

40from numpy.lib.array_utils import normalize_axis_index 

41 

42from bartz.mcmcstep._lazy import DummyArray, _LazyArray 

43 

44# Structure variable for the `PyTree[..., 'T']` annotations below. 

45T = TypeVar('T') 

46 

47# Position of the chain axis in the MCMC state, see `field`. Settable to -1 with 

48# the CHAIN_AXIS environment variable for internal performance experiments on 

49# `init` and `step` only (see `scripts/opt.py`). Everything else, from the 

50# traces onwards, assumes 0. 

51CHAIN_AXIS = int(os.environ.get('CHAIN_AXIS', '0')) 

52 

53 

54def chain_vmap_axes(x: PyTree[EquinoxModule | Any, 'T']) -> PyTree[int | None, 'T ...']: 

55 """Determine vmapping axes for chains. 

56 

57 This function determines the argument to the `in_axes` or `out_axes` 

58 parameter of `jax.vmap` to vmap over all and only the chain axes found in the 

59 pytree `x`. 

60 

61 Parameters 

62 ---------- 

63 x 

64 A pytree. Subpytrees that are Module attributes marked with 

65 ``field(chains=<int>)`` are considered to have a chain axis at that 

66 index. `x` (or one of its subtrees) must define a `has_chains` property 

67 (see `get_has_chains`). A nested Module defining `has_chains` overrides 

68 it for its own subtree. 

69 

70 Returns 

71 ------- 

72 A pytree with the same structure as `x`, with each leaf set to the chain axis index declared by its owning ``field(chains=...)`` marker, normalized against the leaf's ``ndim`` (so the returned indices are non-negative), or `None` for unmarked leaves or where `has_chains` is `False`. 

73 """ 

74 return _find_metadata(x, 'chains', has_chains=get_has_chains(x)) 

75 

76 

77def _none_marker(leaf: object, raw: int) -> None: # noqa: ARG001 

78 """Marker mapper that always returns `None`.""" 

79 return None # noqa: RET501 

80 

81 

82def data_vmap_axes(x: PyTree[EquinoxModule | Any, 'T']) -> PyTree[int | None, 'T ...']: 

83 """Determine vmapping axes for data. 

84 

85 Parameters 

86 ---------- 

87 x 

88 A pytree. Subpytrees that are Module attributes marked with 

89 ``field(data=<int>)`` are considered to have a data axis at that 

90 position in the chain-less layout. `x` (or one of its subtrees) must 

91 define a `has_chains` property (see `get_has_chains`). 

92 

93 Returns 

94 ------- 

95 A pytree with the same structure as `x`, with each leaf set to the data axis index (normalized and chain-shifted), or `None` for unmarked leaves. 

96 """ 

97 chain_axes = chain_vmap_axes(x) 

98 data_raw = _find_metadata(x, 'data', marker_value=_raw_marker) 

99 return tree.map( 

100 _compute_core_axis, x, data_raw, chain_axes, is_leaf=_is_core_axis_leaf 

101 ) 

102 

103 

104def trace_sample_axes( 

105 trace: PyTree[EquinoxModule | Any, 'T'], 

106) -> PyTree[int | None, 'T ...']: 

107 """Determine the position of the sample axis for each leaf of a trace. 

108 

109 Parameters 

110 ---------- 

111 trace 

112 A trace pytree (typically a `~bartz.mcmcloop.BurninTrace` or 

113 `~bartz.mcmcloop.MainTrace`). `trace` (or one of its subtrees) must 

114 define a `has_chains` property. 

115 

116 Returns 

117 ------- 

118 A pytree with the same structure as `trace` but with sample axes in the leaves, see `field`. 

119 """ 

120 chain_axes = chain_vmap_axes(trace) 

121 sample_raw = _find_metadata(trace, 'samples', marker_value=_raw_marker) 

122 return tree.map( 

123 _compute_core_axis, trace, sample_raw, chain_axes, is_leaf=_is_core_axis_leaf 

124 ) 

125 

126 

127def _raw_marker(leaf: object, raw: int) -> int: # noqa: ARG001 

128 """Marker mapper that returns the raw marker value.""" 

129 return raw 

130 

131 

132def _is_core_axis_leaf(x: object) -> bool: 

133 """Treat `None` and `_LazyArray` as leaves when resolving core-axis markers.""" 

134 return x is None or _is_lazy_array(x) 

135 

136 

137def chainful_axis(core_axis: int, chain_axis: int | None) -> int: 

138 """Position of a chainless-layout axis in the corresponding chainful array. 

139 

140 Parameters 

141 ---------- 

142 core_axis 

143 Non-negative axis position in the chainless ("core") layout. 

144 chain_axis 

145 Non-negative position of the chain axis in the chainful layout, or 

146 `None` if there is no chain axis. 

147 

148 Returns 

149 ------- 

150 The non-negative position of `core_axis` after inserting the chain axis at `chain_axis`. 

151 """ 

152 if chain_axis is None or core_axis < chain_axis: 

153 return core_axis 

154 return core_axis + 1 

155 

156 

157def _compute_core_axis( 

158 leaf: Shaped[DummyArray, '...'] | None, raw_axis: int | None, chain_axis: int | None 

159) -> int | None: 

160 """Combine a raw core-layout marker and a (normalized) chain position.""" 

161 if raw_axis is None: 

162 return None 

163 assert leaf is not None 

164 has_chain = chain_axis is not None 

165 core_ndim = leaf.ndim - (1 if has_chain else 0) 

166 axis = normalize_axis_index(raw_axis, core_ndim) 

167 return chainful_axis(axis, chain_axis) 

168 

169 

170class _HasChainsFound(Exception): 

171 """Internal control-flow signal carrying a found `has_chains` value.""" 

172 

173 def __init__(self, value: bool) -> None: 

174 self.value = value 

175 

176 

177def get_has_chains(x: PyTree) -> bool: 

178 """Return the `has_chains` flag from the first node in `x` that defines it. 

179 

180 Walks `x` and stops at the first node exposing a `has_chains` attribute, 

181 returning its value. The walk uses `jax.tree.map` with an `is_leaf` callback 

182 that raises a custom exception to short-circuit traversal. 

183 

184 Parameters 

185 ---------- 

186 x 

187 A pytree, possibly containing nodes that define a `has_chains` 

188 attribute. 

189 

190 Returns 

191 ------- 

192 The value of `has_chains` on the first matching node. 

193 

194 Raises 

195 ------ 

196 ValueError 

197 If no node in `x` defines a `has_chains` property. 

198 """ 

199 

200 def is_leaf(node: object) -> bool: 

201 value = getattr(node, 'has_chains', None) 

202 if value is None: 

203 return False 

204 raise _HasChainsFound(value) 

205 

206 try: 

207 tree.map(lambda _: None, x, is_leaf=is_leaf) 

208 except _HasChainsFound as exc: 

209 return exc.value 

210 msg = 'no `has_chains` property found in the pytree' 

211 raise ValueError(msg) 

212 

213 

214def _normalize_axis_for_leaf(leaf: Shaped[DummyArray, '...'], raw: int) -> int: 

215 """Normalize a marker axis index against `leaf.ndim`. 

216 

217 Raises `numpy.exceptions.AxisError` if `raw` is out of bounds for 

218 `leaf.ndim`. 

219 """ 

220 return normalize_axis_index(raw, leaf.ndim) 

221 

222 

223def _is_lazy_array(x: object) -> bool: 

224 return isinstance(x, _LazyArray) 

225 

226 

227def _is_module(x: object) -> bool: 

228 return isinstance(x, EquinoxModule) and not _is_lazy_array(x) 

229 

230 

231def _find_metadata( 

232 x: PyTree[Any, ' S'], 

233 key: Hashable, 

234 *, 

235 marker_value: Callable[[DummyArray, int], object] = _normalize_axis_for_leaf, 

236 default_value: object = None, 

237 has_chains: bool | None = None, 

238) -> PyTree[Any, ' S ...']: 

239 """Walk `x` replacing marked subtrees with derived values. 

240 

241 For each Module field whose metadata contains `key`, the field's subtree 

242 is replaced by mapping ``marker_value(leaf, raw)`` over its leaves, where 

243 `raw` is the unnormalized metadata value; leaves outside any marked field 

244 become `default_value`. If `has_chains` is set, it is updated by the 

245 Modules that define a `has_chains` property, and where it is `False` the 

246 marked leaves become `None`. 

247 """ 

248 if _is_module(x): 248 ↛ 287line 248 didn't jump to line 287 because the condition on line 248 was always true

249 if has_chains is not None: 

250 has_chains = getattr(x, 'has_chains', has_chains) 

251 if not has_chains: 

252 marker_value = _none_marker 

253 else: 

254 marker_value = _normalize_axis_for_leaf 

255 args = [] 

256 for f in fields(x): 

257 v = getattr(x, f.name) 

258 if f.metadata.get('static', False): 

259 args.append(v) 

260 elif key in f.metadata: 

261 raw = f.metadata[key] 

262 args.append( 

263 tree.map( 

264 lambda leaf, raw=raw: marker_value(leaf, raw), 

265 v, 

266 is_leaf=_is_lazy_array, 

267 ) 

268 ) 

269 else: 

270 args.append( 

271 _find_metadata( 

272 v, 

273 key, 

274 marker_value=marker_value, 

275 default_value=default_value, 

276 has_chains=has_chains, 

277 ) 

278 ) 

279 # rebuild bypassing the (type-checked) __init__: the result is a 

280 # same-structure pytree whose leaves are axis markers (int/None), not 

281 # the arrays the field annotations require. 

282 out = object.__new__(type(x)) 

283 for f, value in zip(fields(x), args, strict=True): 

284 object.__setattr__(out, f.name, value) 

285 return out 

286 

287 def get_axes(x: object) -> PyTree: 

288 if _is_module(x): 

289 return _find_metadata( 

290 x, 

291 key, 

292 marker_value=marker_value, 

293 default_value=default_value, 

294 has_chains=has_chains, 

295 ) 

296 return tree.map(lambda _: default_value, x, is_leaf=_is_lazy_array) 

297 

298 return tree.map(get_axes, x, is_leaf=lambda x: isinstance(x, EquinoxModule))