legit-hamming 0.1.1

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
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
//! Multi-index hashing: one table per chunk of the value, probed with every key near the query's
//! chunk.

use std::sync::Arc;
use std::thread;

use crate::cpu::Isa;
use crate::error::{Error, Result};
use crate::kernel::Hit;
use crate::records::Records;
use crate::scan::scan_tiles;
use crate::search::{Clock, HitList, Memory, Plan, Planning, Search, Share, Stop, Strategy};
use crate::value::Value;

/// The largest distance that `chunks` chunks, each probed with every key within `chunk_radius`
/// bits, are sure to find: `chunks × (chunk_radius + 1) − 1`.
///
/// By the pigeonhole principle, two values that differ in at most that many bits differ in at most
/// `chunk_radius` bits in at least one chunk. Four 16-bit chunks probed exactly (`chunk_radius`
/// 0) find every pair to distance 3 and no further for certain.
///
/// ```
/// assert_eq!(legit_hamming::guaranteed_radius(4, 0), 3);
/// assert_eq!(legit_hamming::guaranteed_radius(16, 1), 31);
/// ```
#[must_use]
pub const fn guaranteed_radius(chunks: u32, chunk_radius: u32) -> u32 {
    chunks.saturating_mul(chunk_radius.saturating_add(1)).saturating_sub(1)
}

/// The radius to probe each chunk with so that a search finds every value within `radius`, for
/// `chunks` chunks: `None` for a chunk that needn't be probed at all. No chunks give no radii.
///
/// With `radius = chunks × q + s` and `0 ≤ s < chunks`, the first `s + 1` chunks are probed within
/// `q` bits and the others within `q − 1`, or not at all when `q` is 0. That is exact: a value
/// that escapes every probe differs in at least `q + 1` bits in each of the first `s + 1` chunks
/// and at least `q` in each other, `chunks × q + s + 1` in all, more than `radius`. It probes fewer
/// keys than giving every chunk `q`, which [`guaranteed_radius`] states.
///
/// ```
/// use legit_hamming::chunk_radii;
///
/// // Radius 8 over four chunks: 2 + 1 + 1 + 1, and one more bit than that escapes every probe.
/// assert_eq!(chunk_radii(4, 8), [Some(2), Some(1), Some(1), Some(1)]);
/// assert_eq!(chunk_radii(4, 1), [Some(0), Some(0), None, None]);
/// ```
#[must_use]
pub fn chunk_radii(chunks: u32, radius: u32) -> Vec<Option<u32>> {
    let Some(quotient) = radius.checked_div(chunks) else {
        return Vec::new();
    };
    let remainder = radius % chunks;
    (0..chunks)
        .map(|chunk| {
            if chunk <= remainder {
                Some(quotient)
            } else {
                quotient.checked_sub(1)
            }
        })
        .collect()
}

/// How many keys a search probes: for each chunk of `chunk_bits` bits probed within `r` bits, the
/// number of keys within `r` bits of a key, the sum of `C(chunk_bits, i)` for `i` from 0 to `r`.
/// Saturates at `u64::MAX` for chunks wider than the crate's tables.
///
/// ```
/// use legit_hamming::{chunk_radii, probes};
///
/// // Radius 8 over four 16-bit chunks: 137 keys in the first, 17 in each other.
/// assert_eq!(probes(16, &chunk_radii(4, 8)), 137 + 3 * 17);
/// ```
#[must_use]
pub fn probes(chunk_bits: u32, radii: &[Option<u32>]) -> u64 {
    radii
        .iter()
        .flatten()
        .map(|&radius| {
            (0..=radius.min(chunk_bits))
                .map(|i| binomial(chunk_bits, i))
                .fold(0u64, u64::saturating_add)
        })
        .fold(0, u64::saturating_add)
}

fn binomial(n: u32, k: u32) -> u64 {
    let mut result = 1u128;
    for i in 0..k {
        result = result * u128::from(n - i) / u128::from(i + 1);
    }
    u64::try_from(result).unwrap_or(u64::MAX)
}

/// The widest chunk a table indexes, in bits.
const MAX_CHUNK_BITS: u32 = 16;

/// Multi-index hashing (Norouzi, Punjani and Fleet, "Fast search in Hamming space with multi-index
/// hashing", CVPR 2012): the value is split into equal chunks, each with a table from the chunk's
/// key to the records that have it. A search probes each table with every key within that chunk's
/// radius of the query's chunk, from [`chunk_radii`], and checks each record found against the
/// whole query.
///
/// Exact at every radius: the per-chunk radii are sized so that the probes reach every record
/// within the radius, and a record reached from two tables is kept only from the first that
/// reaches it. Every record is in every table, under its own key, so records that share a value
/// are each found: nothing is deduplicated by value. Its cost is candidates, the table entries
/// read, which grows quickly with the radius. Where a search would probe at least as many keys as
/// there are records, so that a scan is sure to cost less, it scans instead, on
/// [`Isa::best_for`]; [`scans_at`](Self::scans_at) says when, and the candidates are then every
/// record. [`Planned`](crate::Planned) chooses between the two by an estimate of each instead.
///
/// A table is a direct array of `2^bits + 1` offsets into a list of positions, so it costs 4 bytes
/// a record a chunk, plus 256 KiB a chunk for 16-bit chunks: 16 bytes a record at 64 bits with 4
/// chunks, and 64 at 256 bits with 16. Chunk 0 is the most significant bits.
///
/// ```
/// use std::sync::Arc;
///
/// use legit_hamming::{MultiIndex, Options, Records, search};
///
/// let records = Arc::new(Records::from_records([(1, 0xffu64), (2, 0xfe), (3, u64::MAX)])?);
/// let index = MultiIndex::new(records, 4, 1)?;
/// let found = search(&index, 0xff, &Options::new(1));
/// assert_eq!(found.matches.iter().map(|m| m.id).collect::<Vec<_>>(), [Some(1), Some(2)]);
/// # Ok::<(), legit_hamming::Error>(())
/// ```
#[derive(Debug, Clone)]
pub struct MultiIndex<V> {
    records: Arc<Records<V>>,
    chunk_bits: u32,
    tables: Vec<Table>,
}

/// One chunk's table: the positions of every record, grouped by the chunk's key, and where each
/// key's group starts.
#[derive(Debug, Clone)]
struct Table {
    offsets: Vec<u32>,
    positions: Vec<u32>,
}

impl Table {
    fn postings(&self, key: u32) -> &[u32] {
        &self.positions[self.offsets[key as usize] as usize..self.offsets[key as usize + 1] as usize]
    }

    fn bucket_len(&self, key: u32) -> u64 {
        u64::from(self.offsets[key as usize + 1] - self.offsets[key as usize])
    }

    fn heap_bytes(&self) -> usize {
        (self.offsets.capacity() + self.positions.capacity()) * 4
    }
}

impl<V: Value> MultiIndex<V> {
    /// Build the tables over `records`, splitting each value into `chunks` chunks, one table a
    /// thread on up to `threads` threads.
    ///
    /// # Errors
    ///
    /// [`Error::ChunkCount`] unless the chunks are 1, 2, 4, 8 or 16 bits each: 4, 8, 16, 32 or 64
    /// chunks of a 64-bit value, and 16, 32, 64, 128 or 256 of a 256-bit one; and
    /// [`Error::OutOfMemory`] when the allocator won't give a table its memory.
    ///
    /// # Panics
    ///
    /// Panics if a thread building a table panics.
    pub fn new(records: Arc<Records<V>>, chunks: u32, threads: usize) -> Result<Self> {
        let chunk_bits = V::BITS.checked_div(chunks).unwrap_or(0);
        if chunk_bits == 0 || chunk_bits * chunks != V::BITS || chunk_bits > MAX_CHUNK_BITS || 64 % chunk_bits != 0 {
            return Err(Error::ChunkCount { chunks, bits: V::BITS });
        }
        // At least one table a batch, however many threads are asked for: a count past `u32`
        // must not narrow to none...
        let threads = u32::try_from(threads.max(1)).unwrap_or(u32::MAX);
        let mut tables = Vec::with_capacity(chunks as usize);
        let mut next = 0;
        while next < chunks {
            let batch = next..next.saturating_add(threads).min(chunks);
            let built: Vec<Table> = thread::scope(|scope| {
                let workers: Vec<_> = batch
                    .clone()
                    .map(|chunk| {
                        let records = &records;
                        scope.spawn(move || build_table(records, chunk, chunk_bits))
                    })
                    .collect();
                workers
                    .into_iter()
                    .map(|worker| worker.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic)))
                    .collect()
            });
            tables.extend(built);
            next = batch.end;
        }
        if tables.iter().any(|table: &Table| table.offsets.is_empty()) {
            return Err(Error::OutOfMemory {
                what: "the multi-index tables",
            });
        }
        Ok(Self {
            records,
            chunk_bits,
            tables,
        })
    }

    /// The bytes the tables of `chunks` chunks take over `records` records, beyond the records:
    /// 4 bytes a record a chunk, and `4 × (2^bits + 1)` a chunk for its offsets. `None` if
    /// `chunks` isn't a count [`new`](Self::new) takes.
    #[must_use]
    pub fn table_bytes(records: usize, chunks: u32) -> Option<usize> {
        let chunk_bits = V::BITS.checked_div(chunks)?;
        if chunk_bits == 0 || chunk_bits * chunks != V::BITS || chunk_bits > MAX_CHUNK_BITS || 64 % chunk_bits != 0 {
            return None;
        }
        let per_chunk = records.checked_add((1 << chunk_bits) + 1)?.checked_mul(4)?;
        per_chunk.checked_mul(chunks as usize)
    }

    /// The records the tables index.
    #[must_use]
    pub const fn records(&self) -> &Arc<Records<V>> {
        &self.records
    }

    /// How many chunks each value is split into.
    #[must_use]
    pub fn chunks(&self) -> u32 {
        self.tables.len() as u32
    }

    /// How many bits each chunk holds.
    #[must_use]
    pub const fn chunk_bits(&self) -> u32 {
        self.chunk_bits
    }

    /// The radius each chunk is probed with for a search within `radius`; see [`chunk_radii`].
    #[must_use]
    pub fn chunk_radii(&self, radius: u32) -> Vec<Option<u32>> {
        chunk_radii(self.chunks(), radius)
    }

    /// How many keys a search within `radius` probes; see [`probes`].
    #[must_use]
    pub fn probes(&self, radius: u32) -> u64 {
        probes(self.chunk_bits, &self.chunk_radii(radius))
    }

    /// Whether a search within `radius` scans every record rather than probing the tables: when
    /// it would probe at least as many keys as there are records.
    #[must_use]
    pub fn scans_at(&self, radius: u32) -> bool {
        self.probes(radius) >= self.records.len() as u64
    }

    /// Count what probing the tables for `query` within `radius` would cost: the keys looked up,
    /// and the entries those keys hold, read from the tables' offsets without reading a posting.
    /// Stops as soon as `enough(keys, candidates)` is true, and says whether it counted every key.
    pub(crate) fn count_probe(
        &self,
        query: &V,
        radius: u32,
        mut enough: impl FnMut(u64, u64) -> bool,
    ) -> (u64, u64, bool) {
        let radii = self.chunk_radii(radius);
        let (mut keys, mut candidates) = (0u64, 0u64);
        let mut counted = true;
        for (chunk, (table, chunk_radius)) in self.tables.iter().zip(&radii).enumerate() {
            let Some(chunk_radius) = *chunk_radius else { continue };
            for_each_key(
                chunk_of(query, chunk, self.chunk_bits),
                self.chunk_bits,
                chunk_radius,
                |key| {
                    keys += 1;
                    candidates += table.bucket_len(key);
                    if enough(keys, candidates) {
                        counted = false;
                        return false;
                    }
                    true
                },
            );
            if !counted {
                break;
            }
        }
        (keys, candidates, counted)
    }

    /// How many tables a search within `radius` probes.
    pub(crate) fn tables_probed(&self, radius: u32) -> usize {
        self.chunk_radii(radius).iter().flatten().count()
    }

    /// Probe the tables for this share of the queries, whatever the radius: shares split the
    /// queries when there are at least as many as shares, and the tables otherwise. Returns whether
    /// `stop` cut it short.
    pub(crate) fn probe(&self, queries: &[V], radius: u32, share: Share, stop: &Stop, out: &mut [HitList<'_>]) -> bool {
        let count = share.count.max(1);
        let tables = self.tables.len();
        if queries.len() >= count {
            for (index, (query, list)) in queries.iter().zip(out.iter_mut()).enumerate() {
                if index % count == share.index && self.search_one(query, radius, 0..tables, stop, list) {
                    return true;
                }
            }
        } else {
            for (query, list) in queries.iter().zip(out.iter_mut()) {
                let mine = (0..tables).filter(|table| table % count == share.index);
                if self.search_one(query, radius, mine, stop, list) {
                    return true;
                }
            }
        }
        false
    }

    fn search_one(
        &self,
        query: &V,
        radius: u32,
        tables: impl Iterator<Item = usize>,
        stop: &Stop,
        list: &mut HitList<'_>,
    ) -> bool {
        if stop.reached() {
            return true;
        }
        let radii = self.chunk_radii(radius);
        let query_chunks: Vec<u32> = (0..self.tables.len())
            .map(|chunk| chunk_of(query, chunk, self.chunk_bits))
            .collect();
        let mut clock = Clock::new(stop);
        for table in tables {
            let Some(chunk_radius) = radii[table] else { continue };
            let mut stopped = false;
            for_each_key(query_chunks[table], self.chunk_bits, chunk_radius, |key| {
                if clock.spend(Clock::KEY) {
                    stopped = true;
                    return false;
                }
                // A key can hold millions of records, such as a cluster of duplicates: read its
                // postings a block at a time, checking the deadline between blocks.
                for block in self.tables[table].postings(key).chunks(Clock::EVERY) {
                    list.candidates += block.len() as u64;
                    for &position in block {
                        let distance = self.records.value(position as usize).distance(query);
                        if distance <= radius && !self.reached_earlier(position, table, &radii, &query_chunks) {
                            list.push(Hit { position, distance });
                        }
                    }
                    if clock.spend(block.len()) {
                        stopped = true;
                        return false;
                    }
                }
                true
            });
            if stopped {
                return true;
            }
        }
        false
    }

    /// Whether a table before `table` reaches the record at `position`: whether its chunk there is
    /// within that table's radius of the query's.
    fn reached_earlier(&self, position: u32, table: usize, radii: &[Option<u32>], query_chunks: &[u32]) -> bool {
        let value = self.records.value(position as usize);
        (0..table).any(|earlier| {
            radii[earlier].is_some_and(|radius| {
                (chunk_of(&value, earlier, self.chunk_bits) ^ query_chunks[earlier]).count_ones() <= radius
            })
        })
    }
}

/// Chunk `chunk` of a value, counting from the most significant bits.
fn chunk_of<V: Value>(value: &V, chunk: usize, chunk_bits: u32) -> u32 {
    let bit = chunk * chunk_bits as usize;
    let shift = 64 - chunk_bits as usize - bit % 64;
    ((value.word(bit / 64) >> shift) & mask(chunk_bits)) as u32
}

const fn mask(bits: u32) -> u64 {
    if bits >= 64 { u64::MAX } else { (1 << bits) - 1 }
}

/// Call `visit` with every key within `radius` bits of `key`, in `bits` bits, until it returns
/// false.
fn for_each_key(key: u32, bits: u32, radius: u32, mut visit: impl FnMut(u32) -> bool) {
    let limit = 1u64 << bits;
    for flipped in 0..=radius.min(bits) {
        // Gosper's hack: every `bits`-bit mask with `flipped` bits set, in rising order...
        let mut flips: u64 = (1u64 << flipped) - 1;
        while flips < limit {
            if !visit(key ^ flips as u32) {
                return;
            }
            if flips == 0 {
                break;
            }
            let lowest = flips.isolate_lowest_one();
            let ripple = flips + lowest;
            flips = (((ripple ^ flips) >> 2) / lowest) | ripple;
        }
    }
}

fn build_table<V: Value>(records: &Records<V>, chunk: u32, chunk_bits: u32) -> Table {
    let bit = (chunk * chunk_bits) as usize;
    let column = records.column(bit / 64);
    let shift = 64 - chunk_bits as usize - bit % 64;
    let key = |word: u64| ((word >> shift) & mask(chunk_bits)) as usize;
    // Reserved fallibly: a table the allocator won't give is told, not an abort. An empty table,
    // which no built one is, marks it...
    let zeros = |count: usize| {
        let mut table = Vec::new();
        table.try_reserve_exact(count).ok()?;
        table.resize(count, 0u32);
        Some(table)
    };
    let (Some(mut offsets), Some(mut positions)) = (zeros((1 << chunk_bits) + 1), zeros(column.len())) else {
        return Table {
            offsets: Vec::new(),
            positions: Vec::new(),
        };
    };
    for &word in column {
        offsets[key(word) + 1] += 1;
    }
    for index in 1..offsets.len() {
        offsets[index] += offsets[index - 1];
    }
    let mut cursor = offsets.clone();
    for (position, &word) in (0u32..).zip(column) {
        let slot = &mut cursor[key(word)];
        positions[*slot as usize] = position;
        *slot += 1;
    }
    Table { offsets, positions }
}

impl<V: Value> Search<V> for MultiIndex<V> {
    fn variant(&self) -> String {
        format!("multi-index/{}x{}", self.chunks(), self.chunk_bits)
    }

    fn len(&self) -> usize {
        self.records.len()
    }

    fn has_ids(&self) -> bool {
        self.records.has_ids()
    }

    fn id(&self, position: usize) -> Option<u64> {
        self.records.id(position)
    }

    fn value(&self, position: usize) -> V {
        self.records.value(position)
    }

    fn memory(&self) -> Memory {
        Memory {
            records: self.records.heap_bytes(),
            index: self.tables.iter().map(Table::heap_bytes).sum(),
            mapped: 0,
        }
    }

    /// Shares split the queries when there are at least as many as shares, and the tables
    /// otherwise.
    fn collect(&self, queries: &[V], radius: u32, share: Share, stop: &Stop, out: &mut [HitList<'_>]) -> bool {
        if self.scans_at(radius) {
            let range = share.range(self.records.len());
            return scan_tiles(
                Isa::best_for::<V>(),
                &self.records,
                range,
                0,
                queries,
                radius,
                stop,
                out,
            );
        }
        self.probe(queries, radius, share, stop, out)
    }

    /// Every query the same way: a scan where [`scans_at`](Self::scans_at) says so, the tables
    /// otherwise, with no estimate, on every thread given.
    fn plan(&self, queries: &[V], radius: u32, threads: usize, _stop: &Stop) -> Planning {
        let strategy = if self.scans_at(radius) {
            Strategy::Scan
        } else {
            Strategy::MultiIndex
        };
        Planning::new(vec![Plan::new(strategy, None, false); queries.len()], threads)
    }
}