Skip to main content

zu_vector/kernels/
setops.rs

1//! Sorted-set intersection, the worst-case-optimal join inner loop
2//! (perf/11). Neighbor lists come out of the CSR sorted, so multiway
3//! intersection is repeated pairwise intersection of sorted u64 runs.
4//!
5//! Balanced inputs take the branchy merge, which the branch predictor
6//! handles well on real adjacency data. Once one side is 32x longer the
7//! merge wastes its time stepping the long side, so the short side
8//! drives and the long side is galloped: doubling probe from the cursor,
9//! then a binary search inside the last doubling window.
10
11/// Length ratio at which galloping beats the merge. Measured, not
12/// sacred; the crossover is flat between 16 and 64.
13const GALLOP_RATIO: usize = 32;
14
15/// Below this short-side length the split's partition search and the
16/// tail compaction cost more than the overlap buys.
17const SPLIT_MIN: usize = 64;
18
19/// Intersect two sorted, duplicate-free slices into `out`, returning the
20/// element count. `out` must hold at least `min(a.len(), b.len())`.
21pub fn intersect_sorted(a: &[u64], b: &[u64], out: &mut [u64]) -> usize {
22    // Keep the short side in `a` so the gallop test is one direction.
23    let (a, b) = if a.len() <= b.len() { (a, b) } else { (b, a) };
24    if a.is_empty() {
25        return 0;
26    }
27    if b.len() / a.len() >= GALLOP_RATIO {
28        return gallop_intersect(a, b, out);
29    }
30    if a.len() >= 4 * SPLIT_MIN {
31        return split_merge::<4>(a, b, out);
32    }
33    if a.len() >= SPLIT_MIN {
34        return split_merge::<2>(a, b, out);
35    }
36    merge(a, b, out)
37}
38
39/// The plain branch-free merge. Its throughput ceiling is the
40/// loop-carried load-compare-add chain on the cursors, about six cycles
41/// per step, which is why `split_merge` exists.
42fn merge(a: &[u64], b: &[u64], out: &mut [u64]) -> usize {
43    let mut n = 0;
44    let (mut i, mut j) = (0, 0);
45    while i < a.len() && j < b.len() {
46        let (x, y) = (a[i], b[j]);
47        out[n] = x;
48        n += usize::from(x == y);
49        i += usize::from(x <= y);
50        j += usize::from(y <= x);
51    }
52    n
53}
54
55/// Cut the short side into N equal segments, partition the long side at
56/// the segment pivots, and run the N independent merges interleaved in
57/// one loop. The cursor chains of the segments carry no dependence on
58/// each other, so they overlap in the out-of-order window and the merge
59/// scales close to N-fold until the execution ports saturate.
60fn split_merge<const N: usize>(a: &[u64], b: &[u64], out: &mut [u64]) -> usize {
61    // Segment k of a is [ca[k], ca[k+1]); its partner in b holds exactly
62    // the values in that pivot range, so segments cannot match across
63    // the cuts (sorted, duplicate-free inputs).
64    let mut ca = [0usize; N];
65    let mut cb = [0usize; N];
66    let mut ca_end = [0usize; N];
67    let mut cb_end = [0usize; N];
68    for k in 0..N {
69        ca[k] = a.len() * k / N;
70        ca_end[k] = a.len() * (k + 1) / N;
71        cb[k] = if k == 0 {
72            0
73        } else {
74            b.partition_point(|&y| y < a[ca[k]])
75        };
76    }
77    cb_end[..N - 1].copy_from_slice(&cb[1..]);
78    cb_end[N - 1] = b.len();
79    // Segment k writes into out at [off[k], off[k] + its match count).
80    // Match count is bounded by min of the segment lengths, and those
81    // bounds sum to at most min(|a|, |b|) <= out.len(), so the segments
82    // never collide; the gaps compact away at the end.
83    let mut off = [0usize; N];
84    for k in 1..N {
85        off[k] = off[k - 1] + (ca_end[k - 1] - ca[k - 1]).min(cb_end[k - 1] - cb[k - 1]);
86    }
87    let mut i = ca;
88    let mut j = cb;
89    let mut n = off;
90    loop {
91        let mut all_active = true;
92        for k in 0..N {
93            all_active &= i[k] < ca_end[k] && j[k] < cb_end[k];
94        }
95        if !all_active {
96            break;
97        }
98        for k in 0..N {
99            let (x, y) = (a[i[k]], b[j[k]]);
100            out[n[k]] = x;
101            n[k] += usize::from(x == y);
102            i[k] += usize::from(x <= y);
103            j[k] += usize::from(y <= x);
104        }
105    }
106    for k in 0..N {
107        let cap = if k == N - 1 { out.len() } else { off[k + 1] };
108        n[k] += merge(
109            &a[i[k]..ca_end[k]],
110            &b[j[k]..cb_end[k]],
111            &mut out[n[k]..cap],
112        );
113    }
114    // Compact the segment outputs together, front to back.
115    let mut total = n[0];
116    for k in 1..N {
117        let found = n[k] - off[k];
118        out.copy_within(off[k]..n[k], total);
119        total += found;
120    }
121    total
122}
123
124fn gallop_intersect(short: &[u64], long: &[u64], out: &mut [u64]) -> usize {
125    let mut n = 0;
126    let mut lo = 0usize;
127    for &x in short {
128        // Double until the window covers x, then binary search inside.
129        let mut step = 1usize;
130        while lo + step < long.len() && long[lo + step] < x {
131            step *= 2;
132        }
133        let hi = (lo + step + 1).min(long.len());
134        match long[lo..hi].binary_search(&x) {
135            Ok(off) => {
136                out[n] = x;
137                n += 1;
138                lo += off + 1;
139            }
140            Err(off) => lo += off,
141        }
142        if lo >= long.len() {
143            break;
144        }
145    }
146    n
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    fn naive(a: &[u64], b: &[u64]) -> Vec<u64> {
154        a.iter().filter(|x| b.contains(x)).copied().collect()
155    }
156
157    #[test]
158    fn merge_path() {
159        let a = [1u64, 3, 5, 7, 9, 11];
160        let b = [2u64, 3, 4, 7, 8, 11, 20];
161        let mut out = [0u64; 6];
162        let n = intersect_sorted(&a, &b, &mut out);
163        assert_eq!(&out[..n], &[3, 7, 11]);
164    }
165
166    #[test]
167    fn gallop_path_matches_naive() {
168        // Long side 64x the short side forces the gallop.
169        let long: Vec<u64> = (0..6400).map(|i| i * 3).collect();
170        let short: Vec<u64> = (0..100).map(|i| i * 191).collect();
171        let mut out = vec![0u64; short.len()];
172        let n = intersect_sorted(&short, &long, &mut out);
173        assert_eq!(&out[..n], naive(&short, &long).as_slice());
174        // Argument order must not matter.
175        let mut out2 = vec![0u64; short.len()];
176        let n2 = intersect_sorted(&long, &short, &mut out2);
177        assert_eq!(&out[..n], &out2[..n2]);
178    }
179
180    #[test]
181    fn empty_and_disjoint() {
182        let mut out = [0u64; 4];
183        assert_eq!(intersect_sorted(&[], &[1, 2], &mut out), 0);
184        assert_eq!(intersect_sorted(&[3, 4], &[1, 2], &mut out), 0);
185    }
186}