Skip to main content

legit_hamming/
kernel.rs

1//! The distance kernels: given a run of stored values, a query and a radius, push every position
2//! within the radius with its distance.
3//!
4//! Each kernel has a scalar body here, written once and compiled again inside each `x86` and `arm`
5//! wrapper with that path's instructions enabled, and hand-written vector bodies in those modules.
6//! The dispatchers below pick the body for an [`Isa`]; a path the CPU lacks falls back to the
7//! scalar body, so a kernel never runs an instruction the CPU doesn't have.
8
9#[cfg(target_arch = "aarch64")]
10mod arm;
11#[cfg(target_arch = "x86_64")]
12mod x86;
13
14use crate::cpu::Isa;
15
16/// One stored value within the radius: its position in the set searched and its distance from the
17/// query.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub struct Hit {
20    /// The value's position, counting from 0, in the set searched.
21    pub position: u32,
22    /// How many bits differ from the query.
23    pub distance: u32,
24}
25
26/// Scan one column of 64-bit values, the first at position `base`.
27pub(crate) fn scan64(isa: Isa, column: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
28    match isa {
29        #[cfg(target_arch = "x86_64")]
30        Isa::Popcnt | Isa::Avx2 | Isa::Avx512Bw | Isa::Avx512 => x86::scan64(isa, column, query, radius, base, out),
31        #[cfg(target_arch = "aarch64")]
32        Isa::Neon => arm::scan64(column, query, radius, base, out),
33        #[cfg(target_arch = "aarch64")]
34        Isa::NeonWide => arm::scan64_wide(column, query, radius, base, out),
35        _ => scalar::scan64(column, query, radius, base, out),
36    }
37}
38
39/// Scan four columns of equal length holding the words of 256-bit values, most significant first.
40pub(crate) fn scan256(isa: Isa, columns: [&[u64]; 4], query: [u64; 4], radius: u32, base: u32, out: &mut Vec<Hit>) {
41    let columns = scalar::equal(columns);
42    match isa {
43        #[cfg(target_arch = "x86_64")]
44        Isa::Popcnt | Isa::Avx2 | Isa::Avx512Bw | Isa::Avx512 => x86::scan256(isa, columns, query, radius, base, out),
45        #[cfg(target_arch = "aarch64")]
46        Isa::Neon | Isa::NeonWide => arm::scan256(columns, query, radius, base, out),
47        _ => scalar::scan256(columns, query, radius, base, out),
48    }
49}
50
51/// Scan records laid out one after another, `stride` words each, with the value's words at
52/// `offset` in the order `query` gives them.
53///
54/// This is the layout of a snapshot file: an id word, then the value.
55#[expect(
56    clippy::too_many_arguments,
57    reason = "the layout, query and output of one kernel call"
58)]
59pub(crate) fn scan_interleaved(
60    isa: Isa,
61    words: &[u64],
62    stride: usize,
63    offset: usize,
64    query: &[u64],
65    radius: u32,
66    base: u32,
67    out: &mut Vec<Hit>,
68) {
69    if stride == 1 && query.len() == 1 {
70        return scan64(isa, words, query[0], radius, base, out);
71    }
72    match isa {
73        #[cfg(target_arch = "x86_64")]
74        Isa::Popcnt | Isa::Avx2 | Isa::Avx512Bw | Isa::Avx512 => {
75            x86::scan_interleaved(isa, words, stride, offset, query, radius, base, out);
76        }
77        _ => scalar::scan_interleaved(words, stride, offset, query, radius, base, out),
78    }
79}
80
81/// The path [`scan_interleaved`] really runs when asked for `isa` on records of `stride` words,
82/// the value's `width` words starting at word `offset` of each: only some layouts have a kernel of
83/// their own on a vector path, and the rest run the `popcnt` kernel, or the scalar one.
84pub(crate) fn interleaved_path(isa: Isa, stride: usize, offset: usize, width: usize) -> Isa {
85    if stride == 1 && width == 1 {
86        return isa;
87    }
88    match isa {
89        #[cfg(target_arch = "x86_64")]
90        Isa::Avx512 if stride == 2 && offset == 1 && width == 1 => Isa::Avx512,
91        #[cfg(target_arch = "x86_64")]
92        Isa::Popcnt | Isa::Avx2 | Isa::Avx512Bw | Isa::Avx512 => Isa::Popcnt,
93        _ => {
94            let _ = offset;
95            Isa::Scalar
96        }
97    }
98}
99
100/// The scalar bodies. Each is `#[inline(always)]` so a wrapper with `popcnt` enabled compiles it
101/// with the instruction.
102pub(crate) mod scalar {
103    use super::Hit;
104
105    /// Check the four columns are the same length, and say so to the compiler...
106    #[inline(always)]
107    pub(crate) fn equal(columns: [&[u64]; 4]) -> [&[u64]; 4] {
108        let length = columns[0].len();
109        assert!(
110            columns.iter().all(|column| column.len() == length),
111            "the four columns have the same length"
112        );
113        columns.map(|column| &column[..length])
114    }
115
116    #[inline(always)]
117    pub(crate) fn scan64(column: &[u64], query: u64, radius: u32, base: u32, out: &mut Vec<Hit>) {
118        let (fours, rest) = column.as_chunks::<4>();
119        let mut position = base;
120        for four in fours {
121            let distances = [
122                (four[0] ^ query).count_ones(),
123                (four[1] ^ query).count_ones(),
124                (four[2] ^ query).count_ones(),
125                (four[3] ^ query).count_ones(),
126            ];
127            if distances[0].min(distances[1]).min(distances[2].min(distances[3])) <= radius {
128                for (lane, &distance) in (0u32..).zip(&distances) {
129                    if distance <= radius {
130                        out.push(Hit {
131                            position: position + lane,
132                            distance,
133                        });
134                    }
135                }
136            }
137            position += 4;
138        }
139        for (lane, &value) in (0u32..).zip(rest) {
140            let distance = (value ^ query).count_ones();
141            if distance <= radius {
142                out.push(Hit {
143                    position: position + lane,
144                    distance,
145                });
146            }
147        }
148    }
149
150    #[inline(always)]
151    pub(crate) fn scan256(columns: [&[u64]; 4], query: [u64; 4], radius: u32, base: u32, out: &mut Vec<Hit>) {
152        let [a, b, c, d] = columns;
153        for (position, (((&a, &b), &c), &d)) in (base..).zip(a.iter().zip(b).zip(c).zip(d)) {
154            let distance = (a ^ query[0]).count_ones()
155                + (b ^ query[1]).count_ones()
156                + (c ^ query[2]).count_ones()
157                + (d ^ query[3]).count_ones();
158            if distance <= radius {
159                out.push(Hit { position, distance });
160            }
161        }
162    }
163
164    #[inline(always)]
165    pub(crate) fn scan_interleaved(
166        words: &[u64],
167        stride: usize,
168        offset: usize,
169        query: &[u64],
170        radius: u32,
171        base: u32,
172        out: &mut Vec<Hit>,
173    ) {
174        let width = query.len();
175        for (position, record) in (base..).zip(words.chunks_exact(stride)) {
176            let value = &record[offset..offset + width];
177            let distance: u32 = value.iter().zip(query).map(|(a, b)| (a ^ b).count_ones()).sum();
178            if distance <= radius {
179                out.push(Hit { position, distance });
180            }
181        }
182    }
183}