ferricml 0.2.1

A lean, pure-Rust toolkit for classical machine learning
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
use super::packed::{BuildNode, ClassTree, NO_CHILD, PackedTree};
use super::parameters::{MaxFeatures, Splitter};
use crate::api::ModelError;
use crate::data::MatrixView;
use crate::numeric::OwnedRng;

/// The limits one tree is grown under.
///
/// This is the whole of what growing a tree needs. It deliberately excludes
/// everything an *ensemble* adds around a tree — the member count, bootstrap
/// resampling, the seed derivation, the thread count — so the grower cannot
/// reach back into a consumer, and so a standalone tree and one forest member
/// are grown by the same code under the same values rather than by two
/// implementations that agree today.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct GrowerConfig {
    pub(crate) max_depth: Option<usize>,
    pub(crate) min_samples_split: usize,
    pub(crate) min_samples_leaf: usize,
    pub(crate) max_features: MaxFeatures,
    pub(crate) splitter: Splitter,
}

/// One node's statistics are weighted totals rather than row counts.
///
/// `weight` is the total row weight reaching a node: the bootstrap replication
/// count of each row multiplied by its sample weight. Without sample weights
/// every term is an integer, and an integer sum accumulated in `f64` is exact
/// below `2^53`, so the unweighted arithmetic is bit-for-bit what the earlier
/// `u64` counter produced.
pub(crate) trait Objective<Y>: Copy + Send + Sync {
    fn value(self, y: &Y) -> f64;
    fn impurity(self, sum: f64, sum_sq: f64, weight: f64) -> f64;
    fn leaf_value(self, sum: f64, weight: f64) -> f32 {
        (sum / weight) as f32
    }
    fn pure(self, sum: f64, sum_sq: f64, weight: f64) -> bool;
}

#[derive(Clone, Copy)]
pub(crate) struct Classification;

impl Objective<u8> for Classification {
    fn value(self, y: &u8) -> f64 {
        f64::from(*y)
    }

    fn impurity(self, positives: f64, _sum_sq: f64, weight: f64) -> f64 {
        let p = positives / weight;
        2.0 * p * (1.0 - p)
    }

    fn pure(self, positives: f64, _sum_sq: f64, weight: f64) -> bool {
        positives == 0.0 || positives == weight
    }
}

#[derive(Clone, Copy)]
pub(crate) struct Regression;

impl Objective<f32> for Regression {
    fn value(self, y: &f32) -> f64 {
        f64::from(*y)
    }

    fn impurity(self, sum: f64, sum_sq: f64, weight: f64) -> f64 {
        // Population variance.  Clamp cancellation noise at zero.
        let mean = sum / weight;
        (sum_sq / weight - mean * mean).max(0.0)
    }

    fn pure(self, sum: f64, sum_sq: f64, weight: f64) -> bool {
        self.impurity(sum, sum_sq, weight) == 0.0
    }
}

/// The per-row training weights and retained rows of an unresampled fit.
///
/// A row of zero weight is not in the training sample at all, so it is left out
/// of the row list entirely rather than carried as a zero — which is what keeps
/// a node from ever dividing by a zero total weight.
///
/// This consumes no randomness. That is the property a one-tree, no-bootstrap
/// forest member and a standalone tree at the same derived seed depend on: both
/// enter the grower with the generator in the same state.
pub(crate) fn unbootstrapped_sample(
    rows: usize,
    sample_weights: Option<&[f32]>,
) -> (Vec<f64>, Vec<usize>) {
    let Some(sample_weights) = sample_weights else {
        return (vec![1.0_f64; rows], (0..rows).collect());
    };
    let mut weights = vec![0.0_f64; rows];
    let mut retained = Vec::with_capacity(rows);
    for row in 0..rows {
        if sample_weights[row] > 0.0 {
            weights[row] = f64::from(sample_weights[row]);
            retained.push(row);
        }
    }
    (weights, retained)
}

/// Grows one scalar-leaf tree over the rows the caller retained.
///
/// `row_weights[row]` is that row's total training weight, and `rows` lists
/// exactly the rows of positive weight. A forest passes a resampled weight
/// vector; a standalone tree passes ones. The generator is borrowed rather than
/// seeded here, because who owns the seed — and how a member's seed is derived
/// from an ensemble's — is the caller's contract, not the grower's.
pub(crate) fn grow_tree<Y, O>(
    data: &MatrixView<'_>,
    targets: &[Y],
    row_weights: &[f64],
    rows: Vec<usize>,
    config: &GrowerConfig,
    objective: O,
    rng: &mut OwnedRng,
) -> Result<PackedTree, ModelError>
where
    O: Objective<Y>,
{
    TreeBuilder {
        data,
        targets,
        row_weights,
        config,
        objective,
        rng,
        nodes: Vec::new(),
    }
    .build_tree(rows)
}

/// Grows one natively multiclass tree.
///
/// `class_of_row` holds each row's column in the sorted class list, so the
/// builder never touches a label value.
pub(crate) fn grow_class_tree(
    data: &MatrixView<'_>,
    class_of_row: &[usize],
    classes: usize,
    row_weights: &[f64],
    rows: Vec<usize>,
    config: &GrowerConfig,
    rng: &mut OwnedRng,
) -> Result<ClassTree, ModelError> {
    ClassTreeBuilder {
        data,
        class_of_row,
        classes,
        row_weights,
        config,
        rng,
        nodes: Vec::new(),
        class_weights: Vec::new(),
        weights: Vec::new(),
    }
    .build_tree(rows)
}

/// Partially shuffles `0..columns` so its first `count` entries are the drawn
/// features, in the generator's order.
///
/// Shared by both builders because the sampling — not the sweep that follows
/// it — is what a fitted tree's reproducibility depends on. It runs once per
/// *node*, which is the crate's hottest fitting path outside the sweep itself,
/// so it is `#[inline]`: written inline this was part of its caller's body, and
/// sharing it must not quietly add a call boundary there. It returns the full
/// permutation rather than truncating, so the caller keeps the drawn count in a
/// register the way it did before.
///
/// The resulting order is also FerricML's cross-column tie-break: candidates
/// are swept in exactly this order and a later candidate must be *strictly*
/// better to displace an earlier one, so among exactly-tied splits the first
/// drawn wins. That is reproducible from data, parameters, and seed alone,
/// which is the property the reference cannot offer — its visit permutation is
/// randomized even when every column is considered, and is not observable
/// through its public API.
#[inline]
fn sample_features(rng: &mut OwnedRng, columns: usize, count: usize) -> Vec<usize> {
    let mut features: Vec<usize> = (0..columns).collect();
    for index in 0..count {
        let other = index + rng.index(features.len() - index);
        features.swap(index, other);
    }
    features
}

/// How many features one node draws. Also per node, also `#[inline]`.
#[inline]
fn resolved_feature_count(max_features: MaxFeatures, columns: usize) -> usize {
    match max_features {
        MaxFeatures::All => columns,
        MaxFeatures::Sqrt => integer_sqrt(columns).max(1),
        MaxFeatures::Count(count) => count,
    }
}

struct TreeBuilder<'a, 'm, Y, O> {
    data: &'a MatrixView<'m>,
    targets: &'a [Y],
    /// Total training weight of each row in this tree's sample.
    row_weights: &'a [f64],
    config: &'a GrowerConfig,
    objective: O,
    rng: &'a mut OwnedRng,
    nodes: Vec<BuildNode>,
}

#[derive(Clone, Copy)]
struct Split {
    feature: usize,
    threshold: f32,
    score: f64,
}

#[derive(Clone, Copy)]
enum Attachment {
    Root,
    Left(u32),
    Right(u32),
}

struct PendingNode {
    rows: Vec<usize>,
    depth: usize,
    attachment: Attachment,
}

impl<Y, O: Objective<Y>> TreeBuilder<'_, '_, Y, O> {
    fn build_tree(mut self, rows: Vec<usize>) -> Result<PackedTree, ModelError> {
        let mut pending = vec![PendingNode {
            rows,
            depth: 0,
            attachment: Attachment::Root,
        }];
        while let Some(task) = pending.pop() {
            let (sum, sum_sq, weight) = self.totals(&task.rows);
            let prediction = self.objective.leaf_value(sum, weight);
            let node_index = self.push_node(BuildNode::leaf(prediction))?;
            match task.attachment {
                Attachment::Root => debug_assert_eq!(node_index, 0),
                Attachment::Left(parent) => self.nodes[parent as usize].left = node_index,
                Attachment::Right(parent) => self.nodes[parent as usize].right = node_index,
            }

            let depth_limited = self
                .config
                .max_depth
                .is_some_and(|max_depth| task.depth >= max_depth);
            if depth_limited
                || weight < self.config.min_samples_split as f64
                || self.objective.pure(sum, sum_sq, weight)
            {
                continue;
            }

            let parent_impurity = self.objective.impurity(sum, sum_sq, weight);
            let Some(split) = self.best_split(&task.rows, sum, sum_sq, weight) else {
                continue;
            };
            // A split must reduce impurity, not merely reshuffle equal values.
            if split.score >= parent_impurity {
                continue;
            }

            let mut left_rows = Vec::with_capacity(task.rows.len());
            let mut right_rows = Vec::with_capacity(task.rows.len());
            for row in task.rows {
                if self.data.row(row).expect("known row")[split.feature] <= split.threshold {
                    left_rows.push(row);
                } else {
                    right_rows.push(row);
                }
            }
            self.nodes[node_index as usize] = BuildNode {
                feature: split.feature as u32,
                left: NO_CHILD,
                right: NO_CHILD,
                payload: split.threshold,
            };
            // Right is pushed first so the left subtree remains contiguous and
            // the final node buffer is deterministic pre-order traversal.
            pending.push(PendingNode {
                rows: right_rows,
                depth: task.depth + 1,
                attachment: Attachment::Right(node_index),
            });
            pending.push(PendingNode {
                rows: left_rows,
                depth: task.depth + 1,
                attachment: Attachment::Left(node_index),
            });
        }
        PackedTree::from_build_nodes(self.nodes, self.data.columns())
    }

    fn push_node(&mut self, node: BuildNode) -> Result<u32, ModelError> {
        let index = u32::try_from(self.nodes.len()).map_err(|_| ModelError::TreeTooLarge)?;
        if index == NO_CHILD {
            return Err(ModelError::TreeTooLarge);
        }
        self.nodes.push(node);
        Ok(index)
    }

    fn totals(&self, rows: &[usize]) -> (f64, f64, f64) {
        let mut sum = 0.0;
        let mut sum_sq = 0.0;
        let mut weight = 0.0;
        for &row in rows {
            let row_weight = self.row_weights[row];
            let value = self.objective.value(&self.targets[row]);
            sum += value * row_weight;
            sum_sq += value * value * row_weight;
            weight += row_weight;
        }
        (sum, sum_sq, weight)
    }

    /// The split this node takes, or `None` when no candidate admits one.
    ///
    /// Candidates are drawn first and identically for both splitters, so how a
    /// tree samples columns does not depend on how it then picks thresholds.
    /// The search over those candidates is the only thing that differs.
    fn best_split(
        &mut self,
        rows: &[usize],
        total_sum: f64,
        total_sum_sq: f64,
        total_weight: f64,
    ) -> Option<Split> {
        let feature_count = resolved_feature_count(self.config.max_features, self.data.columns());
        let drawn = sample_features(self.rng, self.data.columns(), feature_count);
        let features = &drawn[..feature_count];
        match self.config.splitter {
            Splitter::Best => {
                self.best_exhaustive_split(features, rows, total_sum, total_sum_sq, total_weight)
            }
            Splitter::Random => {
                self.best_random_split(features, rows, total_sum, total_sum_sq, total_weight)
            }
        }
    }

    /// Evaluates every boundary between adjacent distinct values, in every
    /// candidate column.
    fn best_exhaustive_split(
        &self,
        features: &[usize],
        rows: &[usize],
        total_sum: f64,
        total_sum_sq: f64,
        total_weight: f64,
    ) -> Option<Split> {
        let mut ordered = Vec::with_capacity(rows.len());
        let mut best: Option<Split> = None;
        for &feature in features {
            ordered.clear();
            ordered.extend_from_slice(rows);
            ordered.sort_unstable_by(|&left, &right| {
                self.data.row(left).expect("known row")[feature]
                    .total_cmp(&self.data.row(right).expect("known row")[feature])
                    .then_with(|| left.cmp(&right))
            });

            let mut left_sum = 0.0;
            let mut left_sum_sq = 0.0;
            let mut left_weight = 0.0;
            // `value` is re-converted once per candidate feature per node, and
            // hoisting it looks free. It is not: precomputing a per-row
            // `{weight, sum, sum_sq}` record was built, proven bit-identical,
            // measured at +2.12% and +0.92%, and rejected. This loop is
            // memory-bound on the scattered `ordered[]` gather, so trading two
            // 8/4-byte reads for one 24-byte read loses more than the removed
            // conversion and multiplies save. See
            // dev-docs/designs/forest-sweep-measurements.md before retrying it,
            // and note the same file's rule against extracting anything from
            // this loop body.
            for boundary in 0..ordered.len().saturating_sub(1) {
                let row = ordered[boundary];
                let row_weight = self.row_weights[row];
                let value = self.objective.value(&self.targets[row]);
                left_sum += value * row_weight;
                left_sum_sq += value * value * row_weight;
                left_weight += row_weight;

                let a = self.data.row(row).expect("known row")[feature];
                let b = self.data.row(ordered[boundary + 1]).expect("known row")[feature];
                if a == b {
                    continue;
                }
                let right_weight = total_weight - left_weight;
                if left_weight < self.config.min_samples_leaf as f64
                    || right_weight < self.config.min_samples_leaf as f64
                {
                    continue;
                }
                let right_sum = total_sum - left_sum;
                let right_sum_sq = total_sum_sq - left_sum_sq;
                let left_impurity = self.objective.impurity(left_sum, left_sum_sq, left_weight);
                let right_impurity = self
                    .objective
                    .impurity(right_sum, right_sum_sq, right_weight);
                let score =
                    (left_weight * left_impurity + right_weight * right_impurity) / total_weight;
                if best.as_ref().is_none_or(|current| score < current.score) {
                    best = Some(Split {
                        feature,
                        threshold: split_threshold(a, b),
                        score,
                    });
                }
            }
        }
        best
    }

    /// Scores one uniform draw per candidate column and keeps the best.
    ///
    /// No sort is needed: a single threshold is known before the rows are
    /// visited, so one pass accumulates the left side directly. Rows are
    /// visited in `rows` order, which is fixed, so the accumulation is
    /// reproducible.
    fn best_random_split(
        &mut self,
        features: &[usize],
        rows: &[usize],
        total_sum: f64,
        total_sum_sq: f64,
        total_weight: f64,
    ) -> Option<Split> {
        let mut best: Option<Split> = None;
        for &feature in features {
            let (min, max) = column_range(self.data, rows, feature);
            let Some(threshold) = random_threshold(self.rng, min, max) else {
                continue;
            };
            let mut left_sum = 0.0;
            let mut left_sum_sq = 0.0;
            let mut left_weight = 0.0;
            for &row in rows {
                if self.data.row(row).expect("known row")[feature] <= threshold {
                    let row_weight = self.row_weights[row];
                    let value = self.objective.value(&self.targets[row]);
                    left_sum += value * row_weight;
                    left_sum_sq += value * value * row_weight;
                    left_weight += row_weight;
                }
            }
            let right_weight = total_weight - left_weight;
            // An inadmissible draw is discarded, never redrawn: redrawing until
            // a leaf-bound-satisfying threshold appeared would silently turn a
            // uniform draw into a conditional one, and would make a node whose
            // admissible region is tiny cost unbounded work.
            if left_weight < self.config.min_samples_leaf as f64
                || right_weight < self.config.min_samples_leaf as f64
            {
                continue;
            }
            let right_sum = total_sum - left_sum;
            let right_sum_sq = total_sum_sq - left_sum_sq;
            let score = (left_weight * self.objective.impurity(left_sum, left_sum_sq, left_weight)
                + right_weight
                    * self
                        .objective
                        .impurity(right_sum, right_sum_sq, right_weight))
                / total_weight;
            if best.as_ref().is_none_or(|current| score < current.score) {
                best = Some(Split {
                    feature,
                    threshold,
                    score,
                });
            }
        }
        best
    }
}

/// Builds one natively multiclass tree.
///
/// This is deliberately a second builder rather than a generalization of
/// [`TreeBuilder`]. Making the scalar builder generic over its node statistics
/// would move `left_sum`/`left_sum_sq` out of locals and into a slice inside
/// the crate's hottest fitting loop, and this sprint holds no benchmark lock to
/// prove that costs nothing. Everything outside that loop — feature sampling,
/// threshold selection, row partitioning, bootstrap sampling, tree ordering —
/// is shared. Unifying the sweep itself is a measured change, not a tidy-up.
struct ClassTreeBuilder<'a, 'm> {
    data: &'a MatrixView<'m>,
    /// Each row's column in the sorted class list.
    class_of_row: &'a [usize],
    classes: usize,
    /// Total training weight of each row in this tree's sample.
    row_weights: &'a [f64],
    config: &'a GrowerConfig,
    rng: &'a mut OwnedRng,
    nodes: Vec<BuildNode>,
    /// `classes` weighted counts per build node, parallel to `nodes`.
    class_weights: Vec<f64>,
    /// Total weight per build node, parallel to `nodes`.
    weights: Vec<f64>,
}

impl ClassTreeBuilder<'_, '_> {
    fn build_tree(mut self, rows: Vec<usize>) -> Result<ClassTree, ModelError> {
        let classes = self.classes;
        let mut totals = vec![0.0_f64; classes];
        let mut left = vec![0.0_f64; classes];
        let mut right = vec![0.0_f64; classes];
        let mut pending = vec![PendingNode {
            rows,
            depth: 0,
            attachment: Attachment::Root,
        }];
        while let Some(task) = pending.pop() {
            let weight = self.totals(&task.rows, &mut totals);
            // A leaf's stored value is derived at packing time from these
            // retained statistics, so the payload slot stays free for the
            // threshold this node may still gain.
            let node_index = self.push_node(BuildNode::leaf(0.0), &totals, weight)?;
            match task.attachment {
                Attachment::Root => debug_assert_eq!(node_index, 0),
                Attachment::Left(parent) => self.nodes[parent as usize].left = node_index,
                Attachment::Right(parent) => self.nodes[parent as usize].right = node_index,
            }

            let depth_limited = self
                .config
                .max_depth
                .is_some_and(|max_depth| task.depth >= max_depth);
            if depth_limited
                || weight < self.config.min_samples_split as f64
                || totals.contains(&weight)
            {
                continue;
            }

            let parent_impurity = gini(&totals, weight);
            let Some(split) = self.best_split(&task.rows, &totals, weight, &mut left, &mut right)
            else {
                continue;
            };
            if split.score >= parent_impurity {
                continue;
            }

            let mut left_rows = Vec::with_capacity(task.rows.len());
            let mut right_rows = Vec::with_capacity(task.rows.len());
            for row in task.rows {
                if self.data.row(row).expect("known row")[split.feature] <= split.threshold {
                    left_rows.push(row);
                } else {
                    right_rows.push(row);
                }
            }
            self.nodes[node_index as usize] = BuildNode {
                feature: split.feature as u32,
                left: NO_CHILD,
                right: NO_CHILD,
                payload: split.threshold,
            };
            pending.push(PendingNode {
                rows: right_rows,
                depth: task.depth + 1,
                attachment: Attachment::Right(node_index),
            });
            pending.push(PendingNode {
                rows: left_rows,
                depth: task.depth + 1,
                attachment: Attachment::Left(node_index),
            });
        }
        ClassTree::from_build_nodes(
            self.nodes,
            &self.class_weights,
            &self.weights,
            classes,
            self.data.columns(),
        )
    }

    fn push_node(
        &mut self,
        node: BuildNode,
        class_weights: &[f64],
        weight: f64,
    ) -> Result<u32, ModelError> {
        let index = u32::try_from(self.nodes.len()).map_err(|_| ModelError::TreeTooLarge)?;
        if index == NO_CHILD {
            return Err(ModelError::TreeTooLarge);
        }
        self.nodes.push(node);
        self.class_weights.extend_from_slice(class_weights);
        self.weights.push(weight);
        Ok(index)
    }

    fn totals(&self, rows: &[usize], class_weights: &mut [f64]) -> f64 {
        class_weights.fill(0.0);
        let mut weight = 0.0;
        for &row in rows {
            let row_weight = self.row_weights[row];
            class_weights[self.class_of_row[row]] += row_weight;
            weight += row_weight;
        }
        weight
    }

    fn best_split(
        &mut self,
        rows: &[usize],
        totals: &[f64],
        total_weight: f64,
        left: &mut [f64],
        right: &mut [f64],
    ) -> Option<Split> {
        let feature_count = resolved_feature_count(self.config.max_features, self.data.columns());
        let drawn = sample_features(self.rng, self.data.columns(), feature_count);
        let features = &drawn[..feature_count];
        match self.config.splitter {
            Splitter::Best => {
                self.best_exhaustive_split(features, rows, totals, total_weight, left, right)
            }
            Splitter::Random => {
                self.best_random_split(features, rows, totals, total_weight, left, right)
            }
        }
    }

    fn best_exhaustive_split(
        &self,
        features: &[usize],
        rows: &[usize],
        totals: &[f64],
        total_weight: f64,
        left: &mut [f64],
        right: &mut [f64],
    ) -> Option<Split> {
        let mut ordered = Vec::with_capacity(rows.len());
        let mut best: Option<Split> = None;
        for &feature in features {
            ordered.clear();
            ordered.extend_from_slice(rows);
            ordered.sort_unstable_by(|&left, &right| {
                self.data.row(left).expect("known row")[feature]
                    .total_cmp(&self.data.row(right).expect("known row")[feature])
                    .then_with(|| left.cmp(&right))
            });

            left.fill(0.0);
            let mut left_weight = 0.0;
            for boundary in 0..ordered.len().saturating_sub(1) {
                let row = ordered[boundary];
                let row_weight = self.row_weights[row];
                left[self.class_of_row[row]] += row_weight;
                left_weight += row_weight;

                let a = self.data.row(row).expect("known row")[feature];
                let b = self.data.row(ordered[boundary + 1]).expect("known row")[feature];
                if a == b {
                    continue;
                }
                let right_weight = total_weight - left_weight;
                if left_weight < self.config.min_samples_leaf as f64
                    || right_weight < self.config.min_samples_leaf as f64
                {
                    continue;
                }
                for (slot, (&total, &left)) in right.iter_mut().zip(totals.iter().zip(left.iter()))
                {
                    *slot = total - left;
                }
                let score = (left_weight * gini(left, left_weight)
                    + right_weight * gini(right, right_weight))
                    / total_weight;
                if best.as_ref().is_none_or(|current| score < current.score) {
                    best = Some(Split {
                        feature,
                        threshold: split_threshold(a, b),
                        score,
                    });
                }
            }
        }
        best
    }

    /// One uniform draw per candidate column, scored on multiclass Gini.
    fn best_random_split(
        &mut self,
        features: &[usize],
        rows: &[usize],
        totals: &[f64],
        total_weight: f64,
        left: &mut [f64],
        right: &mut [f64],
    ) -> Option<Split> {
        let mut best: Option<Split> = None;
        for &feature in features {
            let (min, max) = column_range(self.data, rows, feature);
            let Some(threshold) = random_threshold(self.rng, min, max) else {
                continue;
            };
            left.fill(0.0);
            let mut left_weight = 0.0;
            for &row in rows {
                if self.data.row(row).expect("known row")[feature] <= threshold {
                    let row_weight = self.row_weights[row];
                    left[self.class_of_row[row]] += row_weight;
                    left_weight += row_weight;
                }
            }
            let right_weight = total_weight - left_weight;
            // Discarded rather than redrawn, exactly as in the scalar builder.
            if left_weight < self.config.min_samples_leaf as f64
                || right_weight < self.config.min_samples_leaf as f64
            {
                continue;
            }
            for (slot, (&total, &left)) in right.iter_mut().zip(totals.iter().zip(left.iter())) {
                *slot = total - left;
            }
            let score = (left_weight * gini(left, left_weight)
                + right_weight * gini(right, right_weight))
                / total_weight;
            if best.as_ref().is_none_or(|current| score < current.score) {
                best = Some(Split {
                    feature,
                    threshold,
                    score,
                });
            }
        }
        best
    }
}

/// The range one column spans across the rows reaching a node.
///
/// The bound is the *node's* range, not the column's range over the whole
/// training set: a deep node sees a narrow slice, and drawing from the global
/// range there would put almost every draw outside the rows present.
fn column_range(data: &MatrixView<'_>, rows: &[usize], feature: usize) -> (f32, f32) {
    let mut min = f32::INFINITY;
    let mut max = f32::NEG_INFINITY;
    for &row in rows {
        let value = data.row(row).expect("known row")[feature];
        min = min.min(value);
        max = max.max(value);
    }
    (min, max)
}

/// One uniform threshold inside `[min, max)`, or `None` when the column cannot
/// yield a partition.
///
/// A column that is constant within the node has nothing to draw from and
/// consumes no random value — the interval is empty, not merely unlucky. That
/// keeps the generator's stream independent of which columns happen to be
/// constant in a node. Every other column consumes exactly one draw, whether
/// or not the result survives the leaf bound the caller applies next.
///
/// Returning inside `[min, max)` is what makes the partition genuine: at least
/// one row holds `min` and goes left, and at least one holds `max` and goes
/// right, so neither side is empty. The guard is re-checked after narrowing to
/// `f32`, because the draw is computed in `f64` and the packed layout stores an
/// `f32` threshold — rounding could otherwise land it on the upper endpoint and
/// produce an empty partition.
fn random_threshold(rng: &mut OwnedRng, min: f32, max: f32) -> Option<f32> {
    if min >= max {
        return None;
    }
    let span = f64::from(max) - f64::from(min);
    let threshold = (f64::from(min) + rng.unit_f64() * span) as f32;
    (threshold >= min && threshold < max).then_some(threshold)
}

/// Gini impurity of one node's weighted class counts.
///
/// `1 - Σ pₖ²` over any number of classes. At two classes it is exactly the
/// `2p(1-p)` the binary objective above uses, so the two criteria agree where
/// they overlap instead of being two different notions of impurity.
fn gini(class_weights: &[f64], weight: f64) -> f64 {
    let mut squares = 0.0_f64;
    for &count in class_weights {
        let proportion = count / weight;
        squares += proportion * proportion;
    }
    1.0 - squares
}

/// The threshold separating two adjacent distinct values.
///
/// Within a column, candidate boundaries are swept in ascending order and a
/// later one must be strictly better to displace an earlier one, so exactly
/// tied thresholds resolve to the lowest — which is what the reference does
/// too.
fn split_threshold(a: f32, b: f32) -> f32 {
    let midpoint = a + (b - a) * 0.5;
    if midpoint.is_finite() && midpoint >= a && midpoint < b {
        midpoint
    } else {
        // `a` itself exactly represents the desired `<= a` partition, including
        // adjacent floats and opposite-sign values whose subtraction overflows.
        a
    }
}

fn integer_sqrt(value: usize) -> usize {
    // Floating point is only an initial estimate; the corrections make this
    // exact even for usize values beyond f64's integer precision.
    let mut root = (value as f64).sqrt() as usize;
    while root.checked_add(1).is_some_and(|next| next <= value / next) {
        root += 1;
    }
    while root != 0 && root > value / root {
        root -= 1;
    }
    root
}

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

    /// The draw's own contract, stated where the draw is: strictly inside
    /// `[min, max)`, so at least one row goes each way and the partition is
    /// genuine.
    #[test]
    fn a_drawn_threshold_lands_strictly_inside_the_node_range() {
        let mut rng = OwnedRng::new(4);
        for (min, max) in [
            (0.0_f32, 1000.0_f32),
            (-3.5, 2.25),
            (1e-6, 1.05e-6),
            (-1e30, 1e30),
        ] {
            for _ in 0..5_000 {
                let threshold = random_threshold(&mut rng, min, max).expect("a spanned column");
                assert!(
                    threshold >= min && threshold < max,
                    "draw {threshold} escaped [{min}, {max})"
                );
            }
        }
    }

    /// A column that is constant inside the node consumes **no** draw.
    ///
    /// This is what keeps the generator's stream independent of which columns
    /// happen to be constant in a node: were the empty interval to burn a
    /// value, a tree's shape would depend on the data through the RNG as well
    /// as through the impurity, and two nodes with the same candidate set would
    /// diverge for a reason nothing records.
    #[test]
    fn a_constant_column_consumes_no_draw() {
        let mut rng = OwnedRng::new(21);
        assert_eq!(random_threshold(&mut rng, 2.5, 2.5), None);
        assert_eq!(random_threshold(&mut rng, 2.5, 1.0), None);
        let mut untouched = OwnedRng::new(21);
        assert_eq!(rng.next_u64(), untouched.next_u64());

        // A column that does span consumes exactly one, which is the other half
        // of the same contract.
        let mut spent = OwnedRng::new(21);
        let _ = random_threshold(&mut spent, 0.0, 1.0);
        let mut stepped = OwnedRng::new(21);
        let _ = stepped.next_u64();
        assert_eq!(spent.next_u64(), stepped.next_u64());
    }

    /// The `f32`-narrowing re-check, which is what makes the split genuine.
    ///
    /// The draw is uniform in `f64` and cannot reach its upper endpoint, but
    /// the packed layout stores an `f32` threshold. Between two adjacent `f32`
    /// values roughly half of every admissible `f64` rounds *onto* the upper
    /// endpoint, where `value <= threshold` would send every row left and leave
    /// the right child empty. Those draws are rejected rather than nudged.
    #[test]
    fn a_draw_that_narrows_onto_the_upper_endpoint_is_rejected_rather_than_nudged() {
        let min = 1.0_f32;
        let max = f32::from_bits(min.to_bits() + 1);
        let mut rng = OwnedRng::new(5);
        let mut kept = 0;
        let mut rejected = 0;
        for _ in 0..10_000 {
            match random_threshold(&mut rng, min, max) {
                Some(threshold) => {
                    assert_eq!(
                        threshold, min,
                        "the only representable interior value is min"
                    );
                    kept += 1;
                }
                None => rejected += 1,
            }
        }
        assert!(
            kept > 1_000 && rejected > 1_000,
            "the narrowing guard did not fire on both sides: {kept} kept, {rejected} rejected"
        );
    }

    /// The node's own range, not the column's range over the whole matrix.
    #[test]
    fn the_drawn_range_is_the_one_the_nodes_rows_span() {
        let data = crate::data::DenseMatrix::new(vec![0.0, 5.0, 1.0, 6.0, 2.0, 7.0], 3, 2).unwrap();
        let view = data.as_view();
        assert_eq!(column_range(&view, &[0, 1, 2], 0), (0.0, 2.0));
        assert_eq!(column_range(&view, &[1, 2], 0), (1.0, 2.0));
        assert_eq!(column_range(&view, &[0, 2], 1), (5.0, 7.0));
        assert_eq!(column_range(&view, &[1], 1), (6.0, 6.0));
    }
}