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
//! The x86-64 kernels: `popcnt`, AVX2, AVX-512 BW and AVX-512 with `VPOPCNTDQ`.
//!
//! The AVX2 and AVX-512 BW counts are the per-lane nibble lookup of Muła, Kurz and Lemire, "Faster population counts
//! using AVX2 instructions" (The Computer Journal 61.1, 2018; arXiv:1611.07612): each byte is split
//! into two nibbles, both are looked up in a 16-entry table with `vpshufb`, and `vpsadbw` against
//! zero sums the bytes of each 64-bit lane; AVX-512 BW does the same on 512-bit vectors, for CPUs
//! with AVX-512 but no `vpopcntq`. The paper's Harley-Seal adder tree isn't used: it sums
//! across a stream and can't give the per-record count a radius test needs.
//!
//! This module and `arm` are the only places, with `mapped`, where the crate uses `unsafe`. Every
//! function here with `#[target_feature]` is reached only through the safe wrappers at the top,
//! which check at run time that the CPU has the instructions and otherwise run the scalar body.

#![expect(
    unsafe_code,
    reason = "vector intrinsics need `#[target_feature]` calls and raw-pointer loads"
)]

use std::arch::x86_64::{
    __m256i, __m512i, _MM_HINT_T0, _mm_prefetch, _mm_setr_epi8, _mm256_add_epi8, _mm256_and_si256, _mm256_castsi256_pd,
    _mm256_cmpgt_epi64, _mm256_loadu_si256, _mm256_movemask_pd, _mm256_sad_epu8, _mm256_set1_epi8, _mm256_set1_epi64x,
    _mm256_setr_epi8, _mm256_setzero_si256, _mm256_shuffle_epi8, _mm256_srli_epi16, _mm256_storeu_si256,
    _mm256_xor_si256, _mm512_add_epi8, _mm512_add_epi64, _mm512_and_si512, _mm512_broadcast_i32x4,
    _mm512_cmple_epu64_mask, _mm512_loadu_epi64, _mm512_mask_cmple_epu64_mask, _mm512_popcnt_epi64, _mm512_sad_epu8,
    _mm512_set1_epi8, _mm512_set1_epi64, _mm512_setzero_si512, _mm512_shuffle_epi8, _mm512_srli_epi16,
    _mm512_storeu_epi64, _mm512_xor_si512,
};

use super::{Hit, scalar};
use crate::cpu::Isa;

pub(super) fn scan64(isa: Isa, column: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
    if !isa.is_available() {
        return scalar::scan64(column, query, radius, base, out);
    }
    // SAFETY: `is_available` has just confirmed the CPU runs every instruction `isa` enables
    // (AVX-512 checks `avx512f`, `avx512vpopcntdq` and `popcnt`; AVX-512 BW checks `avx512f`,
    // `avx512bw` and `popcnt`; AVX2 checks `avx2` and `popcnt`)...
    unsafe {
        match isa {
            Isa::Avx512 => scan64_avx512(column, query, radius, base, out),
            Isa::Avx512Bw => scan64_avx512bw(column, query, radius, base, out),
            Isa::Avx2 => scan64_avx2(column, query, radius, base, out),
            _ => scan64_popcnt(column, query, radius, base, out),
        }
    }
}

pub(super) fn scan256(isa: Isa, columns: [&[u64]; 4], query: [u64; 4], radius: u32, base: u32, out: &mut Vec<Hit>) {
    if !isa.is_available() {
        return scalar::scan256(columns, query, radius, base, out);
    }
    // SAFETY: as in `scan64`, the CPU has been checked for every instruction the path enables. The
    // vector bodies read `columns[w][i..i + n]` only for `i + n <= columns[0].len()`, and `equal`
    // has checked every column is that long...
    unsafe {
        match isa {
            Isa::Avx512 => scan256_avx512(columns, query, radius, base, out),
            Isa::Avx512Bw => scan256_avx512bw(columns, query, radius, base, out),
            Isa::Avx2 => scan256_avx2(columns, query, radius, base, out),
            _ => scan256_popcnt(columns, query, radius, base, out),
        }
    }
}

#[expect(
    clippy::too_many_arguments,
    reason = "the layout, query and output of one kernel call"
)]
pub(super) fn scan_interleaved(
    isa: Isa,
    words: &[u64],
    stride: usize,
    offset: usize,
    query: &[u64],
    radius: u32,
    base: u32,
    out: &mut Vec<Hit>,
) {
    if !isa.is_available() {
        return scalar::scan_interleaved(words, stride, offset, query, radius, base, out);
    }
    // SAFETY: as in `scan64`. The AVX-512 body reads `words[i..i + 8]` only for
    // `i + 8 <= words.len()`...
    unsafe {
        if isa == Isa::Avx512 && stride == 2 && offset == 1 && query.len() == 1 {
            scan_pairs_avx512(words, query[0], radius, base, out);
        } else {
            scan_interleaved_popcnt(words, stride, offset, query, radius, base, out);
        }
    }
}

#[target_feature(enable = "popcnt")]
fn scan64_popcnt(column: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
    scalar::scan64(column, query, radius, base, out);
}

#[target_feature(enable = "popcnt")]
fn scan256_popcnt(columns: [&[u64]; 4], query: [u64; 4], radius: u32, base: u32, out: &mut Vec<Hit>) {
    scalar::scan256(columns, query, radius, base, out);
}

#[target_feature(enable = "popcnt")]
fn scan_interleaved_popcnt(
    words: &[u64],
    stride: usize,
    offset: usize,
    query: &[u64],
    radius: u32,
    base: u32,
    out: &mut Vec<Hit>,
) {
    scalar::scan_interleaved(words, stride, offset, query, radius, base, out);
}

/// How far ahead the 512-bit 256-bit kernels prefetch each column, in records: one 64-byte line of
/// each column per eight-record step, 1 KiB ahead.
///
/// Measured on an Intel Xeon Gold 5412U scanning 10 million 256-bit records, radius 31, one
/// thread: 128 records ahead ran single queries 14% faster and batches of 1,000 29% faster than no
/// prefetch; 64 to 512 records ahead were within 3% of each other, and 2,048 gave back half the
/// gain. Four columns are four streams, more than the hardware prefetcher keeps ahead of on its
/// own.
const PREFETCH_RECORDS: usize = 128;

/// Ask for the line `PREFETCH_RECORDS` records past `index` of a column. A prefetch never faults,
/// so an address past the column's end is harmless, and the pointer is never read.
#[inline(always)]
fn prefetch(column: *const u64, index: usize) {
    // SAFETY: `_mm_prefetch` is a hint that reads nothing and can't fault on any address; SSE, its
    // instruction set, is part of x86-64...
    unsafe { _mm_prefetch::<_MM_HINT_T0>(column.wrapping_add(index + PREFETCH_RECORDS).cast()) };
}

/// Push the lanes of `distances` that `mask` marks, the first lane at `position`.
#[inline(always)]
fn emit512(distances: __m512i, mut mask: u8, position: u32, out: &mut Vec<Hit>) {
    let mut lanes = [0u64; 8];
    // SAFETY: `lanes` is 64 bytes, the width of the store, and an unaligned store needs no
    // alignment...
    unsafe { _mm512_storeu_epi64(lanes.as_mut_ptr().cast(), distances) };
    while mask != 0 {
        let lane = mask.trailing_zeros();
        out.push(Hit {
            position: position + lane,
            distance: lanes[lane as usize] as u32,
        });
        mask &= mask - 1;
    }
}

#[target_feature(enable = "avx512f,avx512vpopcntdq,popcnt")]
fn scan64_avx512(column: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
    let query_lanes = _mm512_set1_epi64(query as i64);
    let radius_lanes = _mm512_set1_epi64(i64::from(radius));
    let length = column.len();
    let pointer = column.as_ptr();
    let distance = |index: usize| {
        // SAFETY: every caller passes `index + 8 <= length`, so the 64 bytes read lie inside
        // `column`; the load is unaligned...
        let values = unsafe { _mm512_loadu_epi64(pointer.add(index).cast()) };
        _mm512_popcnt_epi64(_mm512_xor_si512(values, query_lanes))
    };
    let mut index = 0;
    while index + 32 <= length {
        let distances = [
            distance(index),
            distance(index + 8),
            distance(index + 16),
            distance(index + 24),
        ];
        let masks = distances.map(|lanes| _mm512_cmple_epu64_mask(lanes, radius_lanes));
        if masks.iter().any(|&mask| mask != 0) {
            for (step, (lanes, mask)) in (0u32..).zip(distances.into_iter().zip(masks)) {
                if mask != 0 {
                    emit512(lanes, mask, base + index as u32 + step * 8, out);
                }
            }
        }
        index += 32;
    }
    while index + 8 <= length {
        let lanes = distance(index);
        let mask = _mm512_cmple_epu64_mask(lanes, radius_lanes);
        if mask != 0 {
            emit512(lanes, mask, base + index as u32, out);
        }
        index += 8;
    }
    scalar::scan64(&column[index..], query, radius, base + index as u32, out);
}

#[target_feature(enable = "avx512f,avx512vpopcntdq,popcnt")]
fn scan256_avx512(columns: [&[u64]; 4], query: [u64; 4], radius: u32, base: u32, out: &mut Vec<Hit>) {
    let query_lanes = query.map(|word| _mm512_set1_epi64(word as i64));
    let radius_lanes = _mm512_set1_epi64(i64::from(radius));
    let length = columns[0].len();
    let pointers = columns.map(<[u64]>::as_ptr);
    let mut index = 0;
    while index + 8 <= length {
        let mut lanes = _mm512_setzero_si512();
        for word in 0..4 {
            prefetch(pointers[word], index);
            // SAFETY: `index + 8 <= length` and every column is `length` words long...
            let values = unsafe { _mm512_loadu_epi64(pointers[word].add(index).cast()) };
            lanes = _mm512_add_epi64(lanes, _mm512_popcnt_epi64(_mm512_xor_si512(values, query_lanes[word])));
        }
        let mask = _mm512_cmple_epu64_mask(lanes, radius_lanes);
        if mask != 0 {
            emit512(lanes, mask, base + index as u32, out);
        }
        index += 8;
    }
    scalar::scan256(
        columns.map(|column| &column[index..]),
        query,
        radius,
        base + index as u32,
        out,
    );
}

/// Records of two words, an id then a 64-bit value: the value is in the odd lanes, and the compare
/// is masked to them.
#[target_feature(enable = "avx512f,avx512vpopcntdq,popcnt")]
fn scan_pairs_avx512(words: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
    const ODD_LANES: u8 = 0b1010_1010;
    let query_lanes = _mm512_set1_epi64(query as i64);
    let radius_lanes = _mm512_set1_epi64(i64::from(radius));
    let length = words.len() / 2 * 2;
    let pointer = words.as_ptr();
    let mut index = 0;
    while index + 8 <= length {
        // SAFETY: `index + 8 <= length <= words.len()`...
        let values = unsafe { _mm512_loadu_epi64(pointer.add(index).cast()) };
        let lanes = _mm512_popcnt_epi64(_mm512_xor_si512(values, query_lanes));
        let mut mask = _mm512_mask_cmple_epu64_mask(ODD_LANES, lanes, radius_lanes);
        if mask != 0 {
            let mut distances = [0u64; 8];
            // SAFETY: `distances` is 64 bytes, the width of the store...
            unsafe { _mm512_storeu_epi64(distances.as_mut_ptr().cast(), lanes) };
            while mask != 0 {
                let lane = mask.trailing_zeros();
                let position = base + (index as u32 + lane) / 2;
                out.push(Hit {
                    position,
                    distance: distances[lane as usize] as u32,
                });
                mask &= mask - 1;
            }
        }
        index += 8;
    }
    scalar::scan_interleaved(
        &words[index..length],
        2,
        1,
        &[query],
        radius,
        base + index as u32 / 2,
        out,
    );
}

/// Per-byte bit counts of a vector, by the nibble lookup.
#[target_feature(enable = "avx2")]
fn count_bytes(values: __m256i) -> __m256i {
    let table = _mm256_setr_epi8(
        0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
    );
    let low_nibble = _mm256_set1_epi8(0x0f);
    let low = _mm256_and_si256(values, low_nibble);
    let high = _mm256_and_si256(_mm256_srli_epi16::<4>(values), low_nibble);
    _mm256_add_epi8(_mm256_shuffle_epi8(table, low), _mm256_shuffle_epi8(table, high))
}

/// The lanes of `distances` within `radius_lanes`, as a 4-bit mask.
#[target_feature(enable = "avx2")]
fn within256(distances: __m256i, radius_lanes: __m256i) -> u32 {
    // The counts are at most 256, so a signed compare is exact...
    let over = _mm256_cmpgt_epi64(distances, radius_lanes);
    !(_mm256_movemask_pd(_mm256_castsi256_pd(over)) as u32) & 0b1111
}

#[inline(always)]
fn emit256(distances: __m256i, mut mask: u32, position: u32, out: &mut Vec<Hit>) {
    let mut lanes = [0u64; 4];
    // SAFETY: `lanes` is 32 bytes, the width of the store; an unaligned store needs no alignment...
    unsafe { _mm256_storeu_si256(lanes.as_mut_ptr().cast(), distances) };
    while mask != 0 {
        let lane = mask.trailing_zeros();
        out.push(Hit {
            position: position + lane,
            distance: lanes[lane as usize] as u32,
        });
        mask &= mask - 1;
    }
}

#[target_feature(enable = "avx2,popcnt")]
fn scan64_avx2(column: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
    let query_lanes = _mm256_set1_epi64x(query as i64);
    let radius_lanes = _mm256_set1_epi64x(i64::from(radius));
    let zero = _mm256_setzero_si256();
    let length = column.len();
    let pointer = column.as_ptr();
    let distance = |index: usize| {
        // SAFETY: every caller passes `index + 4 <= length`, so the 32 bytes read lie inside
        // `column`; the load is unaligned...
        let values = unsafe { _mm256_loadu_si256(pointer.add(index).cast()) };
        _mm256_sad_epu8(count_bytes(_mm256_xor_si256(values, query_lanes)), zero)
    };
    let mut index = 0;
    while index + 8 <= length {
        let (first, second) = (distance(index), distance(index + 4));
        let (first_mask, second_mask) = (within256(first, radius_lanes), within256(second, radius_lanes));
        if first_mask | second_mask != 0 {
            emit256(first, first_mask, base + index as u32, out);
            emit256(second, second_mask, base + index as u32 + 4, out);
        }
        index += 8;
    }
    scalar::scan64(&column[index..], query, radius, base + index as u32, out);
}

#[target_feature(enable = "avx2,popcnt")]
fn scan256_avx2(columns: [&[u64]; 4], query: [u64; 4], radius: u32, base: u32, out: &mut Vec<Hit>) {
    let query_lanes = query.map(|word| _mm256_set1_epi64x(word as i64));
    let radius_lanes = _mm256_set1_epi64x(i64::from(radius));
    let zero = _mm256_setzero_si256();
    let length = columns[0].len();
    let pointers = columns.map(<[u64]>::as_ptr);
    let mut index = 0;
    while index + 4 <= length {
        // Each byte count is at most 8, so four of them summed per byte fit a byte...
        let mut bytes = zero;
        for word in 0..4 {
            // SAFETY: `index + 4 <= length` and every column is `length` words long...
            let values = unsafe { _mm256_loadu_si256(pointers[word].add(index).cast()) };
            bytes = _mm256_add_epi8(bytes, count_bytes(_mm256_xor_si256(values, query_lanes[word])));
        }
        let distances = _mm256_sad_epu8(bytes, zero);
        let mask = within256(distances, radius_lanes);
        if mask != 0 {
            emit256(distances, mask, base + index as u32, out);
        }
        index += 4;
    }
    scalar::scan256(
        columns.map(|column| &column[index..]),
        query,
        radius,
        base + index as u32,
        out,
    );
}

/// Per-byte bit counts of a 512-bit vector, by the nibble lookup: `count_bytes` on four times the
/// bytes.
#[target_feature(enable = "avx512f,avx512bw")]
fn count_bytes512(values: __m512i) -> __m512i {
    let table = _mm512_broadcast_i32x4(_mm_setr_epi8(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4));
    let low_nibble = _mm512_set1_epi8(0x0f);
    let low = _mm512_and_si512(values, low_nibble);
    let high = _mm512_and_si512(_mm512_srli_epi16::<4>(values), low_nibble);
    _mm512_add_epi8(_mm512_shuffle_epi8(table, low), _mm512_shuffle_epi8(table, high))
}

#[target_feature(enable = "avx512f,avx512bw,popcnt")]
fn scan64_avx512bw(column: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
    let query_lanes = _mm512_set1_epi64(query as i64);
    let radius_lanes = _mm512_set1_epi64(i64::from(radius));
    let zero = _mm512_setzero_si512();
    let length = column.len();
    let pointer = column.as_ptr();
    let distance = |index: usize| {
        // SAFETY: every caller passes `index + 8 <= length`, so the 64 bytes read lie inside
        // `column`; the load is unaligned...
        let values = unsafe { _mm512_loadu_epi64(pointer.add(index).cast()) };
        _mm512_sad_epu8(count_bytes512(_mm512_xor_si512(values, query_lanes)), zero)
    };
    let mut index = 0;
    while index + 32 <= length {
        let distances = [
            distance(index),
            distance(index + 8),
            distance(index + 16),
            distance(index + 24),
        ];
        let masks = distances.map(|lanes| _mm512_cmple_epu64_mask(lanes, radius_lanes));
        if masks.iter().any(|&mask| mask != 0) {
            for (step, (lanes, mask)) in (0u32..).zip(distances.into_iter().zip(masks)) {
                if mask != 0 {
                    emit512(lanes, mask, base + index as u32 + step * 8, out);
                }
            }
        }
        index += 32;
    }
    while index + 8 <= length {
        let lanes = distance(index);
        let mask = _mm512_cmple_epu64_mask(lanes, radius_lanes);
        if mask != 0 {
            emit512(lanes, mask, base + index as u32, out);
        }
        index += 8;
    }
    scalar::scan64(&column[index..], query, radius, base + index as u32, out);
}

#[target_feature(enable = "avx512f,avx512bw,popcnt")]
fn scan256_avx512bw(columns: [&[u64]; 4], query: [u64; 4], radius: u32, base: u32, out: &mut Vec<Hit>) {
    let query_lanes = query.map(|word| _mm512_set1_epi64(word as i64));
    let radius_lanes = _mm512_set1_epi64(i64::from(radius));
    let zero = _mm512_setzero_si512();
    let length = columns[0].len();
    let pointers = columns.map(<[u64]>::as_ptr);
    let mut index = 0;
    while index + 8 <= length {
        // Each byte count is at most 8, so four of them summed per byte fit a byte...
        let mut bytes = zero;
        for word in 0..4 {
            prefetch(pointers[word], index);
            // SAFETY: `index + 8 <= length` and every column is `length` words long...
            let values = unsafe { _mm512_loadu_epi64(pointers[word].add(index).cast()) };
            bytes = _mm512_add_epi8(bytes, count_bytes512(_mm512_xor_si512(values, query_lanes[word])));
        }
        let lanes = _mm512_sad_epu8(bytes, zero);
        let mask = _mm512_cmple_epu64_mask(lanes, radius_lanes);
        if mask != 0 {
            emit512(lanes, mask, base + index as u32, out);
        }
        index += 8;
    }
    scalar::scan256(
        columns.map(|column| &column[index..]),
        query,
        radius,
        base + index as u32,
        out,
    );
}