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
//! Diversity-aware probe selection for multi-probe vector search.
//!
//! Provides a Greedy MMR (Maximal Marginal Relevance) selection algorithm
//! that balances proximity to the query with spatial diversity across
//! the selected probe set. Used by IVF-PQ indices.
use alloc::vec;
use alloc::vec::Vec;
use crate::vector_ops::DistanceMetric;
/// Configuration for diversity-aware probe selection.
///
/// When `lambda` is 0.0 (default), selection is identical to pure
/// distance-based top-nprobe -- zero overhead. Increasing `lambda`
/// toward 1.0 trades some proximity for spatial diversity.
#[derive(Debug, Clone, Copy)]
pub struct DiversityConfig {
/// Diversity weight in [0.0, 1.0].
/// - 0.0: pure distance ranking (default, zero overhead)
/// - 0.15-0.3: mild diversity, good for moderately skewed data
/// - 0.5+: aggressive diversity, for highly clustered distributions
pub lambda: f32,
}
impl Default for DiversityConfig {
fn default() -> Self {
Self { lambda: 0.0 }
}
}
impl DiversityConfig {
/// Returns `true` if diversity selection is active.
#[inline]
pub fn enabled(&self) -> bool {
self.lambda > 0.0
}
}
/// Select `nprobe` probes from a pre-sorted candidate list, balancing
/// proximity to the query with inter-probe diversity via Greedy MMR.
///
/// # Arguments
/// - `candidates`: `(id, distance_to_query)` pairs, sorted ascending by distance
/// - `candidate_centroids`: flat f32 array, `candidates.len() * dim` floats,
/// ordered 1:1 with `candidates`
/// - `dim`: vector dimensionality
/// - `nprobe`: number of probes to select
/// - `diversity`: diversity configuration
/// - `metric`: distance metric for inter-centroid distances
///
/// # Complexity
/// `O(nprobe * shortlist_size * dim)` where `shortlist_size = min(2 * nprobe, candidates.len())`.
/// When `lambda == 0.0`, returns immediately with a simple slice copy.
pub fn select_diverse_probes(
candidates: &[(u32, f32)],
candidate_centroids: &[f32],
dim: usize,
nprobe: usize,
diversity: DiversityConfig,
metric: DistanceMetric,
) -> Vec<(u32, f32)> {
let n = nprobe.min(candidates.len());
if n == 0 {
return Vec::new();
}
// Fast path: no diversity or not enough candidates to be selective
if !diversity.enabled() || n >= candidates.len() {
return candidates[..n].to_vec();
}
let Some(total_centroid_floats) = candidates.len().checked_mul(dim) else {
return candidates[..n].to_vec(); // overflow: fallback to top-n
};
if candidate_centroids.len() != total_centroid_floats {
// Length mismatch -- cannot safely index into centroid data.
// Return the top-n by distance as a fallback rather than panicking.
return candidates[..n].to_vec();
}
// Shortlist: top 2*nprobe by distance (already sorted)
let shortlist_len = candidates.len().min(nprobe.saturating_mul(2));
let shortlist = &candidates[..shortlist_len];
// SAFETY: shortlist_len <= candidates.len(), and candidates.len() * dim
// was verified above, so shortlist_len * dim cannot overflow.
let shortlist_centroids = &candidate_centroids[..shortlist_len * dim];
let lambda = diversity.lambda.clamp(0.0, 1.0);
// Normalize query distances to [0, 1]
let d_min = shortlist[0].1;
let d_max = shortlist[shortlist_len - 1].1;
let d_range = if (d_max - d_min).abs() > f32::EPSILON {
d_max - d_min
} else {
1.0
};
let mut selected: Vec<usize> = Vec::with_capacity(nprobe);
let mut result: Vec<(u32, f32)> = Vec::with_capacity(nprobe);
let mut is_selected = vec![false; shortlist_len];
// Always select the closest candidate first
selected.push(0);
is_selected[0] = true;
result.push(shortlist[0]);
// Scratch buffer for per-candidate min-inter-distances
let mut min_inter_dists = vec![0.0f32; shortlist_len];
// Greedy MMR selection for remaining slots
for _ in 1..nprobe {
if selected.len() >= shortlist_len {
break;
}
// Pass 1: compute min inter-centroid distance for each unselected
// candidate and find the min/max for normalization.
let mut inter_min: f32 = f32::INFINITY;
let mut inter_max: f32 = f32::NEG_INFINITY;
for j in 0..shortlist_len {
if is_selected[j] {
continue;
}
let centroid_j = &shortlist_centroids[j * dim..(j + 1) * dim];
let mut min_d = f32::INFINITY;
for &s in &selected {
let centroid_s = &shortlist_centroids[s * dim..(s + 1) * dim];
let d = metric.compute(centroid_j, centroid_s);
if d < min_d {
min_d = d;
}
}
min_inter_dists[j] = min_d;
if min_d < inter_min {
inter_min = min_d;
}
if min_d > inter_max {
inter_max = min_d;
}
}
// Shift-and-scale normalization: maps to [0, 1] regardless of sign.
// Works correctly for all metrics including DotProduct (negative distances).
let inter_range = if (inter_max - inter_min).abs() > f32::EPSILON {
inter_max - inter_min
} else {
1.0
};
// Pass 2: score candidates with consistent normalization
let mut best_idx = usize::MAX;
let mut best_score = f32::INFINITY;
for j in 0..shortlist_len {
if is_selected[j] {
continue;
}
let relevance = (shortlist[j].1 - d_min) / d_range;
let diversity_score = (min_inter_dists[j] - inter_min) / inter_range;
// MMR: lower = better (relevance low = close, diversity high = spread)
let score = (1.0 - lambda) * relevance - lambda * diversity_score;
if score < best_score {
best_score = score;
best_idx = j;
}
}
if best_idx == usize::MAX {
break;
}
selected.push(best_idx);
is_selected[best_idx] = true;
result.push(shortlist[best_idx]);
}
// Sort by original distance for consistent downstream processing
result.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
result
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
fn make_candidates_and_centroids(
positions: &[(f32, f32)],
query: (f32, f32),
) -> (Vec<(u32, f32)>, Vec<f32>) {
let dim = 2;
let mut candidates: Vec<(u32, f32)> = positions
.iter()
.enumerate()
.map(|(i, &(x, y))| {
let dist = (x - query.0).powi(2) + (y - query.1).powi(2);
#[allow(clippy::cast_possible_truncation)]
(i as u32, dist)
})
.collect();
candidates.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
// Build centroids in sorted order
let mut centroids = Vec::with_capacity(candidates.len() * dim);
for &(id, _) in &candidates {
let (x, y) = positions[id as usize];
centroids.push(x);
centroids.push(y);
}
(candidates, centroids)
}
#[test]
fn lambda_zero_identical_to_greedy() {
let positions = vec![(1.0, 0.0), (1.1, 0.0), (1.2, 0.0), (0.0, 5.0), (0.0, 5.1)];
let query = (0.0, 0.0);
let (candidates, centroids) = make_candidates_and_centroids(&positions, query);
let config = DiversityConfig { lambda: 0.0 };
let result = select_diverse_probes(
&candidates,
¢roids,
2,
3,
config,
DistanceMetric::EuclideanSq,
);
// Should be the 3 closest by distance
assert_eq!(result.len(), 3);
assert_eq!(result[0].0, candidates[0].0);
assert_eq!(result[1].0, candidates[1].0);
assert_eq!(result[2].0, candidates[2].0);
}
#[test]
fn diversity_selects_from_both_clusters() {
// Two tight groups: group A near (1,0), group B near (0,10)
let positions = vec![
(1.0, 0.0),
(1.05, 0.0),
(1.1, 0.0),
(1.15, 0.0),
(1.2, 0.0),
(0.0, 10.0),
(0.0, 10.1),
(0.0, 10.2),
];
let query = (0.0, 0.0);
let (candidates, centroids) = make_candidates_and_centroids(&positions, query);
// With lambda=0.0, nprobe=3: all from group A
let greedy = select_diverse_probes(
&candidates,
¢roids,
2,
3,
DiversityConfig { lambda: 0.0 },
DistanceMetric::EuclideanSq,
);
let greedy_ids: Vec<u32> = greedy.iter().map(|x| x.0).collect();
// All 3 should be from group A (ids correspond to positions 0-4)
assert!(greedy_ids.iter().all(|&id| id <= 4));
// With lambda=0.5, nprobe=3: should pick at least one from group B
let diverse = select_diverse_probes(
&candidates,
¢roids,
2,
3,
DiversityConfig { lambda: 0.5 },
DistanceMetric::EuclideanSq,
);
let diverse_ids: Vec<u32> = diverse.iter().map(|x| x.0).collect();
let has_group_b = diverse_ids.iter().any(|&id| id >= 5);
assert!(
has_group_b,
"diversity should select from group B, got IDs: {diverse_ids:?}"
);
}
#[test]
fn single_probe_always_closest() {
let positions = vec![(5.0, 0.0), (0.0, 10.0), (3.0, 3.0)];
let query = (0.0, 0.0);
let (candidates, centroids) = make_candidates_and_centroids(&positions, query);
for lambda in [0.0, 0.5, 1.0] {
let result = select_diverse_probes(
&candidates,
¢roids,
2,
1,
DiversityConfig { lambda },
DistanceMetric::EuclideanSq,
);
assert_eq!(result.len(), 1);
assert_eq!(result[0].0, candidates[0].0);
}
}
#[test]
fn nprobe_exceeds_candidates() {
let positions = vec![(1.0, 0.0), (0.0, 1.0)];
let query = (0.0, 0.0);
let (candidates, centroids) = make_candidates_and_centroids(&positions, query);
let result = select_diverse_probes(
&candidates,
¢roids,
2,
10,
DiversityConfig { lambda: 0.5 },
DistanceMetric::EuclideanSq,
);
assert_eq!(result.len(), 2);
}
#[test]
fn deterministic() {
let positions = vec![(1.0, 0.0), (2.0, 0.0), (0.0, 3.0), (3.0, 3.0), (5.0, 5.0)];
let query = (0.0, 0.0);
let (candidates, centroids) = make_candidates_and_centroids(&positions, query);
let config = DiversityConfig { lambda: 0.3 };
let r1 = select_diverse_probes(
&candidates,
¢roids,
2,
3,
config,
DistanceMetric::EuclideanSq,
);
let r2 = select_diverse_probes(
&candidates,
¢roids,
2,
3,
config,
DistanceMetric::EuclideanSq,
);
assert_eq!(r1, r2);
}
#[test]
fn empty_candidates() {
let result = select_diverse_probes(
&[],
&[],
2,
5,
DiversityConfig { lambda: 0.5 },
DistanceMetric::EuclideanSq,
);
assert!(result.is_empty());
}
#[test]
fn dot_product_diversity_selects_spread() {
// DotProduct metric returns -dot_product(a,b), so distances can be negative.
// Group A: unit-ish vectors near (1,0) -- all very similar to each other
// Group B: unit-ish vectors near (0,1) -- orthogonal to group A
// Query: (0.9, 0.1) normalized-ish -- closest to group A
let dim = 2;
let centroids_raw: Vec<(f32, f32)> = vec![
(0.99, 0.0), // A0
(0.98, 0.0), // A1
(0.97, 0.0), // A2
(0.96, 0.0), // A3
(0.0, 0.99), // B0
(0.0, 0.98), // B1
];
let query = (0.9, 0.1);
// Compute DotProduct distances (= -dot(q, c))
let mut candidates: Vec<(u32, f32)> = centroids_raw
.iter()
.enumerate()
.map(|(i, &(x, y))| {
let dist = -(query.0 * x + query.1 * y);
#[allow(clippy::cast_possible_truncation)]
(i as u32, dist)
})
.collect();
candidates.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
let mut centroids_flat = Vec::with_capacity(candidates.len() * dim);
for &(id, _) in &candidates {
let (x, y) = centroids_raw[id as usize];
centroids_flat.push(x);
centroids_flat.push(y);
}
// Without diversity: all from group A (closest by dot product)
let greedy = select_diverse_probes(
&candidates,
¢roids_flat,
dim,
3,
DiversityConfig { lambda: 0.0 },
DistanceMetric::DotProduct,
);
let greedy_ids: Vec<u32> = greedy.iter().map(|x| x.0).collect();
assert!(
greedy_ids.iter().all(|&id| id <= 3),
"greedy should pick all from group A, got {greedy_ids:?}"
);
// With diversity: should include at least one from group B
let diverse = select_diverse_probes(
&candidates,
¢roids_flat,
dim,
3,
DiversityConfig { lambda: 0.5 },
DistanceMetric::DotProduct,
);
let diverse_ids: Vec<u32> = diverse.iter().map(|x| x.0).collect();
let has_group_b = diverse_ids.iter().any(|&id| id >= 4);
assert!(
has_group_b,
"diversity should select from group B with DotProduct, got IDs: {diverse_ids:?}"
);
}
#[test]
fn cosine_diversity_selects_spread() {
// Cosine distance is in [0, 2]. Test that diversity works with this range.
let dim = 2;
// Group A: vectors pointing right, Group B: vectors pointing up
let centroids_raw: Vec<(f32, f32)> = vec![
(1.0, 0.1),
(1.0, 0.15),
(1.0, 0.2),
(1.0, 0.25),
(0.1, 1.0),
(0.15, 1.0),
];
let query = (1.0, 0.05);
let mut candidates: Vec<(u32, f32)> = centroids_raw
.iter()
.enumerate()
.map(|(i, &(x, y))| {
let dist = DistanceMetric::Cosine.compute(&[query.0, query.1], &[x, y]);
#[allow(clippy::cast_possible_truncation)]
(i as u32, dist)
})
.collect();
candidates.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
let mut centroids_flat = Vec::with_capacity(candidates.len() * dim);
for &(id, _) in &candidates {
let (x, y) = centroids_raw[id as usize];
centroids_flat.push(x);
centroids_flat.push(y);
}
let diverse = select_diverse_probes(
&candidates,
¢roids_flat,
dim,
3,
DiversityConfig { lambda: 0.5 },
DistanceMetric::Cosine,
);
let diverse_ids: Vec<u32> = diverse.iter().map(|x| x.0).collect();
let has_group_b = diverse_ids.iter().any(|&id| id >= 4);
assert!(
has_group_b,
"diversity should select from group B with Cosine, got IDs: {diverse_ids:?}"
);
}
}