tinymind/tree.rs
1//! Quantized decision trees and gradient-boosted tree ensembles (C++
2//! `cpp/qtree.hpp`).
3//!
4//! A tree walk is a handful of integer compares and branches: no
5//! multiply-accumulates, no activation tables. Each split compares one input
6//! feature against a threshold on the same integer grid as the feature. An affine
7//! map is monotone, so `x_q <= t_q` makes the same decision as `x <= t` in the
8//! real domain, except for an input within one grid step of the threshold. Leaf
9//! values are `i32`, so an ensemble can add them up into per-class scores.
10//!
11//! - [`QTreeNode`]: one node of a flat node array (a *pool*), with integer
12//! indices to its children.
13//! - [`QDecisionTree`]: one tree, rooted at node 0; returns its leaf's value.
14//! - [`QGbdt`]: an additive ensemble whose trees share one pool. Each tree adds
15//! its leaf value to one class's score; the prediction is the class with the
16//! largest score. A single regression output is the case of one class.
17//!
18//! Both borrow their arrays, so a model can be `static` or `const` data in
19//! flash, and both are generic over the threshold type `T` and the input type
20//! `I` (`i8`, `u8`, `i16`, anything that converts losslessly to `i32`); the
21//! compare is made in `i32`, as in the C++.
22//!
23//! # Malformed models
24//!
25//! The C++ reads out of bounds for a child, root or feature index outside the
26//! model (undefined behaviour), and checks indices at compile time only for its
27//! compile-time models. Here every function is total instead: a walk that meets
28//! an index outside the pool or the input stops and contributes 0, and a tree
29//! whose class index is out of range contributes nothing. A cyclic pool ends
30//! after as many steps as the pool has nodes, as in the C++. Well-formed models
31//! give the C++ results exactly; check a model with [`QDecisionTree::is_valid`]
32//! or [`QGbdt::is_valid`], which are `const fn`, so a model in a `const` can be
33//! checked at compile time:
34//!
35//! ```
36//! use tinymind::tree::{QDecisionTree, QTreeNode};
37//!
38//! const fn split(feature: i16, threshold: i8, left: i16, right: i16) -> QTreeNode<i8> {
39//! QTreeNode { feature, threshold, left, right, leaf_value: 0 }
40//! }
41//! const fn leaf(value: i32) -> QTreeNode<i8> {
42//! QTreeNode { feature: -1, threshold: 0, left: -1, right: -1, leaf_value: value }
43//! }
44//!
45//! // x[0] <= 10 ? 1 : (x[1] <= -5 ? 2 : 3)
46//! static NODES: [QTreeNode<i8>; 5] = [split(0, 10, 1, 2), leaf(1), split(1, -5, 3, 4), leaf(2), leaf(3)];
47//! const TREE: QDecisionTree<'static, i8, 5, 2> = QDecisionTree::new(&NODES);
48//! const _: () = assert!(TREE.is_valid());
49//!
50//! assert_eq!(TREE.predict(&[10i8, 0]), 1);
51//! assert_eq!(TREE.predict(&[11i8, -5]), 2);
52//! assert_eq!(TREE.predict(&[11i8, -4]), 3);
53//! ```
54//!
55//! Not ported: the C++ compile-time models (`QStaticDecisionTree`,
56//! `QStaticGBDT`) and their evaluation policies. Rust cannot run a pool through
57//! the type system the way C++ templates do. The repository's tree importer
58//! (`tools/import_trees`, for scikit-learn, XGBoost and LightGBM models) writes
59//! a module with both forms instead: a pool walked by these types, and the same
60//! trees as nested `if`s (the inline policy).
61
62/// One node of a quantized decision tree (C++ `QTreeNode`).
63///
64/// `feature >= 0` marks a split: go to `left` if `x[feature] <= threshold`,
65/// else to `right` (indices into the same node array). `feature < 0` marks a
66/// leaf, whose prediction is `leaf_value`; a split's `leaf_value` and a leaf's
67/// other fields are not read.
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69pub struct QTreeNode<T> {
70 /// Input feature this node splits on; negative for a leaf.
71 pub feature: i16,
72 /// Split threshold, on the feature's integer grid.
73 pub threshold: T,
74 /// Child for `x[feature] <= threshold`.
75 pub left: i16,
76 /// Child for `x[feature] > threshold`.
77 pub right: i16,
78 /// The leaf's value.
79 pub leaf_value: i32,
80}
81
82/// The node at index `n`, or `None` outside the pool.
83fn node<T>(nodes: &[QTreeNode<T>], n: i16) -> Option<&QTreeNode<T>> {
84 usize::try_from(n).ok().and_then(|i| nodes.get(i))
85}
86
87/// Walk the tree rooted at `root` in the pool `nodes` to a leaf and return its
88/// value (C++ `walkQTree`). At most `max_nodes` splits are followed, so a cyclic
89/// pool ends; the node reached then gives its `leaf_value`, as in the C++. An
90/// index outside `nodes` or `x` ends the walk with 0 (see the module docs).
91pub fn walk_tree<I, T>(nodes: &[QTreeNode<T>], root: i16, x: &[I], max_nodes: usize) -> i32
92where
93 I: Copy + Into<i32>,
94 T: Copy + Into<i32>,
95{
96 let mut n = root;
97 for _ in 0..max_nodes {
98 let Some(node) = node(nodes, n) else {
99 return 0;
100 };
101 if node.feature < 0 {
102 return node.leaf_value;
103 }
104 let Some(&xv) = x.get(node.feature as usize) else {
105 return 0;
106 };
107 n = if xv.into() <= node.threshold.into() {
108 node.left
109 } else {
110 node.right
111 };
112 }
113 node(nodes, n).map_or(0, |node| node.leaf_value)
114}
115
116/// Whether every split in `nodes` reads a feature below `features` and points
117/// at children inside the pool (C++ `qtreePoolIsValid`).
118const fn pool_is_valid<T>(nodes: &[QTreeNode<T>], features: usize) -> bool {
119 let len = nodes.len();
120 let mut i = 0;
121 while i < len {
122 let n = &nodes[i];
123 if n.feature >= 0
124 && (n.feature as usize >= features
125 || n.left < 0
126 || n.left as usize >= len
127 || n.right < 0
128 || n.right as usize >= len)
129 {
130 return false;
131 }
132 i += 1;
133 }
134 true
135}
136
137/// A single quantized decision tree over `FEATURES` inputs, with `NODES` nodes;
138/// `nodes[0]` is the root (C++ `QDecisionTree`).
139#[derive(Clone, Copy, Debug)]
140pub struct QDecisionTree<'a, T, const NODES: usize, const FEATURES: usize> {
141 /// The node pool.
142 pub nodes: &'a [QTreeNode<T>; NODES],
143}
144
145impl<'a, T, const NODES: usize, const FEATURES: usize> QDecisionTree<'a, T, NODES, FEATURES> {
146 /// A tree over the pool `nodes`.
147 pub const fn new(nodes: &'a [QTreeNode<T>; NODES]) -> Self {
148 Self { nodes }
149 }
150
151 /// Whether every split reads a feature below `FEATURES` and points at
152 /// children inside the pool. A cycle is not detected; it ends as described
153 /// in the module docs.
154 pub const fn is_valid(&self) -> bool {
155 pool_is_valid(self.nodes, FEATURES)
156 }
157
158 /// The value of the leaf that `x` reaches.
159 pub fn predict<I: Copy + Into<i32>>(&self, x: &[I; FEATURES]) -> i32
160 where
161 T: Copy + Into<i32>,
162 {
163 const { assert!(NODES > 0 && FEATURES > 0, "a tree needs nodes and features") };
164 walk_tree(self.nodes, 0, x, NODES)
165 }
166}
167
168/// A gradient-boosted ensemble of `TREES` trees sharing one pool of `NODES`
169/// nodes, scoring `CLASSES` classes from `FEATURES` inputs (C++ `QGBDT`).
170///
171/// Tree `t` starts at `nodes[tree_root[t]]` and adds its leaf value to the
172/// score of class `tree_class[t]`. Scores start at `base_score` (zero when
173/// `None`).
174#[derive(Clone, Copy, Debug)]
175pub struct QGbdt<
176 'a,
177 T,
178 const TREES: usize,
179 const CLASSES: usize,
180 const NODES: usize,
181 const FEATURES: usize,
182> {
183 /// The shared node pool.
184 pub nodes: &'a [QTreeNode<T>; NODES],
185 /// Each tree's root index into `nodes`.
186 pub tree_root: &'a [i16; TREES],
187 /// The class each tree scores, in `0..CLASSES` (0 for a regression).
188 pub tree_class: &'a [i16; TREES],
189 /// Each class's starting score, or `None` for zeros.
190 pub base_score: Option<&'a [i32; CLASSES]>,
191}
192
193impl<T, const TREES: usize, const CLASSES: usize, const NODES: usize, const FEATURES: usize>
194 QGbdt<'_, T, TREES, CLASSES, NODES, FEATURES>
195{
196 /// Whether every split reads a feature below `FEATURES` and points at
197 /// children inside the pool, every root is inside the pool, and every class
198 /// index is below `CLASSES`. A cycle is not detected; it ends as described
199 /// in the module docs.
200 pub const fn is_valid(&self) -> bool {
201 let mut t = 0;
202 while t < TREES {
203 let root = self.tree_root[t];
204 let class = self.tree_class[t];
205 if root < 0 || root as usize >= NODES || class < 0 || class as usize >= CLASSES {
206 return false;
207 }
208 t += 1;
209 }
210 pool_is_valid(self.nodes, FEATURES)
211 }
212
213 /// Every class's score: its base score plus the leaf values of its trees,
214 /// added in tree order (wrapping on `i32` overflow, which the C++ leaves
215 /// undefined).
216 pub fn forward<I: Copy + Into<i32>>(&self, x: &[I; FEATURES]) -> [i32; CLASSES]
217 where
218 T: Copy + Into<i32>,
219 {
220 const {
221 assert!(
222 TREES > 0 && CLASSES > 0 && NODES > 0 && FEATURES > 0,
223 "an ensemble needs trees, classes, nodes and features"
224 )
225 };
226 let mut scores = self.base_score.copied().unwrap_or([0; CLASSES]);
227 for (&root, &class) in self.tree_root.iter().zip(self.tree_class) {
228 let leaf = walk_tree(self.nodes, root, x, NODES);
229 if let Some(s) = usize::try_from(class).ok().and_then(|c| scores.get_mut(c)) {
230 *s = s.wrapping_add(leaf);
231 }
232 }
233 scores
234 }
235
236 /// The class with the largest score; the lowest index on a tie.
237 pub fn predict<I: Copy + Into<i32>>(&self, x: &[I; FEATURES]) -> usize
238 where
239 T: Copy + Into<i32>,
240 {
241 let scores = self.forward(x);
242 // The running best is carried by value, not re-read by index: panic
243 // freedom must not depend on the compiler proving `best` in range.
244 let mut best = (0, scores.first().copied().unwrap_or(0));
245 for (c, &s) in scores.iter().enumerate().skip(1) {
246 if s > best.1 {
247 best = (c, s);
248 }
249 }
250 best.0
251 }
252}
253
254#[cfg(test)]
255mod tests {
256 use super::*;
257
258 const fn split(feature: i16, threshold: i8, left: i16, right: i16) -> QTreeNode<i8> {
259 QTreeNode {
260 feature,
261 threshold,
262 left,
263 right,
264 leaf_value: 0,
265 }
266 }
267
268 const fn leaf(value: i32) -> QTreeNode<i8> {
269 QTreeNode {
270 feature: -1,
271 threshold: 0,
272 left: -1,
273 right: -1,
274 leaf_value: value,
275 }
276 }
277
278 #[test]
279 fn walk_follows_splits_inclusively() {
280 let nodes = [split(0, 0, 1, 2), leaf(-7), leaf(9)];
281 assert_eq!(walk_tree(&nodes, 0, &[0i8], 3), -7);
282 assert_eq!(walk_tree(&nodes, 0, &[1i8], 3), 9);
283 assert_eq!(walk_tree(&nodes, 0, &[-128i8], 3), -7);
284 // A root that is a leaf.
285 assert_eq!(walk_tree(&nodes, 2, &[0i8], 3), 9);
286 // Mixed input and threshold types compare in i32.
287 assert_eq!(walk_tree(&nodes, 0, &[200u8], 3), 9);
288 }
289
290 #[test]
291 fn malformed_pools_are_total() {
292 // Child, root and feature out of range give 0.
293 let bad_child = [split(0, 0, 5, -1), leaf(1)];
294 assert_eq!(walk_tree(&bad_child, 0, &[0i8], 2), 0);
295 assert_eq!(walk_tree(&bad_child, 0, &[1i8], 2), 0);
296 assert_eq!(walk_tree(&bad_child, -1, &[0i8], 2), 0);
297 assert_eq!(walk_tree(&bad_child, 9, &[0i8], 2), 0);
298 let bad_feature = [split(3, 0, 1, 1), leaf(1)];
299 assert_eq!(walk_tree(&bad_feature, 0, &[0i8], 2), 0);
300 // A cycle stops after max_nodes steps and reads that node's leaf_value
301 // field, as the C++ does.
302 let mut cyclic = [split(0, 0, 1, 1), split(0, 0, 0, 0)];
303 cyclic[0].leaf_value = 4;
304 cyclic[1].leaf_value = 5;
305 assert_eq!(walk_tree(&cyclic, 0, &[0i8], 2), 4);
306 assert_eq!(walk_tree(&cyclic, 0, &[0i8], 3), 5);
307 assert_eq!(walk_tree(&cyclic, 0, &[0i8], 0), 4);
308 }
309
310 static ENSEMBLE: [QTreeNode<i8>; 6] = [
311 split(0, 0, 1, 2),
312 leaf(10),
313 leaf(-10),
314 split(1, 5, 4, 5),
315 leaf(3),
316 leaf(30),
317 ];
318 const GBDT: QGbdt<'static, i8, 2, 2, 6, 2> = QGbdt {
319 nodes: &ENSEMBLE,
320 tree_root: &[0, 3],
321 tree_class: &[0, 1],
322 base_score: Some(&[1, -1]),
323 };
324 const _: () = assert!(GBDT.is_valid());
325
326 #[test]
327 fn ensemble_adds_leaves_per_class() {
328 assert_eq!(GBDT.forward(&[0i8, 5]), [11, 2]);
329 assert_eq!(GBDT.predict(&[0i8, 5]), 0);
330 assert_eq!(GBDT.forward(&[1i8, 6]), [-9, 29]);
331 assert_eq!(GBDT.predict(&[1i8, 6]), 1);
332 // A tie goes to the lowest class.
333 let tie = QGbdt::<'_, i8, 2, 2, 6, 2> {
334 base_score: Some(&[0, 7]),
335 ..GBDT
336 };
337 assert_eq!(tie.forward(&[0i8, 5]), [10, 10]);
338 assert_eq!(tie.predict(&[0i8, 5]), 0);
339 // No base score starts at zero; sums wrap.
340 let wrap = QGbdt::<'_, i8, 2, 2, 6, 2> {
341 base_score: Some(&[i32::MAX, 0]),
342 ..GBDT
343 };
344 assert_eq!(wrap.forward(&[0i8, 5])[0], i32::MIN + 9);
345 let none = QGbdt::<'_, i8, 2, 2, 6, 2> {
346 base_score: None,
347 ..GBDT
348 };
349 assert_eq!(none.forward(&[0i8, 5]), [10, 3]);
350 }
351
352 #[test]
353 fn validity() {
354 let nodes = [split(1, 0, 1, 2), leaf(0), leaf(0)];
355 assert!(QDecisionTree::<'_, i8, 3, 2>::new(&nodes).is_valid());
356 assert!(!QDecisionTree::<'_, i8, 3, 1>::new(&nodes).is_valid());
357 let child = [split(0, 0, 1, 3), leaf(0), leaf(0)];
358 assert!(!QDecisionTree::<'_, i8, 3, 1>::new(&child).is_valid());
359 let negative = [split(0, 0, -1, 2), leaf(0), leaf(0)];
360 assert!(!QDecisionTree::<'_, i8, 3, 1>::new(&negative).is_valid());
361 let bad_class = QGbdt::<'_, i8, 2, 2, 6, 2> {
362 tree_class: &[0, 2],
363 ..GBDT
364 };
365 assert!(!bad_class.is_valid());
366 // An invalid class index is skipped.
367 assert_eq!(bad_class.forward(&[0i8, 5]), [11, -1]);
368 let bad_root = QGbdt::<'_, i8, 2, 2, 6, 2> {
369 tree_root: &[0, 6],
370 ..GBDT
371 };
372 assert!(!bad_root.is_valid());
373 assert_eq!(bad_root.forward(&[0i8, 5]), [11, -1]);
374 }
375}