treeboost 0.1.0

High-performance Gradient Boosted Decision Tree engine for large-scale tabular data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Decision tree structure

use crate::dataset::BinnedDataset;
use crate::tree::{Node, NodeType};
use rayon::prelude::*;
use rkyv::{Archive, Deserialize, Serialize};

/// Decision tree
#[derive(Debug, Clone, Archive, Serialize, Deserialize, serde::Serialize, serde::Deserialize)]
pub struct Tree {
    /// Nodes in the tree (index 0 is root)
    nodes: Vec<Node>,
}

impl Tree {
    /// Create a new tree with a single root leaf
    pub fn new(root_value: f32, num_samples: usize, sum_g: f32, sum_h: f32) -> Self {
        Self {
            nodes: vec![Node::leaf(root_value, 0, num_samples, sum_g, sum_h)],
        }
    }

    /// Create from a vector of nodes
    pub fn from_nodes(nodes: Vec<Node>) -> Self {
        Self { nodes }
    }

    /// Get the root node
    #[inline]
    pub fn root(&self) -> &Node {
        &self.nodes[0]
    }

    /// Get a node by index
    #[inline]
    pub fn get_node(&self, idx: usize) -> &Node {
        &self.nodes[idx]
    }

    /// Get mutable node by index
    #[inline]
    pub fn get_node_mut(&mut self, idx: usize) -> &mut Node {
        &mut self.nodes[idx]
    }

    /// Add a node and return its index
    pub fn add_node(&mut self, node: Node) -> usize {
        let idx = self.nodes.len();
        self.nodes.push(node);
        idx
    }

    /// Number of nodes
    #[inline]
    pub fn num_nodes(&self) -> usize {
        self.nodes.len()
    }

    /// Number of leaves
    pub fn num_leaves(&self) -> usize {
        self.nodes.iter().filter(|n| n.is_leaf()).count()
    }

    /// Maximum depth of the tree
    pub fn max_depth(&self) -> usize {
        self.nodes.iter().map(|n| n.depth).max().unwrap_or(0)
    }

    /// Predict for a single sample using binned features
    ///
    /// # Arguments
    /// * `get_bin` - Function to get bin value for a feature: `|feature_idx| -> u8`
    pub fn predict<F>(&self, get_bin: F) -> f32
    where
        F: Fn(usize) -> u8,
    {
        let mut node_idx = 0;

        loop {
            let node = &self.nodes[node_idx];
            match node.node_type {
                NodeType::Leaf { value } => return value,
                NodeType::Internal {
                    feature_idx,
                    bin_threshold,
                    left_child,
                    right_child,
                    ..
                } => {
                    let bin = get_bin(feature_idx);
                    node_idx = if bin <= bin_threshold {
                        left_child
                    } else {
                        right_child
                    };
                }
            }
        }
    }

    /// Predict for a single row in a dataset
    pub fn predict_row(&self, dataset: &BinnedDataset, row_idx: usize) -> f32 {
        self.predict(|feature_idx| dataset.get_bin(row_idx, feature_idx))
    }

    /// Predict for all rows in a dataset
    pub fn predict_all(&self, dataset: &BinnedDataset) -> Vec<f32> {
        (0..dataset.num_rows())
            .map(|row_idx| self.predict_row(dataset, row_idx))
            .collect()
    }

    /// Predict for a single sample using raw feature values (no binning needed)
    ///
    /// This uses the split_value stored in internal nodes to compare directly
    /// against raw feature values. Much faster than binning + predict.
    ///
    /// # Arguments
    /// * `get_value` - Function to get feature value: `|feature_idx| -> f64`
    #[inline]
    pub fn predict_raw<F>(&self, get_value: F) -> f32
    where
        F: Fn(usize) -> f64,
    {
        let mut node_idx = 0;

        loop {
            let node = &self.nodes[node_idx];
            match node.node_type {
                NodeType::Leaf { value } => return value,
                NodeType::Internal {
                    feature_idx,
                    split_value,
                    left_child,
                    right_child,
                    ..
                } => {
                    let value = get_value(feature_idx);
                    node_idx = if value <= split_value {
                        left_child
                    } else {
                        right_child
                    };
                }
            }
        }
    }

    /// Batch predict using raw feature values: add this tree's contribution
    ///
    /// Similar to predict_batch_add but uses split_value for comparison
    /// instead of bin thresholds. Input is raw feature values, not binned data.
    ///
    /// Uses parallel execution for large datasets (>= 10K rows).
    ///
    /// # Arguments
    /// * `features` - Row-major feature matrix: features[row * num_features + feature]
    /// * `num_features` - Number of features per row
    /// * `predictions` - Mutable slice to accumulate predictions into
    #[inline]
    pub fn predict_batch_add_raw(
        &self,
        features: &[f64],
        num_features: usize,
        predictions: &mut [f32],
    ) {
        let num_rows = predictions.len();
        debug_assert_eq!(features.len(), num_rows * num_features);

        // Parallel threshold - overhead not worth it for small datasets
        const PARALLEL_THRESHOLD: usize = 10_000;

        if num_rows >= PARALLEL_THRESHOLD {
            // Parallel: each row is independent
            predictions
                .par_iter_mut()
                .enumerate()
                .for_each(|(row_idx, pred)| {
                    *pred += self.predict_row_raw_inner(features, num_features, row_idx);
                });
        } else {
            // Sequential for small datasets
            for (row_idx, pred) in predictions.iter_mut().enumerate() {
                *pred += self.predict_row_raw_inner(features, num_features, row_idx);
            }
        }
    }

    /// Inner prediction logic for a single row using raw features
    #[inline]
    fn predict_row_raw_inner(&self, features: &[f64], num_features: usize, row_idx: usize) -> f32 {
        let row_offset = row_idx * num_features;
        let mut node_idx = 0;

        loop {
            let node = &self.nodes[node_idx];
            match node.node_type {
                NodeType::Leaf { value } => {
                    return value;
                }
                NodeType::Internal {
                    feature_idx,
                    split_value,
                    left_child,
                    right_child,
                    ..
                } => {
                    let value = features[row_offset + feature_idx];
                    node_idx = if value <= split_value {
                        left_child
                    } else {
                        right_child
                    };
                }
            }
        }
    }

    /// Batch predict: add this tree's contribution to all predictions
    ///
    /// This is the tree-wise prediction approach: traverse one tree for ALL rows,
    /// then move to the next tree. More cache-friendly than row-wise traversal.
    ///
    /// Uses parallel execution for large datasets (>= 10K rows).
    ///
    /// # Arguments
    /// * `dataset` - The binned dataset
    /// * `predictions` - Mutable slice to accumulate predictions into
    #[inline]
    pub fn predict_batch_add(&self, dataset: &BinnedDataset, predictions: &mut [f32]) {
        let num_rows = predictions.len();
        debug_assert_eq!(num_rows, dataset.num_rows());

        // Parallel threshold - overhead not worth it for small datasets
        const PARALLEL_THRESHOLD: usize = 10_000;

        if num_rows >= PARALLEL_THRESHOLD {
            // Parallel: each row is independent
            predictions
                .par_iter_mut()
                .enumerate()
                .for_each(|(row_idx, pred)| {
                    *pred += self.predict_row_inner(dataset, row_idx);
                });
        } else {
            // Sequential for small datasets
            for (row_idx, pred) in predictions.iter_mut().enumerate() {
                *pred += self.predict_row_inner(dataset, row_idx);
            }
        }
    }

    /// Inner prediction logic for a single row (used by both parallel and sequential paths)
    #[inline]
    fn predict_row_inner(&self, dataset: &BinnedDataset, row_idx: usize) -> f32 {
        let mut node_idx = 0;

        loop {
            let node = &self.nodes[node_idx];
            match node.node_type {
                NodeType::Leaf { value } => {
                    return value;
                }
                NodeType::Internal {
                    feature_idx,
                    bin_threshold,
                    left_child,
                    right_child,
                    ..
                } => {
                    let bin = dataset.get_bin(row_idx, feature_idx);
                    node_idx = if bin <= bin_threshold {
                        left_child
                    } else {
                        right_child
                    };
                }
            }
        }
    }

    /// Batch predict with contiguous feature columns
    ///
    /// Optimized version that accesses feature columns directly for better cache behavior.
    /// For each internal node, we fetch the entire feature column once.
    #[inline]
    pub fn predict_batch_add_columnar(&self, dataset: &BinnedDataset, predictions: &mut [f32]) {
        let num_rows = predictions.len();
        debug_assert_eq!(num_rows, dataset.num_rows());

        // Track which node each row is currently at
        let mut node_indices = vec![0usize; num_rows];

        // Process level by level until all rows reach leaves
        let mut active_count = num_rows;

        while active_count > 0 {
            active_count = 0;

            // Group rows by their current node to batch feature lookups
            for row_idx in 0..num_rows {
                let node_idx = node_indices[row_idx];
                if node_idx == usize::MAX {
                    continue; // Already at leaf
                }

                let node = &self.nodes[node_idx];
                match node.node_type {
                    NodeType::Leaf { value } => {
                        predictions[row_idx] += value;
                        node_indices[row_idx] = usize::MAX; // Mark as done
                    }
                    NodeType::Internal {
                        feature_idx,
                        bin_threshold,
                        left_child,
                        right_child,
                        ..
                    } => {
                        let bin = dataset.get_bin(row_idx, feature_idx);
                        node_indices[row_idx] = if bin <= bin_threshold {
                            left_child
                        } else {
                            right_child
                        };
                        active_count += 1;
                    }
                }
            }
        }
    }

    /// Get all leaf nodes
    pub fn leaves(&self) -> impl Iterator<Item = (usize, &Node)> {
        self.nodes.iter().enumerate().filter(|(_, n)| n.is_leaf())
    }

    /// Get all internal nodes
    pub fn internal_nodes(&self) -> impl Iterator<Item = (usize, &Node)> {
        self.nodes.iter().enumerate().filter(|(_, n)| !n.is_leaf())
    }

    /// Get nodes as slice
    pub fn nodes(&self) -> &[Node] {
        &self.nodes
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tree_creation() {
        let tree = Tree::new(0.5, 100, 10.0, 20.0);

        assert_eq!(tree.num_nodes(), 1);
        assert_eq!(tree.num_leaves(), 1);
        assert!(tree.root().is_leaf());
        assert_eq!(tree.root().leaf_value(), Some(0.5));
    }

    #[test]
    fn test_tree_prediction() {
        // Create a simple tree:
        //        [f0 <= 5]
        //        /        \
        //    leaf=1.0   [f1 <= 10]
        //               /        \
        //           leaf=2.0   leaf=3.0

        let tree = Tree::from_nodes(vec![
            Node::internal(0, 5, 5.0, 1, 2, 0, 100, 0.0, 100.0),
            Node::leaf(1.0, 1, 50, 0.0, 50.0),
            Node::internal(1, 10, 10.0, 3, 4, 1, 50, 0.0, 50.0),
            Node::leaf(2.0, 2, 25, 0.0, 25.0),
            Node::leaf(3.0, 2, 25, 0.0, 25.0),
        ]);

        // Test predictions
        // f0=3 (<=5): go left -> leaf=1.0
        assert_eq!(tree.predict(|f| if f == 0 { 3 } else { 0 }), 1.0);

        // f0=7 (>5): go right, f1=5 (<=10): go left -> leaf=2.0
        assert_eq!(tree.predict(|f| if f == 0 { 7 } else { 5 }), 2.0);

        // f0=7 (>5): go right, f1=15 (>10): go right -> leaf=3.0
        assert_eq!(tree.predict(|f| if f == 0 { 7 } else { 15 }), 3.0);
    }

    #[test]
    fn test_tree_stats() {
        let tree = Tree::from_nodes(vec![
            Node::internal(0, 5, 5.0, 1, 2, 0, 100, 0.0, 100.0),
            Node::leaf(1.0, 1, 50, 0.0, 50.0),
            Node::internal(1, 10, 10.0, 3, 4, 1, 50, 0.0, 50.0),
            Node::leaf(2.0, 2, 25, 0.0, 25.0),
            Node::leaf(3.0, 2, 25, 0.0, 25.0),
        ]);

        assert_eq!(tree.num_nodes(), 5);
        assert_eq!(tree.num_leaves(), 3);
        assert_eq!(tree.max_depth(), 2);
    }
}