rinnd 0.4.0__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.
Files changed (49) hide show
  1. {rinnd-0.4.0 → rinnd-0.4.4}/PKG-INFO +1 -1
  2. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd/Cargo.toml +1 -0
  3. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd/src/lib.rs +7 -8
  4. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/Cargo.toml +3 -1
  5. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/index.rs +6 -4
  6. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/nndescent/mod.rs +95 -14
  7. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/search/greedy.rs +25 -0
  8. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/tree/breadth_first.rs +71 -13
  9. rinnd-0.4.4/crates/rinnd-core/src/tree/hybrid_forest.rs +660 -0
  10. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/tree/mod.rs +1 -1
  11. {rinnd-0.4.0 → rinnd-0.4.4}/pyproject.toml +1 -1
  12. rinnd-0.4.0/crates/rinnd-core/src/tree/hybrid_forest.rs +0 -430
  13. {rinnd-0.4.0 → rinnd-0.4.4}/Cargo.lock +0 -0
  14. {rinnd-0.4.0 → rinnd-0.4.4}/Cargo.toml +0 -0
  15. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/benches/distance.rs +0 -0
  16. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/benches/heap.rs +0 -0
  17. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/examples/graph_bench.rs +0 -0
  18. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/distance/alternatives.rs +0 -0
  19. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/distance/angular.rs +0 -0
  20. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/distance/binary.rs +0 -0
  21. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/distance/cosine.rs +0 -0
  22. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/distance/euclidean.rs +0 -0
  23. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/distance/hellinger.rs +0 -0
  24. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/distance/inner_product.rs +0 -0
  25. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/distance/minkowski.rs +0 -0
  26. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/distance/mod.rs +0 -0
  27. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/distance/quantized.rs +0 -0
  28. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/distance/tile.rs +0 -0
  29. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/distance/traits.rs +0 -0
  30. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/graph/mod.rs +0 -0
  31. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/graph/neighbor_graph.rs +0 -0
  32. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/graph/search_graph.rs +0 -0
  33. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/heap/candidate_heap.rs +0 -0
  34. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/heap/mod.rs +0 -0
  35. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/heap/neighbor_heap.rs +0 -0
  36. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/lib.rs +0 -0
  37. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/nndescent/candidates.rs +0 -0
  38. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/nndescent/update.rs +0 -0
  39. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/rng.rs +0 -0
  40. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/search/mod.rs +0 -0
  41. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/tree/builder.rs +0 -0
  42. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/tree/flat_tree.rs +0 -0
  43. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-core/src/visited.rs +0 -0
  44. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-simd/Cargo.toml +0 -0
  45. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-simd/benches/simd_distance.rs +0 -0
  46. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-simd/src/avx2.rs +0 -0
  47. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-simd/src/avx512.rs +0 -0
  48. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-simd/src/detect.rs +0 -0
  49. {rinnd-0.4.0 → rinnd-0.4.4}/crates/rinnd-simd/src/lib.rs +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rinnd
3
- Version: 0.4.0
3
+ Version: 0.4.4
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: 3
@@ -21,6 +21,7 @@ active-candidates = ["rinnd-core/active-candidates"]
21
21
  blocked-candidates = ["rinnd-core/blocked-candidates"]
22
22
  hybrid-forest = ["rinnd-core/hybrid-forest"]
23
23
  tiled-leaves = ["rinnd-core/tiled-leaves"]
24
+ generation-prefetch = ["rinnd-core/generation-prefetch"]
24
25
 
25
26
  [dependencies]
26
27
  rinnd-core = { path = "../rinnd-core", default-features = false, features = ["std", "rayon"] }
@@ -881,15 +881,8 @@ impl PyNNDescent {
881
881
  }
882
882
 
883
883
  let breadth_first_batch_width = match tree_build_strategy {
884
- "auto" if graph_only => Some(tree_batch_width),
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.
@@ -9,7 +9,7 @@ repository.workspace = true
9
9
  rust-version.workspace = true
10
10
 
11
11
  [features]
12
- default = ["std", "rayon", "batched-euclidean", "batched-angular", "compact-candidates", "batched-leaves", "candidate-membership", "candidate-workspace", "active-candidates", "hybrid-forest", "tiled-leaves"]
12
+ default = ["std", "rayon", "batched-euclidean", "batched-angular", "compact-candidates", "batched-leaves", "candidate-membership", "candidate-workspace", "active-candidates", "hybrid-forest", "tiled-leaves", "generation-prefetch"]
13
13
  std = []
14
14
  rayon = ["dep:rayon"]
15
15
  mmap = ["dep:memmap2"]
@@ -28,6 +28,8 @@ active-candidates = []
28
28
  batched-leaves = []
29
29
  # Register-tiled leaf-initialization kernels (bit-identical distances).
30
30
  tiled-leaves = []
31
+ # Prefetch next hub's candidate vectors during update generation (dim <= 256).
32
+ generation-prefetch = []
31
33
  packed-updates = []
32
34
 
33
35
  [dependencies]
@@ -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::{nn_descent, nn_descent_graph, NNDescentParams, NNDescentStats};
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
- /// Use the experimental breadth-first forest for graph-only construction.
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 for graph-only 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) = nn_descent(
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
  &params,
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
- let forest = build_rp_forest(
158
- data,
159
- n_points,
160
- dim,
161
- params.n_trees,
162
- params.leaf_size,
163
- rng,
164
- params.angular,
165
- params.max_depth,
166
- );
167
- let leaf_array = rptree_leaf_array(&forest);
168
- (forest, leaf_array)
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(
@@ -508,6 +560,31 @@ struct PotentialUpdate {
508
560
 
509
561
  const UPDATE_BLOCK_SIZE: usize = 16384;
510
562
 
563
+ // Above this, whole-vector prefetch (49 lines at d = 784) slowed generation; the hardware prefetcher suffices.
564
+ const GENERATION_PREFETCH_MAX_DIM: usize = 256;
565
+
566
+ /// Prefetch every cache line of a hub's candidate vectors and their heap roots.
567
+ #[inline(always)]
568
+ fn prefetch_hub(candidates: &CandidateSets, hub: usize, data: &[f32], dim: usize, graph: &NeighborHeap) {
569
+ #[cfg(target_arch = "x86_64")]
570
+ unsafe {
571
+ use std::arch::x86_64::{_mm_prefetch, _MM_HINT_T0};
572
+ let lines = (dim * 4).div_ceil(64);
573
+ for &candidate in candidates.get_new(hub).iter().chain(candidates.get_old(hub)) {
574
+ if candidate < 0 {
575
+ continue;
576
+ }
577
+ let vector = data.as_ptr().add(candidate as usize * dim) as *const i8;
578
+ for line in 0..lines {
579
+ _mm_prefetch(vector.add(line * 64), _MM_HINT_T0);
580
+ }
581
+ _mm_prefetch(graph.distances.as_ptr().add(candidate as usize * graph.k) as *const i8, _MM_HINT_T0);
582
+ }
583
+ }
584
+ #[cfg(not(target_arch = "x86_64"))]
585
+ let _ = (candidates, hub, data, dim, graph);
586
+ }
587
+
511
588
  trait UpdateRecord: Copy + Send + Sync {
512
589
  fn encode(
513
590
  update: PotentialUpdate,
@@ -770,11 +847,15 @@ fn update_iteration_observed<D: Distance<f32> + Sync, Record: UpdateRecord>(
770
847
 
771
848
  // Generate updates and bucket by destination vertex block
772
849
  let generation_started = Instant::now();
850
+ let prefetch_hubs = cfg!(feature = "generation-prefetch") && dim <= GENERATION_PREFETCH_MAX_DIM;
773
851
  thread_buckets.par_iter_mut().enumerate().for_each(|(t, local_buckets)| {
774
852
  let row_start = block_start + t * rows_per_thread;
775
853
  let row_end = (row_start + rows_per_thread).min(block_end);
776
854
 
777
855
  for i in row_start..row_end {
856
+ if prefetch_hubs && i + 1 < row_end {
857
+ prefetch_hub(candidates, i + 1, data, dim, graph);
858
+ }
778
859
  let new_cands = candidates.get_new(i);
779
860
  let old_cands = candidates.get_old(i);
780
861
 
@@ -86,6 +86,31 @@ fn initialize_fp32<D: Distance<f32>>(
86
86
  &mut workspace.tree_leaves,
87
87
  );
88
88
  for &(start, end) in &workspace.tree_leaves {
89
+ if D::USE_DISTANCE_FOUR && dim >= 32 {
90
+ let mut pending = [0i32; 4];
91
+ let mut count = 0;
92
+ for &idx in &tree.indices[start..end] {
93
+ if idx >= 0 && !workspace.visited.check_and_mark(idx) {
94
+ pending[count] = idx;
95
+ count += 1;
96
+ if count == 4 {
97
+ let vectors = pending.map(|c| &data[c as usize * dim..(c as usize + 1) * dim]);
98
+ let distances = distance.distance_four(query, vectors);
99
+ for slot in 0..4 {
100
+ workspace.result_heap.push(distances[slot], pending[slot]);
101
+ workspace.seed_set.push(distances[slot], pending[slot]);
102
+ }
103
+ count = 0;
104
+ }
105
+ }
106
+ }
107
+ for &idx in &pending[..count] {
108
+ let d = distance.distance(query, &data[idx as usize * dim..(idx as usize + 1) * dim]);
109
+ workspace.result_heap.push(d, idx);
110
+ workspace.seed_set.push(d, idx);
111
+ }
112
+ continue;
113
+ }
89
114
  for &idx in &tree.indices[start..end] {
90
115
  if idx >= 0 && !workspace.visited.check_and_mark(idx) {
91
116
  let d = distance
@@ -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
- make_split(
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.leaves
102
- .push(self.permutation[node.start..node.end].to_vec());
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(tree.frontier[node_index].seed, point_index)
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