rinnd 0.4.1__tar.gz → 0.4.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {rinnd-0.4.1 → rinnd-0.4.4}/PKG-INFO +1 -1
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd/src/lib.rs +7 -8
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/index.rs +6 -4
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/nndescent/mod.rs +66 -14
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/tree/breadth_first.rs +71 -13
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/tree/hybrid_forest.rs +204 -52
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/tree/mod.rs +1 -1
- {rinnd-0.4.1 → rinnd-0.4.4}/pyproject.toml +1 -1
- {rinnd-0.4.1 → rinnd-0.4.4}/Cargo.lock +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/Cargo.toml +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd/Cargo.toml +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/Cargo.toml +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/benches/distance.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/benches/heap.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/examples/graph_bench.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/distance/alternatives.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/distance/angular.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/distance/binary.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/distance/cosine.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/distance/euclidean.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/distance/hellinger.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/distance/inner_product.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/distance/minkowski.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/distance/mod.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/distance/quantized.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/distance/tile.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/distance/traits.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/graph/mod.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/graph/neighbor_graph.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/graph/search_graph.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/heap/candidate_heap.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/heap/mod.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/heap/neighbor_heap.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/lib.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/nndescent/candidates.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/nndescent/update.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/rng.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/search/greedy.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/search/mod.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/tree/builder.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/tree/flat_tree.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-core/src/visited.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-simd/Cargo.toml +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-simd/benches/simd_distance.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-simd/src/avx2.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-simd/src/avx512.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-simd/src/detect.rs +0 -0
- {rinnd-0.4.1 → rinnd-0.4.4}/crates/rinnd-simd/src/lib.rs +0 -0
|
@@ -881,15 +881,8 @@ impl PyNNDescent {
|
|
|
881
881
|
}
|
|
882
882
|
|
|
883
883
|
let breadth_first_batch_width = match tree_build_strategy {
|
|
884
|
-
"auto"
|
|
885
|
-
"auto" => None,
|
|
884
|
+
"auto" | "breadth_first" => Some(tree_batch_width),
|
|
886
885
|
"depth_first" => None,
|
|
887
|
-
"breadth_first" if !graph_only => {
|
|
888
|
-
return Err(PyValueError::new_err(
|
|
889
|
-
"tree_build_strategy='breadth_first' currently requires graph_only=True",
|
|
890
|
-
));
|
|
891
|
-
}
|
|
892
|
-
"breadth_first" => Some(tree_batch_width),
|
|
893
886
|
other => {
|
|
894
887
|
return Err(PyValueError::new_err(format!(
|
|
895
888
|
"Unknown tree_build_strategy: {other}; expected 'auto', 'depth_first', or 'breadth_first'"
|
|
@@ -997,6 +990,7 @@ impl PyNNDescent {
|
|
|
997
990
|
diversify_prob,
|
|
998
991
|
pruning_degree_multiplier,
|
|
999
992
|
verbose,
|
|
993
|
+
breadth_first_batch_width,
|
|
1000
994
|
)
|
|
1001
995
|
})?;
|
|
1002
996
|
|
|
@@ -1694,6 +1688,7 @@ impl PyNNDescent {
|
|
|
1694
1688
|
diversify_prob: f32,
|
|
1695
1689
|
pruning_degree_multiplier: f32,
|
|
1696
1690
|
verbose: bool,
|
|
1691
|
+
breadth_first_batch_width: Option<usize>,
|
|
1697
1692
|
) -> PyResult<Box<dyn AnyIndex>> {
|
|
1698
1693
|
// Compute default n_trees matching PyNNDescent: max(3, min(12, round(2*log10(n))))
|
|
1699
1694
|
let effective_n_trees = n_trees.unwrap_or_else(|| {
|
|
@@ -1722,6 +1717,10 @@ impl PyNNDescent {
|
|
|
1722
1717
|
if let Some(ni) = n_iters {
|
|
1723
1718
|
builder = builder.n_iters(ni);
|
|
1724
1719
|
}
|
|
1720
|
+
builder = match breadth_first_batch_width {
|
|
1721
|
+
Some(width) => builder.breadth_first_tree_batch_width(width),
|
|
1722
|
+
None => builder.depth_first_tree_build(),
|
|
1723
|
+
};
|
|
1725
1724
|
// Dispatch to the correct concrete distance type for each metric.
|
|
1726
1725
|
// Metrics with fast alternatives use proxy distances + correction.
|
|
1727
1726
|
// Others use the direct distance function.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
use crate::distance::{Cosine, Distance, Euclidean, InnerProduct, Metric, SquaredEuclidean};
|
|
4
4
|
use crate::graph::{NeighborGraph, SearchGraph};
|
|
5
|
-
use crate::nndescent::{
|
|
5
|
+
use crate::nndescent::{nn_descent_graph, nn_descent_retained, NNDescentParams, NNDescentStats};
|
|
6
6
|
use crate::rng::FastRng;
|
|
7
7
|
use crate::search::{
|
|
8
8
|
greedy_search_indices_with_workspace_initialized,
|
|
@@ -636,7 +636,7 @@ impl<'a> NNDescentBuilder<'a> {
|
|
|
636
636
|
self
|
|
637
637
|
}
|
|
638
638
|
|
|
639
|
-
///
|
|
639
|
+
/// Build the forest breadth first (hybrid builder), `width` trees per margin pass.
|
|
640
640
|
pub fn breadth_first_tree_batch_width(mut self, width: usize) -> Self {
|
|
641
641
|
assert!(
|
|
642
642
|
(1..=8).contains(&width),
|
|
@@ -646,7 +646,7 @@ impl<'a> NNDescentBuilder<'a> {
|
|
|
646
646
|
self
|
|
647
647
|
}
|
|
648
648
|
|
|
649
|
-
/// Use depth-first forest construction
|
|
649
|
+
/// Use the legacy depth-first forest construction.
|
|
650
650
|
pub fn depth_first_tree_build(mut self) -> Self {
|
|
651
651
|
self.breadth_first_batch_width = None;
|
|
652
652
|
self
|
|
@@ -868,13 +868,15 @@ impl<'a> NNDescentBuilder<'a> {
|
|
|
868
868
|
let mut rng = FastRng::new(self.random_seed);
|
|
869
869
|
|
|
870
870
|
// Run NN-descent
|
|
871
|
-
let (mut neighbor_heap, forest, nn_descent_stats) =
|
|
871
|
+
let (mut neighbor_heap, forest, nn_descent_stats) = nn_descent_retained(
|
|
872
872
|
&self.data,
|
|
873
873
|
self.n_points,
|
|
874
874
|
self.dim,
|
|
875
875
|
&distance,
|
|
876
876
|
¶ms,
|
|
877
877
|
&mut rng,
|
|
878
|
+
self.breadth_first_batch_width,
|
|
879
|
+
self.n_search_trees,
|
|
878
880
|
);
|
|
879
881
|
|
|
880
882
|
// Sort the heap so neighbors are in ascending distance order
|
|
@@ -16,7 +16,7 @@ use crate::tree::{build_rp_forest, build_rp_leaf_forest, rptree_leaf_array, Flat
|
|
|
16
16
|
#[cfg(not(feature = "hybrid-forest"))]
|
|
17
17
|
use crate::tree::build_breadth_first_leaf_forest;
|
|
18
18
|
#[cfg(feature = "hybrid-forest")]
|
|
19
|
-
use crate::tree::{build_hybrid_leaf_forest, local_points_for};
|
|
19
|
+
use crate::tree::{build_hybrid_forest, build_hybrid_leaf_forest, local_points_for};
|
|
20
20
|
|
|
21
21
|
use rayon::prelude::*;
|
|
22
22
|
|
|
@@ -109,7 +109,24 @@ pub fn nn_descent<D: Distance<f32> + Sync>(
|
|
|
109
109
|
params: &NNDescentParams,
|
|
110
110
|
rng: &mut FastRng,
|
|
111
111
|
) -> (NeighborHeap, Vec<FlatTree>, NNDescentStats) {
|
|
112
|
-
nn_descent_impl(data, n_points, dim, distance, params, rng, true, None)
|
|
112
|
+
nn_descent_impl(data, n_points, dim, distance, params, rng, true, None, params.n_trees)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/// Like [`nn_descent`], but returns only the first `n_retained` trees. With a batch
|
|
116
|
+
/// width, the forest is built by the hybrid builder, so the graph matches
|
|
117
|
+
/// `nn_descent_graph` with the same width.
|
|
118
|
+
#[allow(clippy::too_many_arguments)]
|
|
119
|
+
pub(crate) fn nn_descent_retained<D: Distance<f32> + Sync>(
|
|
120
|
+
data: &[f32],
|
|
121
|
+
n_points: usize,
|
|
122
|
+
dim: usize,
|
|
123
|
+
distance: &D,
|
|
124
|
+
params: &NNDescentParams,
|
|
125
|
+
rng: &mut FastRng,
|
|
126
|
+
breadth_first_batch_width: Option<usize>,
|
|
127
|
+
n_retained: usize,
|
|
128
|
+
) -> (NeighborHeap, Vec<FlatTree>, NNDescentStats) {
|
|
129
|
+
nn_descent_impl(data, n_points, dim, distance, params, rng, true, breadth_first_batch_width, n_retained)
|
|
113
130
|
}
|
|
114
131
|
|
|
115
132
|
pub(crate) fn nn_descent_graph<D: Distance<f32> + Sync>(
|
|
@@ -130,9 +147,35 @@ pub(crate) fn nn_descent_graph<D: Distance<f32> + Sync>(
|
|
|
130
147
|
rng,
|
|
131
148
|
false,
|
|
132
149
|
breadth_first_batch_width,
|
|
150
|
+
0,
|
|
133
151
|
)
|
|
134
152
|
}
|
|
135
153
|
|
|
154
|
+
/// Depth-first forest; leaves come from every tree, only the first `n_retained` are kept.
|
|
155
|
+
fn build_retained_rp_forest(
|
|
156
|
+
data: &[f32],
|
|
157
|
+
n_points: usize,
|
|
158
|
+
dim: usize,
|
|
159
|
+
params: &NNDescentParams,
|
|
160
|
+
rng: &mut FastRng,
|
|
161
|
+
n_retained: usize,
|
|
162
|
+
) -> (Vec<FlatTree>, Vec<Vec<i32>>) {
|
|
163
|
+
let mut forest = build_rp_forest(
|
|
164
|
+
data,
|
|
165
|
+
n_points,
|
|
166
|
+
dim,
|
|
167
|
+
params.n_trees,
|
|
168
|
+
params.leaf_size,
|
|
169
|
+
rng,
|
|
170
|
+
params.angular,
|
|
171
|
+
params.max_depth,
|
|
172
|
+
);
|
|
173
|
+
let leaf_array = rptree_leaf_array(&forest);
|
|
174
|
+
forest.truncate(n_retained);
|
|
175
|
+
(forest, leaf_array)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
#[allow(clippy::too_many_arguments)]
|
|
136
179
|
fn nn_descent_impl<D: Distance<f32> + Sync>(
|
|
137
180
|
data: &[f32],
|
|
138
181
|
n_points: usize,
|
|
@@ -142,6 +185,7 @@ fn nn_descent_impl<D: Distance<f32> + Sync>(
|
|
|
142
185
|
rng: &mut FastRng,
|
|
143
186
|
retain_trees: bool,
|
|
144
187
|
breadth_first_batch_width: Option<usize>,
|
|
188
|
+
n_retained: usize,
|
|
145
189
|
) -> (NeighborHeap, Vec<FlatTree>, NNDescentStats) {
|
|
146
190
|
use std::time::Instant;
|
|
147
191
|
|
|
@@ -154,18 +198,26 @@ fn nn_descent_impl<D: Distance<f32> + Sync>(
|
|
|
154
198
|
}
|
|
155
199
|
|
|
156
200
|
let (forest, leaf_array) = if retain_trees {
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
201
|
+
#[cfg(feature = "hybrid-forest")]
|
|
202
|
+
if let Some(batch_width) = breadth_first_batch_width {
|
|
203
|
+
build_hybrid_forest(
|
|
204
|
+
data,
|
|
205
|
+
n_points,
|
|
206
|
+
dim,
|
|
207
|
+
params.n_trees,
|
|
208
|
+
params.leaf_size,
|
|
209
|
+
rng,
|
|
210
|
+
params.angular,
|
|
211
|
+
params.max_depth,
|
|
212
|
+
batch_width,
|
|
213
|
+
local_points_for(dim),
|
|
214
|
+
n_retained,
|
|
215
|
+
)
|
|
216
|
+
} else {
|
|
217
|
+
build_retained_rp_forest(data, n_points, dim, params, rng, n_retained)
|
|
218
|
+
}
|
|
219
|
+
#[cfg(not(feature = "hybrid-forest"))]
|
|
220
|
+
build_retained_rp_forest(data, n_points, dim, params, rng, n_retained)
|
|
169
221
|
} else if let Some(batch_width) = breadth_first_batch_width {
|
|
170
222
|
#[cfg(feature = "hybrid-forest")]
|
|
171
223
|
let leaves = build_hybrid_leaf_forest(
|
|
@@ -19,6 +19,8 @@ struct FrontierNode {
|
|
|
19
19
|
pub(super) struct Split {
|
|
20
20
|
pub(super) hyperplane: Vec<f32>,
|
|
21
21
|
pub(super) offset: f32,
|
|
22
|
+
/// Seed for breaking margin ties (the seed that produced this split).
|
|
23
|
+
pub(super) tie_seed: u64,
|
|
22
24
|
}
|
|
23
25
|
|
|
24
26
|
struct TreeState {
|
|
@@ -60,20 +62,20 @@ impl TreeState {
|
|
|
60
62
|
if node.end - node.start <= leaf_size || node.depth >= max_depth {
|
|
61
63
|
None
|
|
62
64
|
} else {
|
|
63
|
-
|
|
65
|
+
Some(choose_split(
|
|
64
66
|
data,
|
|
65
67
|
dim,
|
|
66
68
|
&self.permutation[node.start..node.end],
|
|
67
69
|
node.seed,
|
|
68
70
|
angular,
|
|
69
|
-
)
|
|
71
|
+
))
|
|
70
72
|
}
|
|
71
73
|
})
|
|
72
74
|
.collect();
|
|
73
75
|
self.splits.iter().any(Option::is_some)
|
|
74
76
|
}
|
|
75
77
|
|
|
76
|
-
fn finish_level(&mut self, tree_slot: usize, batch_width: usize, sides: &[u8]) {
|
|
78
|
+
fn finish_level(&mut self, data: &[f32], dim: usize, angular: bool, tree_slot: usize, batch_width: usize, sides: &[u8]) {
|
|
77
79
|
let mut next_frontier = Vec::with_capacity(self.frontier.len() * 2);
|
|
78
80
|
for (node_index, node) in self.frontier.iter().copied().enumerate() {
|
|
79
81
|
if self.splits[node_index].is_none() {
|
|
@@ -98,12 +100,8 @@ impl TreeState {
|
|
|
98
100
|
}
|
|
99
101
|
|
|
100
102
|
if left == node.start || left == node.end {
|
|
101
|
-
self.
|
|
102
|
-
|
|
103
|
-
for &point in &self.permutation[node.start..node.end] {
|
|
104
|
-
self.assignments[point as usize] = NO_NODE;
|
|
105
|
-
}
|
|
106
|
-
continue;
|
|
103
|
+
let (_, offset) = repair_split(data, dim, &mut self.permutation[node.start..node.end], |_, _| {}, node.seed, angular);
|
|
104
|
+
left = node.start + offset;
|
|
107
105
|
}
|
|
108
106
|
|
|
109
107
|
let left_index = next_frontier.len();
|
|
@@ -203,7 +201,7 @@ pub(crate) fn build_breadth_first_leaf_forest(
|
|
|
203
201
|
if let Some(split) = &tree.splits[node_index] {
|
|
204
202
|
let margin = margins[tree_slot] + split.offset;
|
|
205
203
|
point_sides[tree_slot] = if margin.abs() < 1e-8 {
|
|
206
|
-
tie_side(
|
|
204
|
+
tie_side(split.tie_seed, point_index)
|
|
207
205
|
} else {
|
|
208
206
|
(margin >= 0.0) as u8
|
|
209
207
|
};
|
|
@@ -214,7 +212,7 @@ pub(crate) fn build_breadth_first_leaf_forest(
|
|
|
214
212
|
trees
|
|
215
213
|
.par_iter_mut()
|
|
216
214
|
.enumerate()
|
|
217
|
-
.for_each(|(tree_slot, tree)| tree.finish_level(tree_slot, batch_width, &sides));
|
|
215
|
+
.for_each(|(tree_slot, tree)| tree.finish_level(data, dim, angular, tree_slot, batch_width, &sides));
|
|
218
216
|
}
|
|
219
217
|
|
|
220
218
|
for tree in trees {
|
|
@@ -292,6 +290,63 @@ unsafe fn batched_dot_products_avx2(
|
|
|
292
290
|
sums
|
|
293
291
|
}
|
|
294
292
|
|
|
293
|
+
const SPLIT_ATTEMPTS: u64 = 8;
|
|
294
|
+
|
|
295
|
+
#[inline]
|
|
296
|
+
fn attempt_seed(seed: u64, attempt: u64) -> u64 {
|
|
297
|
+
if attempt == 0 { seed } else { mix64(seed ^ attempt.wrapping_mul(0x9e3779b97f4a7c15)) }
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/// First valid split among `SPLIT_ATTEMPTS` seeds; otherwise a zero hyperplane,
|
|
301
|
+
/// which sends every point to a random side by the tie rule.
|
|
302
|
+
pub(super) fn choose_split(data: &[f32], dim: usize, indices: &[i32], seed: u64, angular: bool) -> Split {
|
|
303
|
+
(0..SPLIT_ATTEMPTS)
|
|
304
|
+
.find_map(|attempt| make_split(data, dim, indices, attempt_seed(seed, attempt), angular))
|
|
305
|
+
.unwrap_or(Split { hyperplane: vec![0.0; dim], offset: 0.0, tie_seed: attempt_seed(seed, SPLIT_ATTEMPTS) })
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/// Re-split a node whose split put every point on one side, like the depth-first
|
|
309
|
+
/// builder: retry with new seeds, then fall back to a shuffled half split with a
|
|
310
|
+
/// zero hyperplane. Partitions `ids` in place (mirroring each swap through `swap`)
|
|
311
|
+
/// and returns the split and the size of the left part.
|
|
312
|
+
pub(super) fn repair_split(
|
|
313
|
+
data: &[f32],
|
|
314
|
+
dim: usize,
|
|
315
|
+
ids: &mut [i32],
|
|
316
|
+
mut swap: impl FnMut(usize, usize),
|
|
317
|
+
seed: u64,
|
|
318
|
+
angular: bool,
|
|
319
|
+
) -> (Split, usize) {
|
|
320
|
+
for attempt in SPLIT_ATTEMPTS + 1..2 * SPLIT_ATTEMPTS {
|
|
321
|
+
let Some(split) = make_split(data, dim, ids, attempt_seed(seed, attempt), angular) else {
|
|
322
|
+
continue;
|
|
323
|
+
};
|
|
324
|
+
let (mut left, mut right) = (0, ids.len());
|
|
325
|
+
while left < right {
|
|
326
|
+
let id = ids[left] as usize;
|
|
327
|
+
let margin = dot_product(&data[id * dim..(id + 1) * dim], &split.hyperplane) + split.offset;
|
|
328
|
+
let side = if margin.abs() < 1e-8 { tie_side(split.tie_seed, id) } else { (margin >= 0.0) as u8 };
|
|
329
|
+
if side == 0 {
|
|
330
|
+
left += 1;
|
|
331
|
+
} else {
|
|
332
|
+
right -= 1;
|
|
333
|
+
ids.swap(left, right);
|
|
334
|
+
swap(left, right);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
if left > 0 && left < ids.len() {
|
|
338
|
+
return (split, left);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
let mut rng = FastRng::new(attempt_seed(seed, 2 * SPLIT_ATTEMPTS));
|
|
342
|
+
for position in (1..ids.len()).rev() {
|
|
343
|
+
let other = rng.next_index(position + 1);
|
|
344
|
+
ids.swap(position, other);
|
|
345
|
+
swap(position, other);
|
|
346
|
+
}
|
|
347
|
+
(Split { hyperplane: vec![0.0; dim], offset: 0.0, tie_seed: seed }, ids.len() / 2)
|
|
348
|
+
}
|
|
349
|
+
|
|
295
350
|
pub(super) fn make_split(
|
|
296
351
|
data: &[f32],
|
|
297
352
|
dim: usize,
|
|
@@ -309,11 +364,12 @@ pub(super) fn make_split(
|
|
|
309
364
|
let second_index = indices[second] as usize;
|
|
310
365
|
let point1 = &data[first_index * dim..(first_index + 1) * dim];
|
|
311
366
|
let point2 = &data[second_index * dim..(second_index + 1) * dim];
|
|
312
|
-
if angular {
|
|
367
|
+
let split = if angular {
|
|
313
368
|
make_angular_split(point1, point2)
|
|
314
369
|
} else {
|
|
315
370
|
make_euclidean_split(point1, point2)
|
|
316
|
-
}
|
|
371
|
+
};
|
|
372
|
+
split.map(|split| Split { tie_seed: seed, ..split })
|
|
317
373
|
}
|
|
318
374
|
|
|
319
375
|
fn make_angular_split(point1: &[f32], point2: &[f32]) -> Option<Split> {
|
|
@@ -337,6 +393,7 @@ fn make_angular_split(point1: &[f32], point2: &[f32]) -> Option<Split> {
|
|
|
337
393
|
Some(Split {
|
|
338
394
|
hyperplane,
|
|
339
395
|
offset: 0.0,
|
|
396
|
+
tie_seed: 0,
|
|
340
397
|
})
|
|
341
398
|
}
|
|
342
399
|
|
|
@@ -361,6 +418,7 @@ fn make_euclidean_split(point1: &[f32], point2: &[f32]) -> Option<Split> {
|
|
|
361
418
|
Some(Split {
|
|
362
419
|
hyperplane,
|
|
363
420
|
offset: -midpoint_dot * inverse_norm,
|
|
421
|
+
tie_seed: 0,
|
|
364
422
|
})
|
|
365
423
|
}
|
|
366
424
|
|
|
@@ -17,9 +17,11 @@
|
|
|
17
17
|
//! partition are used, and leaves are emitted in breadth-first order by
|
|
18
18
|
//! sorting on (depth, root-to-node path).
|
|
19
19
|
|
|
20
|
-
use super::breadth_first::{batched_dot_products, child_seed,
|
|
20
|
+
use super::breadth_first::{batched_dot_products, child_seed, choose_split, repair_split, tie_side, Split, MAX_TREE_BATCH_WIDTH};
|
|
21
|
+
use super::flat_tree::FlatTree;
|
|
21
22
|
use crate::rng::FastRng;
|
|
22
23
|
use rayon::prelude::*;
|
|
24
|
+
use std::collections::HashMap;
|
|
23
25
|
|
|
24
26
|
const NO_NODE: u32 = u32::MAX;
|
|
25
27
|
const LOCAL_SUBTREE_BYTES: usize = 1 << 20;
|
|
@@ -62,7 +64,7 @@ pub(crate) fn local_points_for(dim: usize) -> usize {
|
|
|
62
64
|
|
|
63
65
|
/// Root-to-node path, one bit per level (right = 1), most significant first.
|
|
64
66
|
/// Nodes at equal depth compare lexicographically, which is breadth-first order.
|
|
65
|
-
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
|
|
67
|
+
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
|
|
66
68
|
struct Path(Vec<u64>);
|
|
67
69
|
|
|
68
70
|
impl Path {
|
|
@@ -88,6 +90,26 @@ struct Node {
|
|
|
88
90
|
}
|
|
89
91
|
|
|
90
92
|
type Leaf = (usize, Path, Vec<i32>);
|
|
93
|
+
/// A split node of a retained tree, keyed like leaves by (depth, path).
|
|
94
|
+
type Internal = (usize, Path, Split);
|
|
95
|
+
|
|
96
|
+
/// Split nodes of a retained tree, for its query tree.
|
|
97
|
+
#[derive(Default)]
|
|
98
|
+
struct Retained {
|
|
99
|
+
splits: Vec<Internal>,
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
impl Retained {
|
|
103
|
+
fn extend(&mut self, other: Retained) {
|
|
104
|
+
self.splits.extend(other.splits);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/// Leaves of one subtree, plus its query-tree record when the tree is retained.
|
|
109
|
+
struct Output {
|
|
110
|
+
leaves: Vec<Leaf>,
|
|
111
|
+
retained: Option<Retained>,
|
|
112
|
+
}
|
|
91
113
|
|
|
92
114
|
struct Tree {
|
|
93
115
|
permutation: Vec<i32>,
|
|
@@ -96,10 +118,11 @@ struct Tree {
|
|
|
96
118
|
splits: Vec<Split>,
|
|
97
119
|
leaves: Vec<Leaf>,
|
|
98
120
|
deferred: Vec<(Node, Vec<i32>)>,
|
|
121
|
+
retained: Option<Retained>,
|
|
99
122
|
}
|
|
100
123
|
|
|
101
124
|
impl Tree {
|
|
102
|
-
fn new(n_points: usize, seed: u64) -> Self {
|
|
125
|
+
fn new(n_points: usize, seed: u64, retain: bool) -> Self {
|
|
103
126
|
Self {
|
|
104
127
|
permutation: (0..n_points as i32).collect(),
|
|
105
128
|
assignments: vec![0; n_points],
|
|
@@ -107,6 +130,7 @@ impl Tree {
|
|
|
107
130
|
splits: Vec::new(),
|
|
108
131
|
leaves: Vec::new(),
|
|
109
132
|
deferred: Vec::new(),
|
|
133
|
+
retained: retain.then(Retained::default),
|
|
110
134
|
}
|
|
111
135
|
}
|
|
112
136
|
|
|
@@ -126,26 +150,19 @@ impl Tree {
|
|
|
126
150
|
let ids = self.permutation[node.start..node.end].to_vec();
|
|
127
151
|
self.deferred.push((node, ids));
|
|
128
152
|
} else {
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
self.leaves.push((node.depth, node.path.clone(), self.permutation[node.start..node.end].to_vec()));
|
|
133
|
-
}
|
|
134
|
-
Some(split) => {
|
|
135
|
-
ranges.push((node.start, node.end, self.frontier.len() as u32));
|
|
136
|
-
self.frontier.push(node);
|
|
137
|
-
self.splits.push(split);
|
|
138
|
-
}
|
|
139
|
-
}
|
|
153
|
+
ranges.push((node.start, node.end, self.frontier.len() as u32));
|
|
154
|
+
self.splits.push(choose_split(data, dim, &self.permutation[node.start..node.end], node.seed, angular));
|
|
155
|
+
self.frontier.push(node);
|
|
140
156
|
}
|
|
141
157
|
}
|
|
142
158
|
assign_ranges(&self.permutation, &mut self.assignments, &ranges);
|
|
143
159
|
!self.frontier.is_empty()
|
|
144
160
|
}
|
|
145
161
|
|
|
146
|
-
/// Partition each split node exactly as the breadth-first builder does
|
|
162
|
+
/// Partition each split node exactly as the breadth-first builder does,
|
|
163
|
+
/// re-splitting nodes whose split left one side empty.
|
|
147
164
|
/// Children's assignments are written by the next `classify`.
|
|
148
|
-
fn partition(&mut self, tree_slot: usize, batch_width: usize, sides: &[u8]) {
|
|
165
|
+
fn partition(&mut self, data: &[f32], dim: usize, angular: bool, tree_slot: usize, batch_width: usize, sides: &[u8]) {
|
|
149
166
|
let frontier = std::mem::take(&mut self.frontier);
|
|
150
167
|
// Frontier nodes are disjoint ranges in increasing order of `start`.
|
|
151
168
|
let mut slices = Vec::with_capacity(frontier.len());
|
|
@@ -154,13 +171,13 @@ impl Tree {
|
|
|
154
171
|
for node in &frontier {
|
|
155
172
|
let (_, tail) = std::mem::take(&mut rest).split_at_mut(node.start - offset);
|
|
156
173
|
let (slice, tail) = tail.split_at_mut(node.end - node.start);
|
|
157
|
-
slices.push(slice);
|
|
174
|
+
slices.push((slice, node.seed));
|
|
158
175
|
rest = tail;
|
|
159
176
|
offset = node.end;
|
|
160
177
|
}
|
|
161
|
-
let lefts: Vec<usize> = slices
|
|
178
|
+
let lefts: Vec<(usize, Option<Split>)> = slices
|
|
162
179
|
.into_par_iter()
|
|
163
|
-
.map(|slice| {
|
|
180
|
+
.map(|(slice, seed)| {
|
|
164
181
|
let (mut left, mut right) = (0, slice.len());
|
|
165
182
|
while left < right {
|
|
166
183
|
if sides[slice[left] as usize * batch_width + tree_slot] == 0 {
|
|
@@ -170,24 +187,24 @@ impl Tree {
|
|
|
170
187
|
slice.swap(left, right);
|
|
171
188
|
}
|
|
172
189
|
}
|
|
173
|
-
left
|
|
190
|
+
if left == 0 || left == slice.len() {
|
|
191
|
+
let (split, left) = repair_split(data, dim, slice, |_, _| {}, seed, angular);
|
|
192
|
+
return (left, Some(split));
|
|
193
|
+
}
|
|
194
|
+
(left, None)
|
|
174
195
|
})
|
|
175
196
|
.collect();
|
|
176
197
|
let mut next = Vec::with_capacity(frontier.len() * 2);
|
|
177
|
-
let
|
|
178
|
-
for (node, offset) in frontier.into_iter().zip(lefts) {
|
|
198
|
+
let splits = std::mem::take(&mut self.splits);
|
|
199
|
+
for ((node, (offset, repaired)), split) in frontier.into_iter().zip(lefts).zip(splits) {
|
|
179
200
|
let left = node.start + offset;
|
|
180
|
-
if left == node.start || left == node.end {
|
|
181
|
-
retired.push((node.start, node.end, NO_NODE));
|
|
182
|
-
self.leaves.push((node.depth, node.path.clone(), self.permutation[node.start..node.end].to_vec()));
|
|
183
|
-
continue;
|
|
184
|
-
}
|
|
185
201
|
next.push(Node { start: node.start, end: left, depth: node.depth + 1, seed: child_seed(node.seed, false), path: node.path.child(node.depth, false) });
|
|
186
202
|
next.push(Node { start: left, end: node.end, depth: node.depth + 1, seed: child_seed(node.seed, true), path: node.path.child(node.depth, true) });
|
|
203
|
+
if let Some(retained) = &mut self.retained {
|
|
204
|
+
retained.splits.push((node.depth, node.path, repaired.unwrap_or(split)));
|
|
205
|
+
}
|
|
187
206
|
}
|
|
188
|
-
assign_ranges(&self.permutation, &mut self.assignments, &retired);
|
|
189
207
|
self.frontier = next;
|
|
190
|
-
self.splits.clear();
|
|
191
208
|
}
|
|
192
209
|
}
|
|
193
210
|
|
|
@@ -265,18 +282,15 @@ fn local_subtree(
|
|
|
265
282
|
leaf_size: usize,
|
|
266
283
|
angular: bool,
|
|
267
284
|
max_depth: usize,
|
|
268
|
-
out: &mut
|
|
285
|
+
out: &mut Output,
|
|
269
286
|
scratch: &mut (Vec<f32>, Vec<u8>),
|
|
270
287
|
) {
|
|
271
288
|
let m = ids.len();
|
|
272
289
|
if m <= leaf_size || depth >= max_depth {
|
|
273
|
-
out.push((depth, path, ids.to_vec()));
|
|
290
|
+
out.leaves.push((depth, path, ids.to_vec()));
|
|
274
291
|
return;
|
|
275
292
|
}
|
|
276
|
-
let
|
|
277
|
-
out.push((depth, path, ids.to_vec()));
|
|
278
|
-
return;
|
|
279
|
-
};
|
|
293
|
+
let mut split = choose_split(data, dim, ids, seed, angular);
|
|
280
294
|
// Sides for every point (a function of the point alone), then the same
|
|
281
295
|
// two-pointer partition as the breadth-first builder.
|
|
282
296
|
let (margins, sides) = scratch;
|
|
@@ -284,7 +298,7 @@ fn local_subtree(
|
|
|
284
298
|
sides.clear();
|
|
285
299
|
sides.extend(margins.iter().zip(ids.iter()).map(|(&dot, &id)| {
|
|
286
300
|
let margin = dot + split.offset;
|
|
287
|
-
if margin.abs() < 1e-8 { tie_side(
|
|
301
|
+
if margin.abs() < 1e-8 { tie_side(split.tie_seed, id as usize) } else { (margin >= 0.0) as u8 }
|
|
288
302
|
}));
|
|
289
303
|
let (mut left, mut right) = (0, m);
|
|
290
304
|
while left < right {
|
|
@@ -298,13 +312,15 @@ fn local_subtree(
|
|
|
298
312
|
}
|
|
299
313
|
}
|
|
300
314
|
if left == 0 || left == m {
|
|
301
|
-
|
|
302
|
-
return;
|
|
315
|
+
(split, left) = repair_split(data, dim, ids, |a, b| rows.swap(a, b), seed, angular);
|
|
303
316
|
}
|
|
304
317
|
let (left_ids, right_ids) = ids.split_at_mut(left);
|
|
305
318
|
let (left_rows, right_rows) = rows.split_at_mut(left);
|
|
306
319
|
let left_path = path.child(depth, false);
|
|
307
320
|
let right_path = path.child(depth, true);
|
|
321
|
+
if let Some(retained) = &mut out.retained {
|
|
322
|
+
retained.splits.push((depth, path, split));
|
|
323
|
+
}
|
|
308
324
|
local_subtree(data, dim, buffer, left_ids, left_rows, depth + 1, child_seed(seed, false), left_path, leaf_size, angular, max_depth, out, scratch);
|
|
309
325
|
local_subtree(data, dim, buffer, right_ids, right_rows, depth + 1, child_seed(seed, true), right_path, leaf_size, angular, max_depth, out, scratch);
|
|
310
326
|
}
|
|
@@ -328,7 +344,70 @@ pub(crate) fn build_hybrid_leaf_forest(
|
|
|
328
344
|
assert!((1..=MAX_TREE_BATCH_WIDTH).contains(&tree_batch_width));
|
|
329
345
|
|
|
330
346
|
let seeds: Vec<u64> = (0..n_trees).map(|_| rng.next_u64()).collect();
|
|
331
|
-
build_trees(data, n_points, dim, &seeds, tree_batch_width, leaf_size, angular, max_depth, local_points)
|
|
347
|
+
build_trees(data, n_points, dim, &seeds, tree_batch_width, leaf_size, angular, max_depth, local_points, 0).1
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/// Hybrid forest that also returns the first `n_retained` trees as query trees.
|
|
351
|
+
/// Leaves are identical to `build_hybrid_leaf_forest` for the same RNG state.
|
|
352
|
+
#[allow(clippy::too_many_arguments)]
|
|
353
|
+
pub(crate) fn build_hybrid_forest(
|
|
354
|
+
data: &[f32],
|
|
355
|
+
n_points: usize,
|
|
356
|
+
dim: usize,
|
|
357
|
+
n_trees: usize,
|
|
358
|
+
leaf_size: usize,
|
|
359
|
+
rng: &mut FastRng,
|
|
360
|
+
angular: bool,
|
|
361
|
+
max_depth: usize,
|
|
362
|
+
tree_batch_width: usize,
|
|
363
|
+
local_points: usize,
|
|
364
|
+
n_retained: usize,
|
|
365
|
+
) -> (Vec<FlatTree>, Vec<Vec<i32>>) {
|
|
366
|
+
assert_eq!(data.len(), n_points * dim);
|
|
367
|
+
assert!(n_points <= i32::MAX as usize);
|
|
368
|
+
assert!((1..=MAX_TREE_BATCH_WIDTH).contains(&tree_batch_width));
|
|
369
|
+
|
|
370
|
+
let seeds: Vec<u64> = (0..n_trees).map(|_| rng.next_u64()).collect();
|
|
371
|
+
build_trees(data, n_points, dim, &seeds, tree_batch_width, leaf_size, angular, max_depth, local_points, n_retained)
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/// Assemble a query tree with nodes numbered in breadth-first order (root 0).
|
|
375
|
+
fn flat_tree(dim: usize, leaves: &[Leaf], splits: Vec<Internal>) -> FlatTree {
|
|
376
|
+
enum Kind {
|
|
377
|
+
Leaf(usize),
|
|
378
|
+
Split(Split),
|
|
379
|
+
}
|
|
380
|
+
let mut nodes: Vec<(usize, Path, Kind)> = leaves
|
|
381
|
+
.iter()
|
|
382
|
+
.enumerate()
|
|
383
|
+
.map(|(i, leaf)| (leaf.0, leaf.1.clone(), Kind::Leaf(i)))
|
|
384
|
+
.chain(splits.into_iter().map(|(depth, path, split)| (depth, path, Kind::Split(split))))
|
|
385
|
+
.collect();
|
|
386
|
+
nodes.sort_unstable_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));
|
|
387
|
+
let ids: HashMap<(usize, Path), i32> =
|
|
388
|
+
nodes.iter().enumerate().map(|(id, node)| ((node.0, node.1.clone()), id as i32)).collect();
|
|
389
|
+
|
|
390
|
+
let n_nodes = nodes.len();
|
|
391
|
+
let mut hyperplanes = vec![0.0; n_nodes * dim];
|
|
392
|
+
let mut offsets = vec![0.0; n_nodes];
|
|
393
|
+
let mut children = Vec::with_capacity(n_nodes);
|
|
394
|
+
let mut indices = Vec::with_capacity(leaves.iter().map(|leaf| leaf.2.len()).sum());
|
|
395
|
+
for (id, (depth, path, kind)) in nodes.into_iter().enumerate() {
|
|
396
|
+
match kind {
|
|
397
|
+
Kind::Leaf(i) => {
|
|
398
|
+
let start = indices.len() as i32;
|
|
399
|
+
indices.extend_from_slice(&leaves[i].2);
|
|
400
|
+
children.push([-start, -(indices.len() as i32)]);
|
|
401
|
+
}
|
|
402
|
+
Kind::Split(split) => {
|
|
403
|
+
hyperplanes[id * dim..(id + 1) * dim].copy_from_slice(&split.hyperplane);
|
|
404
|
+
offsets[id] = split.offset;
|
|
405
|
+
let child = |right| ids[&(depth + 1, path.child(depth, right))];
|
|
406
|
+
children.push([child(false), child(true)]);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
FlatTree { hyperplanes, offsets, children, indices, dim, n_nodes }
|
|
332
411
|
}
|
|
333
412
|
|
|
334
413
|
/// Build all trees with shared breadth-first levels and return their leaves in tree order,
|
|
@@ -344,9 +423,11 @@ fn build_trees(
|
|
|
344
423
|
angular: bool,
|
|
345
424
|
max_depth: usize,
|
|
346
425
|
local_points: usize,
|
|
347
|
-
|
|
426
|
+
n_retained: usize,
|
|
427
|
+
) -> (Vec<FlatTree>, Vec<Vec<i32>>) {
|
|
348
428
|
let n_trees = seeds.len();
|
|
349
|
-
let mut trees: Vec<Tree> =
|
|
429
|
+
let mut trees: Vec<Tree> =
|
|
430
|
+
seeds.par_iter().enumerate().map(|(i, &seed)| Tree::new(n_points, seed, i < n_retained)).collect();
|
|
350
431
|
// Points outside every frontier keep stale sides, which partition never reads.
|
|
351
432
|
let mut sides = vec![0u8; n_points * n_trees];
|
|
352
433
|
|
|
@@ -381,7 +462,7 @@ fn build_trees(
|
|
|
381
462
|
let node = node as usize;
|
|
382
463
|
let margin = margins[slot] + tree.splits[node].offset;
|
|
383
464
|
group_sides[slot] = if margin.abs() < 1e-8 {
|
|
384
|
-
tie_side(tree.
|
|
465
|
+
tie_side(tree.splits[node].tie_seed, point_index)
|
|
385
466
|
} else {
|
|
386
467
|
(margin >= 0.0) as u8
|
|
387
468
|
};
|
|
@@ -389,20 +470,22 @@ fn build_trees(
|
|
|
389
470
|
}
|
|
390
471
|
}
|
|
391
472
|
});
|
|
392
|
-
trees.par_iter_mut().enumerate().for_each(|(slot, tree)| tree.partition(slot, n_trees, &sides));
|
|
473
|
+
trees.par_iter_mut().enumerate().for_each(|(slot, tree)| tree.partition(data, dim, angular, slot, n_trees, &sides));
|
|
393
474
|
}
|
|
394
475
|
drop(sides);
|
|
395
476
|
|
|
396
477
|
// Cache-local subtrees for all trees at once, then breadth-first output order per tree.
|
|
397
|
-
trees
|
|
478
|
+
let built: Vec<(Option<FlatTree>, Vec<Vec<i32>>)> = trees
|
|
398
479
|
.into_par_iter()
|
|
399
480
|
.map(|tree| {
|
|
400
481
|
let mut leaves = tree.leaves;
|
|
401
|
-
let
|
|
482
|
+
let mut retained = tree.retained;
|
|
483
|
+
let retain = retained.is_some();
|
|
484
|
+
let local: Vec<Output> = tree
|
|
402
485
|
.deferred
|
|
403
486
|
.into_par_iter()
|
|
404
487
|
.map(|(node, mut ids)| {
|
|
405
|
-
let mut out = Vec::new();
|
|
488
|
+
let mut out = Output { leaves: Vec::new(), retained: retain.then(Retained::default) };
|
|
406
489
|
let mut scratch = (Vec::new(), Vec::new());
|
|
407
490
|
if dim > GATHER_MAX_DIM {
|
|
408
491
|
let mut rows: Vec<u32> = ids.iter().map(|&id| id as u32).collect();
|
|
@@ -418,14 +501,24 @@ fn build_trees(
|
|
|
418
501
|
out
|
|
419
502
|
})
|
|
420
503
|
.collect();
|
|
421
|
-
|
|
504
|
+
for out in local {
|
|
505
|
+
leaves.extend(out.leaves);
|
|
506
|
+
if let (Some(retained), Some(local_retained)) = (&mut retained, out.retained) {
|
|
507
|
+
retained.extend(local_retained);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
422
510
|
leaves.sort_unstable_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));
|
|
423
|
-
|
|
511
|
+
let flat = retained.map(|retained| flat_tree(dim, &leaves, retained.splits));
|
|
512
|
+
(flat, leaves.into_iter().map(|leaf| leaf.2).collect::<Vec<_>>())
|
|
424
513
|
})
|
|
425
|
-
.collect
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
514
|
+
.collect();
|
|
515
|
+
let mut flat_trees = Vec::with_capacity(n_retained.min(n_trees));
|
|
516
|
+
let mut all_leaves = Vec::new();
|
|
517
|
+
for (flat, leaves) in built {
|
|
518
|
+
flat_trees.extend(flat);
|
|
519
|
+
all_leaves.extend(leaves);
|
|
520
|
+
}
|
|
521
|
+
(flat_trees, all_leaves)
|
|
429
522
|
}
|
|
430
523
|
|
|
431
524
|
#[cfg(test)]
|
|
@@ -477,6 +570,65 @@ mod tests {
|
|
|
477
570
|
}
|
|
478
571
|
}
|
|
479
572
|
|
|
573
|
+
#[test]
|
|
574
|
+
fn retained_trees_match_leaves_and_route_training_points() {
|
|
575
|
+
for &(n, dim, angular, local, retained) in &[
|
|
576
|
+
(6000, 37, false, 800, 2),
|
|
577
|
+
(6000, 37, true, 0, 1),
|
|
578
|
+
(3000, GATHER_MAX_DIM + 72, false, 500, 3),
|
|
579
|
+
(3000, 16, false, 10_000, 7), // whole tree deferred at the root
|
|
580
|
+
(40, 16, false, 800, 1), // root is a leaf
|
|
581
|
+
] {
|
|
582
|
+
let x = data(n, dim, 4);
|
|
583
|
+
let expected = build_hybrid_leaf_forest(&x, n, dim, 7, 60, &mut FastRng::new(9), angular, 200, 6, local);
|
|
584
|
+
let (trees, leaves) = build_hybrid_forest(&x, n, dim, 7, 60, &mut FastRng::new(9), angular, 200, 6, local, retained);
|
|
585
|
+
assert_eq!(leaves, expected);
|
|
586
|
+
assert_eq!(trees.len(), retained);
|
|
587
|
+
|
|
588
|
+
let mut offset = 0;
|
|
589
|
+
for tree in &trees {
|
|
590
|
+
let n_leaves = tree.get_all_leaves().len();
|
|
591
|
+
assert_eq!(tree.n_nodes, 2 * n_leaves - 1);
|
|
592
|
+
let mut from_tree: Vec<Vec<i32>> =
|
|
593
|
+
tree.get_all_leaves().into_iter().map(|(s, e)| tree.indices[s..e].to_vec()).collect();
|
|
594
|
+
let mut from_forest = leaves[offset..offset + n_leaves].to_vec();
|
|
595
|
+
from_tree.sort();
|
|
596
|
+
from_forest.sort();
|
|
597
|
+
assert_eq!(from_tree, from_forest);
|
|
598
|
+
offset += n_leaves;
|
|
599
|
+
|
|
600
|
+
let mut rng = FastRng::new(1);
|
|
601
|
+
for point in 0..n {
|
|
602
|
+
let leaf = tree.get_leaf_indices(&x[point * dim..(point + 1) * dim], &mut rng);
|
|
603
|
+
assert!(leaf.contains(&(point as i32)), "point {point} routed to the wrong leaf");
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
#[test]
|
|
610
|
+
fn failed_splits_are_retried_and_leaves_stay_bounded() {
|
|
611
|
+
// Duplicates and zero vectors make many splits fail.
|
|
612
|
+
let (n, dim) = (3000, 16);
|
|
613
|
+
let base = data(40, dim, 2);
|
|
614
|
+
let mut x: Vec<f32> = (0..n).flat_map(|i| base[(i % 40) * dim..(i % 40 + 1) * dim].to_vec()).collect();
|
|
615
|
+
x[..500 * dim].fill(0.0);
|
|
616
|
+
for angular in [false, true] {
|
|
617
|
+
let (a, b) = both(&x, n, dim, 3, 20, angular, 200, 6, 500, 2);
|
|
618
|
+
assert_eq!(a, b);
|
|
619
|
+
let (trees, leaves) = build_hybrid_forest(&x, n, dim, 3, 20, &mut FastRng::new(9), angular, 200, 6, 500, 3);
|
|
620
|
+
assert_eq!(leaves, b);
|
|
621
|
+
assert!(leaves.iter().all(|leaf| !leaf.is_empty() && leaf.len() <= 20), "angular={angular}");
|
|
622
|
+
for tree in &trees {
|
|
623
|
+
let tree_leaves = tree.get_all_leaves();
|
|
624
|
+
assert_eq!(tree.n_nodes, 2 * tree_leaves.len() - 1);
|
|
625
|
+
let mut points = tree.indices.clone();
|
|
626
|
+
points.sort_unstable();
|
|
627
|
+
assert_eq!(points, (0..n as i32).collect::<Vec<_>>());
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
480
632
|
#[test]
|
|
481
633
|
fn hybrid_matches_with_depth_limit_and_ties() {
|
|
482
634
|
// Many duplicate points force tie-breaking and depth-limited leaves.
|
|
@@ -9,7 +9,7 @@ mod flat_tree;
|
|
|
9
9
|
#[cfg(not(feature = "hybrid-forest"))]
|
|
10
10
|
pub(crate) use breadth_first::build_breadth_first_leaf_forest;
|
|
11
11
|
#[cfg(feature = "hybrid-forest")]
|
|
12
|
-
pub(crate) use hybrid_forest::{build_hybrid_leaf_forest, local_points_for};
|
|
12
|
+
pub(crate) use hybrid_forest::{build_hybrid_forest, build_hybrid_leaf_forest, local_points_for};
|
|
13
13
|
pub use builder::{build_rp_forest, build_rp_tree, rptree_leaf_array};
|
|
14
14
|
pub(crate) use builder::{build_rp_leaf_forest, build_rp_leaf_tree};
|
|
15
15
|
pub use flat_tree::{FlatTree, QuantizedFlatTree};
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|