Coverage for src/bartz/grove/_check.py: 98%
94 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/grove/_check.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 functions to check validity of trees."""
27from typing import Protocol, runtime_checkable
29from jax import numpy as jnp
30from jaxtyping import Array, Bool, Integer, UInt
32from bartz._jaxext import autobatch, jit, minimal_unsigned_dtype
33from bartz.grove._grove import TreeHeaps, TreesTrace, is_actual_leaf, is_multivariate
35CHECK_FUNCTIONS = []
38@runtime_checkable
39class CheckFunc(Protocol):
40 """Protocol for functions that check whether a tree is valid."""
42 def __call__(
43 self, tree: TreeHeaps, max_split: UInt[Array, ' p'], /
44 ) -> bool | Bool[Array, '']:
45 """Check whether a tree is valid.
47 Parameters
48 ----------
49 tree
50 The tree to check.
51 max_split
52 The maximum split value for each variable.
54 Returns
55 -------
56 A boolean scalar indicating whether the tree is valid.
57 """
58 ...
61def check(func: CheckFunc) -> CheckFunc:
62 """Add a function to a list of functions used to check trees.
64 Use to decorate functions that check whether a tree is valid in some way.
65 These functions are invoked automatically by `check_tree` and `check_trace`.
67 Parameters
68 ----------
69 func
70 The function to add to the list. It must accept a `TreeHeaps` and a
71 `max_split` argument, and return a boolean scalar that indicates if the
72 tree is ok.
74 Returns
75 -------
76 The function unchanged.
77 """
78 CHECK_FUNCTIONS.append(func)
79 return func
82@check
83def check_types(tree: TreeHeaps, max_split: UInt[Array, ' p']) -> bool:
84 """Check that integer types are as small as possible and coherent."""
85 expected_var_dtype = minimal_unsigned_dtype(max_split.size - 1)
86 expected_split_dtype = max_split.dtype
87 return (
88 tree.var_tree.dtype == expected_var_dtype
89 and tree.split_tree.dtype == expected_split_dtype
90 and jnp.issubdtype(max_split.dtype, jnp.unsignedinteger)
91 )
94@check
95def check_shapes(tree: TreeHeaps, _max_split: UInt[Array, ' p']) -> bool:
96 """Check that array shapes are coherent."""
97 return (
98 tree.leaf_tree.ndim in (1, 2)
99 and tree.var_tree.ndim == 1
100 and tree.split_tree.ndim == 1
101 and tree.leaf_tree.shape[-1] == tree.var_tree.size == tree.split_tree.size
102 )
105@check
106def check_unused_node(
107 tree: TreeHeaps, _max_split: UInt[Array, ' p']
108) -> Bool[Array, '']:
109 """Check that the unused node slot at index 0 is not dirty."""
110 return (tree.var_tree[0] == 0) & (tree.split_tree[0] == 0)
113@check
114def check_leaf_values(
115 tree: TreeHeaps, _max_split: UInt[Array, ' p']
116) -> Bool[Array, '']:
117 """Check that all leaf values are not inf of nan."""
118 return jnp.all(jnp.isfinite(tree.leaf_tree))
121@check
122def check_stray_nodes(
123 tree: TreeHeaps, _max_split: UInt[Array, ' p']
124) -> Bool[Array, '']:
125 """Check if there is any marked-non-leaf node with a marked-leaf parent."""
126 index = jnp.arange(
127 2 * tree.split_tree.size,
128 dtype=minimal_unsigned_dtype(2 * tree.split_tree.size - 1),
129 )
130 parent_index = index >> 1
131 is_not_leaf = tree.split_tree.at[index].get(mode='fill', fill_value=0) != 0
132 parent_is_leaf = tree.split_tree[parent_index] == 0
133 stray = is_not_leaf & parent_is_leaf
134 stray = stray.at[1].set(False)
135 return ~jnp.any(stray)
138@check
139def check_rule_consistency(
140 tree: TreeHeaps, max_split: UInt[Array, ' p']
141) -> bool | Bool[Array, '']:
142 """Check that decision rules define proper subsets of ancestor rules."""
143 if tree.var_tree.size < 4: 143 ↛ 144line 143 didn't jump to line 144 because the condition on line 143 was never true
144 return True
146 # initial boundaries of decision rules. use extreme integers instead of 0,
147 # max_split to avoid checking if there is something out of bounds.
148 dtype = tree.split_tree.dtype
149 small = jnp.iinfo(dtype).min
150 large = jnp.iinfo(dtype).max
151 lower = jnp.full(max_split.size, small, dtype)
152 upper = jnp.full(max_split.size, large, dtype)
153 # the split must be in (lower[var], upper[var]]
155 def _check_recursive(
156 node: int, lower: UInt[Array, ' p'], upper: UInt[Array, ' p']
157 ) -> Bool[Array, '']:
158 # read decision rule
159 var = tree.var_tree[node]
160 split = tree.split_tree[node]
162 # get rule boundaries from ancestors. use fill value in case var is
163 # out of bounds, we don't want to check out of bounds in this function
164 lower_var = lower.at[var].get(mode='fill', fill_value=small)
165 upper_var = upper.at[var].get(mode='fill', fill_value=large)
167 # check rule is in bounds
168 bad = jnp.where(split, (split <= lower_var) | (split > upper_var), False)
170 # recurse
171 if node < tree.var_tree.size // 2:
172 idx = jnp.where(split, var, max_split.size)
173 bad |= _check_recursive(2 * node, lower, upper.at[idx].set(split - 1))
174 bad |= _check_recursive(2 * node + 1, lower.at[idx].set(split), upper)
176 return bad
178 return ~_check_recursive(1, lower, upper)
181@check
182def check_num_nodes(
183 tree: TreeHeaps,
184 max_split: UInt[Array, ' p'], # noqa: ARG001
185) -> Bool[Array, '']:
186 """Check that #leaves = 1 + #(internal nodes)."""
187 is_leaf = is_actual_leaf(tree.split_tree, add_bottom_level=True)
188 num_leaves = jnp.count_nonzero(is_leaf)
189 num_internal = jnp.count_nonzero(tree.split_tree)
190 return num_leaves == num_internal + 1
193@check
194def check_var_in_bounds(
195 tree: TreeHeaps, max_split: UInt[Array, ' p']
196) -> Bool[Array, '']:
197 """Check that variables are in [0, max_split.size)."""
198 decision_node = tree.split_tree.astype(bool)
199 in_bounds = (tree.var_tree >= 0) & (tree.var_tree < max_split.size)
200 return jnp.all(in_bounds | ~decision_node)
203@check
204def check_split_in_bounds(
205 tree: TreeHeaps, max_split: UInt[Array, ' p']
206) -> Bool[Array, '']:
207 """Check that splits are in [0, max_split[var]]."""
208 max_split_var = (
209 max_split.astype(jnp.int32)
210 .at[tree.var_tree]
211 .get(mode='fill', fill_value=jnp.iinfo(jnp.int32).max)
212 )
213 return jnp.all((tree.split_tree >= 0) & (tree.split_tree <= max_split_var))
216def check_tree(tree: TreeHeaps, max_split: UInt[Array, ' p']) -> UInt[Array, '']:
217 """Check the validity of a tree.
219 Use `describe_error` to parse the error code returned by this function.
221 Parameters
222 ----------
223 tree
224 The tree to check.
225 max_split
226 The maximum split value for each variable.
228 Returns
229 -------
230 An integer where each bit indicates whether a check failed.
231 """
232 error_type = minimal_unsigned_dtype(2 ** len(CHECK_FUNCTIONS) - 1)
233 error = jnp.zeros((), error_type)
234 for i, func in enumerate(CHECK_FUNCTIONS):
235 ok = func(tree, max_split)
236 ok = jnp.bool_(ok)
237 bit = (~ok) << i
238 error |= bit
239 return error
242def describe_error(error: int | Integer[Array, '']) -> list[str]:
243 """Describe an error code returned by `check_trace`.
245 Parameters
246 ----------
247 error
248 An error code returned by `check_trace`.
250 Returns
251 -------
252 A list of the function names that implement the failed checks.
253 """
254 return [func.__name__ for i, func in enumerate(CHECK_FUNCTIONS) if error & (1 << i)]
257@jit
258def check_trace(
259 trace: TreeHeaps, max_split: UInt[Array, ' p']
260) -> UInt[Array, '*batch_shape']:
261 """Check the validity of a set of trees.
263 Use `describe_error` to parse the error codes returned by this function.
265 Parameters
266 ----------
267 trace
268 The set of trees to check. This object can have additional attributes
269 beyond the tree arrays, they are ignored.
270 max_split
271 The maximum split value for each variable.
273 Returns
274 -------
275 A tensor of error codes for each tree.
276 """
277 # vectorize check_tree over all batch dimensions
278 unpack_check_tree = lambda l, v, s: check_tree(
279 TreesTrace(leaf_tree=l, var_tree=v, split_tree=s), max_split
280 )
281 is_mv = is_multivariate(trace)
282 signature = '(k,mnl),(mnl),(mnl)->()' if is_mv else '(mnl),(mnl),(mnl)->()'
283 vec_check_tree = jnp.vectorize(unpack_check_tree, signature=signature)
285 # automatically batch over all batch dimensions
286 max_io_nbytes = 2**24 # 16 MiB
287 batch_ndim = trace.split_tree.ndim - 1
288 batched_check_tree = vec_check_tree
289 for i in reversed(range(batch_ndim)):
290 batched_check_tree = autobatch(batched_check_tree, max_io_nbytes, i, i)
292 return batched_check_tree(trace.leaf_tree, trace.var_tree, trace.split_tree)