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
//! A layer over the centroids, so that finding the nearest partition is not a
//! walk over every partition.
//!
//! # Why this is here
//!
//! [`Partitions`](crate::Partitions) keeps one centroid per partition and finds
//! the nearest one by measuring against all of them. That is the right thing at
//! a hundred partitions and it is the wrong thing at four thousand, and the
//! partition count is `n / posting`, so it grows with the collection. Placing a
//! vector does one of those lookups, so building the index is quadratic in the
//! number of vectors. Measured on 128 dimensional vectors by
//! `examples/ingest.rs`, with the placement already 86 percent of the time by
//! eight hundred thousand: 34 thousand a second at two hundred thousand vectors,
//! 22 thousand at four hundred thousand and 13 thousand at eight hundred
//! thousand. Doubling the collection halves the rate, which is the shape of a
//! quadratic and is exactly what an index that never rebuilds is supposed to not
//! do.
//!
//! So there is a second level. The centroids are themselves clustered under a
//! smaller set of anchors, and a lookup measures against the anchors first and
//! then only against the centroids under the nearest few. With `A` anchors over
//! `P` centroids a lookup costs `A + k * P / A` distances instead of `P`, which
//! is smallest at `A = sqrt(P)` and is then about `2 * sqrt(k * P)`. At four
//! thousand partitions that is a few hundred distances rather than four
//! thousand.
//!
//! This is SPANN's shape and not an invention: SPANN puts an SPTAG index over
//! its posting centroids for the same reason. The difference is that one level
//! of anchors is enough here, because `P` is already about `sqrt(n)` and the
//! square root of that is small enough that scanning it is free.
//!
//! # What it costs in answers
//!
//! The layer is approximate, in the same way and for the same reason the codes
//! under it are. An exact version is possible, by keeping a radius per anchor
//! and pruning on the triangle inequality, and it does not work: at a hundred
//! and twenty eight dimensions the distances concentrate enough that almost
//! nothing prunes, which is the ordinary curse of dimensionality and is why
//! every published index at this scale is approximate.
//!
//! So it is approximate and the compensation is over collection. A lookup walks
//! anchors until it has a few hundred candidates and the caller then ranks those
//! exactly, so the answer is only wrong when the true nearest centroid sits
//! under an anchor further away than every anchor holding a few hundred near
//! misses.
//!
//! # It never decides anything, and that is the whole design
//!
//! The first version of this was used everywhere a nearest centroid was wanted,
//! and it made the index ten times slower rather than faster. That is worth
//! writing down, because the reason is not obvious and it decides the shape of
//! everything here.
//!
//! With [`KEEP`] at 64 the layer looked at 75 centroids out of 619 and got the
//! nearest one wrong 11.4 percent of the time. Inside LIRE's sweep that is
//! ruinous. The sweep decides whether a member should move, and if the answer is
//! sometimes a partition that is not actually the nearest, members leak out of
//! partitions that then fall under the merge threshold, and the members they
//! leaked into push other partitions over the split threshold. It is a feedback
//! loop with nothing damping it: 199 splits became 9715 and 0 merges became
//! 9097.
//!
//! Placing a new vector has no such loop. The vector has no partition yet, so a
//! near miss costs one vector sitting in a partition next to the right one, and
//! nothing about that makes the next placement worse. That is a recall cost and
//! it is bounded and it is measurable, which the other one was not.
//!
//! So the line is not which call sites are allowed to use the layer, it is what
//! the answer is used for. Deciding where a member that already has a partition
//! should live has to be exact, and everything else can be approximate. That
//! puts three call sites on the layer. Placing a new vector, which is
//! [`Partitions::insert`](crate::Partitions::insert). Rehoming the members of a
//! partition a merge has just dissolved, which is the same question because
//! their partition has been taken away from them. And picking which partitions
//! a sweep should look in after a split, which is not a decision at all: every
//! member the sweep then visits is compared exactly against the centroids that
//! changed, so a neighbour the layer missed costs a few members not moving yet
//! and the next split in that neighbourhood picks them up. The sweep's own
//! comparison, the one the feedback loop above was about, is still exact and is
//! still against three centroids.
//!
//! The two maintenance sites are what pay for the layer at a high dimension, and
//! they are worth measuring apart because they are not the same size. Measured
//! by `examples/ingest.rs` at 1024 dimensions with posting 24 and replication
//! off, which builds 4849 partitions out of a hundred thousand vectors: 764
//! vectors a second overall with both exact, 1474 with only the merge on the
//! layer, and 2431 with the sweep's neighbour pick on it as well. Over the last
//! quarter of the run, which is the part that says what happens at a real size,
//! that is 558 then 1189 then 2298. The `touched` column does not move at any of
//! the three, so it is the same members being visited and only the lookup got
//! cheaper.
//!
//! The recall that costs is nothing that can be measured. On SIFT1M with one bit
//! codes at probe 128 and rerank 32, recall at 10 is 0.9898 with both exact and
//! 0.9919 with both on the layer, and across the patience settings the two
//! differ by two or three thousandths in each direction. The partition counts
//! come out at 6914 and 6880, so the sweep is genuinely making different
//! decisions and the answers are the same anyway, which is what the argument
//! above predicted.
//!
//! A search does not use it either, and that one was measured rather than
//! argued. Ranking every centroid is the fixed cost of every search, it is a
//! cost in the dimension rather than in the probe count, and on a thousand
//! dimensional embedding it is most of a short query: the MS-MARCO probe sweep
//! is a straight line of about 48 microseconds a partition with a 700
//! microsecond intercept, and the intercept is 2963 centroids at 1024
//! dimensions, which is twelve megabytes read per query. Picking the probe head
//! through the layer does take that intercept off, and the saving is real, 6891
//! microseconds down to 6289 at probe 128 on a 13900K. It also takes recall at
//! 10 from 0.8950 to 0.8312 there, and from 0.8516 to 0.7440 at probe 64,
//! because a shortlist that holds the nearest centroid nine times in ten is not
//! thereby a shortlist that holds the nearest hundred in the right order.
//! Widening the shortlist to fix that is paying the ranking back a piece at a
//! time. Ten percent of the latency for six to ten points of recall is the
//! wrong trade in the only direction anybody runs a vector index for, so a
//! search ranks the centroids itself and the intercept stays.
//!
//! That was measured again with a shortlist four times the probe count, which is
//! as wide as it can be asked to be before ranking it costs what ranking
//! everything costs, and it is still the wrong trade. On SIFT1M with 6880
//! partitions, one bit codes at probe 128 and rerank 32, recall at 10 goes from
//! 0.9898 to 0.9741, and with the probe pruning on top the three patience
//! settings go from 0.9912, 0.9936 and 0.9941 to 0.9714, 0.9738 and 0.9741. A
//! point and a half at 128 dimensions where MS-MARCO lost six at 1024, which is
//! the same finding twice: a shortlist that holds the nearest centroid holds the
//! nearest hundred in roughly the right order and roughly is not good enough
//! when the probe head is the whole answer.
//!
//! # When it is not there
//!
//! Below [`FLOOR`] partitions there is no layer and the caller scans. A few
//! hundred centroids is a few microseconds and the layer would only add its own
//! scan on top, so the collections where this could go wrong are exactly the
//! ones where it is not used. That also means every existing test, all of which
//! are well under the floor, measures the same code path it always did.
use cratesqdist;
/// How many partitions there have to be before a layer is worth having.
///
/// A lookup through the layer costs `sqrt(P)` anchors plus [`KEEP`] centroids,
/// so it only starts saving once `P` is comfortably past `KEEP`, and just above
/// the floor it is close to a wash: at 256 partitions the shortlist is every
/// centroid there is and the anchor scan is 16 distances on top. That is
/// deliberate. The floor is not where the saving begins, it is where the layer
/// stops being pure overhead, and a small collection is a few microseconds to
/// scan either way. What the floor really buys is that the collections where an
/// approximate placement could hurt recall the most, the ones with few enough
/// partitions that each one covers a lot of ground, do not use it at all.
pub const FLOOR: usize = 256;
/// The fewest candidates a lookup collects before it stops walking anchors.
///
/// A lookup for one centroid that stopped at the first anchor would be trusting
/// the anchor layer completely, which is the arrangement that turns a coarse
/// index into a recall problem. Collecting a few hundred and ranking them
/// exactly costs a few microseconds and means the layer only has to get the
/// neighbourhood right rather than the answer.
///
/// It is 256 rather than the 64 it started at because 64 was measured and it was
/// not good enough: at 595 partitions a shortlist of 75 got the nearest centroid
/// wrong 11.4 percent of the time, where 268 got it wrong 0.013 percent of the
/// time. That is the curse of dimensionality doing what it always does, and it
/// means the saving here is the 2.2x that comes of ranking half the centroids
/// rather than the 10x that a flat layer looks like it should give on paper. The
/// number that makes it worth having anyway is that the cost stops growing:
/// `KEEP` is a constant, so a lookup is `sqrt(P) + KEEP` distances at any size,
/// where the scan it replaces is `P`.
const KEEP: usize = 256;
/// The most anchors a lookup will walk.
///
/// An anchor holds about `sqrt(P)` centroids, so filling a shortlist of [`KEEP`]
/// takes `KEEP / sqrt(P)` of them, which is five at four thousand partitions and
/// falls as the collection grows. Sixteen is well past what that needs and the
/// cap is here so that the nearest anchors can be picked into a fixed array
/// instead of sorted into one that has to be allocated. Where the cap does bite,
/// which is a collection barely over [`FLOOR`], sixteen anchors is most of the
/// layer anyway.
const WALK: usize = 16;
/// How many times a rebuild moves the anchors to the middle of what they hold.
///
/// The anchors start as a stride sample of the centroids, which is a random
/// sample because the order centroids sit in is the order partitions split in
/// and that has nothing to do with where they are. A random sample is where
/// k-means starts and not where it finishes, and finishing it matters here more
/// than it looks like it should, because an anchor in the wrong place does not
/// just cost its own accuracy, it makes its neighbours hold the centroids it
/// should have had.
///
/// Measured on the shortlist test, which is a thousand centroids of uniform
/// noise in thirty two dimensions and is the hardest case there is for this: no
/// rounds finds the true nearest centroid 362 times in 500, one finds it 378,
/// two 394, three 400 and six 407, and after that it stops moving. Three is
/// where the curve flattens.
///
/// It costs `A * P` distances a round, so a rebuild at four thousand partitions
/// is about a million of them, which is tens of milliseconds, and rebuilds
/// happen when the partition count has moved a quarter, which is every quarter
/// million inserts. Amortised that is nothing. It is a stall rather than a cost,
/// and at ten million vectors it would be a stall worth removing, which is what
/// seeding a rebuild from the anchors it already has would do.
const ROUNDS: usize = 3;
/// The centroids, clustered.
pub