Skip to main content

vortex_array/stats/
majority.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! The majority candidate of a slice: the value filling more than half of its valid positions,
5//! if there is one.
6//!
7//! A [Boyer–Moore majority vote] finds such a value with comparisons alone. It keeps one
8//! candidate and a counter, increments the counter on a match, decrements it otherwise, and
9//! replaces the candidate when the counter is zero. A value filling more than half of the input
10//! survives as the candidate, because every decrement pairs off two different values and each
11//! pair holds at most one copy of it.
12//!
13//! The vote is a mergeable summary: votes over disjoint parts of the input combine into a vote
14//! over all of it, with the same guarantee. Sixteen independent votes therefore run over
15//! interleaved elements, which removes the loop-carried dependency of a single vote and lets the
16//! compiler keep the lanes in vector registers. Without a majority the candidate is an arbitrary
17//! valid value, so callers that need to tell the cases apart count it afterwards.
18//!
19//! [`fearless_simd`] compiles the loops once per instruction set level, such as AVX2 or NEON,
20//! and selects one for the current CPU at runtime. LLVM vectorizes each of them.
21//!
22//! [Boyer–Moore majority vote]: https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
23
24use fearless_simd::Level;
25use fearless_simd::Simd;
26use fearless_simd::dispatch;
27use fearless_simd_macros::simd;
28use vortex_buffer::BitBuffer;
29use vortex_mask::Mask;
30
31use crate::dtype::NativePType;
32use crate::dtype::half::f16;
33use crate::dtype::i256;
34
35/// The number of independent votes run over interleaved elements.
36const LANES: usize = 16;
37
38/// The most values voted on with `u32` lane counters before the votes are merged into a `usize`
39/// one. A multiple of 64, so each chunk's validity starts on a word.
40const CHUNK_LEN: usize = 1 << 31;
41
42/// A fixed-width value that a majority vote compares for equality.
43///
44/// The comparison must be an equivalence relation. Floats compare by bit pattern, as in
45/// [`NativePType::is_eq`], so every NaN payload is its own value and `-0.0` differs from `0.0`.
46pub trait MajorityKey: Copy + Default {
47    /// Returns whether the two values are the same value.
48    fn key_eq(self, other: Self) -> bool;
49}
50
51macro_rules! native_majority_key {
52    ($($T:ty),*) => {
53        $(
54            impl MajorityKey for $T {
55                #[inline]
56                fn key_eq(self, other: Self) -> bool {
57                    NativePType::is_eq(self, other)
58                }
59            }
60        )*
61    };
62}
63
64native_majority_key!(u8, u16, u32, u64, i8, i16, i32, i64, f16, f32, f64);
65
66/// Fixed-size byte strings, such as UUIDs or the 16-byte views of variable-length strings.
67impl<const N: usize> MajorityKey for [u8; N]
68where
69    [u8; N]: Default,
70{
71    #[inline]
72    fn key_eq(self, other: Self) -> bool {
73        self == other
74    }
75}
76
77impl MajorityKey for i128 {
78    #[inline]
79    fn key_eq(self, other: Self) -> bool {
80        self == other
81    }
82}
83
84impl MajorityKey for i256 {
85    #[inline]
86    fn key_eq(self, other: Self) -> bool {
87        self == other
88    }
89}
90
91/// Runs a Boyer–Moore vote over the valid `values` and returns its candidate.
92///
93/// The candidate is the value filling more than half of the valid positions whenever there is
94/// one. Otherwise it is some valid value; callers that need to know which case they have count it,
95/// for example with an equality comparison. `validity` must have the same length as `values`.
96/// Returns `None` only when no position is valid.
97pub fn majority_candidate<T: MajorityKey>(values: &[T], validity: &Mask) -> Option<T> {
98    dispatch!(Level::new(), simd => majority_candidate_simd(simd, values, validity))
99}
100
101/// The vote, compiled with the target features of `simd`.
102///
103/// The loops below are plain Rust, inlined here so that each level's instantiation compiles them
104/// with its features. The x86-64 baseline has no 64-bit vector compare, so without a higher level
105/// LLVM keeps 64-bit keys in scalar code.
106#[simd]
107fn majority_candidate_simd<S: Simd, T: MajorityKey>(
108    _: S,
109    values: &[T],
110    validity: &Mask,
111) -> Option<T> {
112    let first_valid = match validity {
113        Mask::AllTrue(len) => (*len > 0).then_some(0)?,
114        Mask::AllFalse(_) => return None,
115        Mask::Values(mask_values) => mask_values.bit_buffer().set_indices().next()?,
116    };
117    let mut merged = (T::default(), 0usize);
118    for (index, chunk) in values.chunks(CHUNK_LEN).enumerate() {
119        let start = index * CHUNK_LEN;
120        let vote = match validity {
121            Mask::Values(mask_values) => masked_lane_vote(
122                chunk,
123                &mask_values.bit_buffer().slice(start..start + chunk.len()),
124            ),
125            _ => lane_vote(chunk),
126        };
127        merged = merge_vote(merged, (vote.0, vote.1 as usize));
128    }
129    // A majority keeps a positive surplus. Without one, every vote may cancel out and leave the
130    // fold's default, which need not occur at all, so any valid value will do.
131    Some(if merged.1 > 0 {
132        merged.0
133    } else {
134        values[first_valid]
135    })
136}
137
138/// One step of a vote over a valid value, written without branches so the lanes vectorize.
139#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
140#[inline(always)]
141fn vote<T: MajorityKey>(candidate: &mut T, count: &mut u32, value: T) {
142    let empty = *count == 0;
143    let agrees = candidate.key_eq(value);
144    *candidate = if empty { value } else { *candidate };
145    *count = if empty | agrees {
146        *count + 1
147    } else {
148        *count - 1
149    };
150}
151
152/// One step of a vote that skips invalid values. Arithmetic rather than selects on the count
153/// vectorizes better once validity is involved.
154#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
155#[inline(always)]
156fn masked_vote<T: MajorityKey>(candidate: &mut T, count: &mut u32, value: T, valid: bool) {
157    let empty = *count == 0;
158    let agrees = candidate.key_eq(value);
159    *candidate = if valid & empty { value } else { *candidate };
160    let up = valid & (empty | agrees);
161    let down = valid & !(empty | agrees);
162    *count = *count + u32::from(up) - u32::from(down);
163}
164
165/// Merges two votes over disjoint parts of the input into a vote over both.
166///
167/// Merging votes for different candidates pairs off the smaller surplus against the larger, so a
168/// value filling more than half of the input still cannot be paired off entirely. A vote that saw
169/// no value has a zero surplus and merges as a no-op.
170#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
171#[inline(always)]
172fn merge_vote<
173    T: MajorityKey,
174    C: Copy + Ord + std::ops::Add<Output = C> + std::ops::Sub<Output = C>,
175>(
176    (candidate, count): (T, C),
177    (other, other_count): (T, C),
178) -> (T, C) {
179    if candidate.key_eq(other) {
180        (candidate, count + other_count)
181    } else if count >= other_count {
182        (candidate, count - other_count)
183    } else {
184        (other, other_count - count)
185    }
186}
187
188/// Merges the per-lane votes into one.
189fn merge_lanes<T: MajorityKey>(candidates: [T; LANES], counts: [u32; LANES]) -> (T, u32) {
190    candidates
191        .into_iter()
192        .zip(counts)
193        .fold((T::default(), 0), merge_vote)
194}
195
196#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
197#[inline(always)]
198fn lane_vote<T: MajorityKey>(values: &[T]) -> (T, u32) {
199    let mut candidates = [T::default(); LANES];
200    let mut counts = [0u32; LANES];
201    let (chunks, remainder) = values.as_chunks::<LANES>();
202    for chunk in chunks {
203        for lane in 0..LANES {
204            vote(&mut candidates[lane], &mut counts[lane], chunk[lane]);
205        }
206    }
207    for (lane, &value) in remainder.iter().enumerate() {
208        vote(&mut candidates[lane], &mut counts[lane], value);
209    }
210    merge_lanes(candidates, counts)
211}
212
213#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
214#[inline(always)]
215fn masked_lane_vote<T: MajorityKey>(values: &[T], validity: &BitBuffer) -> (T, u32) {
216    let mut candidates = [T::default(); LANES];
217    let mut counts = [0u32; LANES];
218    let mut words = validity.chunks().iter_padded();
219    let (chunks, remainder) = values.as_chunks::<64>();
220    for (chunk, bits) in chunks.iter().zip(&mut words) {
221        for block in 0..64 / LANES {
222            for lane in 0..LANES {
223                let index = block * LANES + lane;
224                let valid = (bits >> index) & 1 == 1;
225                masked_vote(
226                    &mut candidates[lane],
227                    &mut counts[lane],
228                    chunk[index],
229                    valid,
230                );
231            }
232        }
233    }
234    let bits = words.next().unwrap_or(0);
235    for (index, &value) in remainder.iter().enumerate() {
236        let valid = (bits >> index) & 1 == 1;
237        masked_vote(
238            &mut candidates[index % LANES],
239            &mut counts[index % LANES],
240            value,
241            valid,
242        );
243    }
244    merge_lanes(candidates, counts)
245}
246
247#[cfg(test)]
248mod tests {
249    use rstest::rstest;
250
251    use super::*;
252
253    #[rstest]
254    #[case::shorter_than_lanes(7)]
255    #[case::not_a_multiple_of_64(1_001)]
256    fn wide_keys(#[case] len: usize) {
257        let values: Vec<i256> = (0..len)
258            .map(|index| {
259                if index % 3 == 0 {
260                    i256::from_i128(index as i128)
261                } else {
262                    i256::MAX
263                }
264            })
265            .collect();
266        assert_eq!(
267            majority_candidate(&values, &Mask::new_true(len)),
268            Some(i256::MAX)
269        );
270    }
271
272    #[test]
273    fn fixed_size_bytes() {
274        let values: Vec<[u8; 16]> = (0u8..100)
275            .map(|index| {
276                if index % 4 == 0 {
277                    [index; 16]
278                } else {
279                    *b"0123456789abcdef"
280                }
281            })
282            .collect();
283        assert_eq!(
284            majority_candidate(&values, &Mask::new_true(values.len())),
285            Some(*b"0123456789abcdef")
286        );
287    }
288
289    /// Every lane's vote cancels out, which leaves the fold's default, absent from the input.
290    #[rstest]
291    #[case::all_valid(Mask::new_true(32))]
292    #[case::nullable(Mask::from_iter((0..32).map(|index| index % 2 == 1)))]
293    fn cancelled_votes_return_a_valid_value(#[case] validity: Mask) {
294        let values: Vec<u32> = (1..=32).collect();
295        let candidate = majority_candidate(&values, &validity).expect("values are valid");
296        let index = values.iter().position(|&value| value == candidate);
297        assert!(index.is_some_and(|index| validity.value(index)));
298    }
299
300    #[test]
301    fn nothing_valid() {
302        assert_eq!(majority_candidate::<u32>(&[], &Mask::new_true(0)), None);
303        assert_eq!(majority_candidate(&[5u32; 10], &Mask::new_false(10)), None);
304    }
305
306    /// Zero fills most positions, but most zeros are invalid, so nine is the majority.
307    #[rstest]
308    #[case::short(40)]
309    #[case::long(8_000)]
310    fn invalid_values_do_not_vote(#[case] len: usize) {
311        let values: Vec<u64> = (0..len)
312            .map(|index| if index % 8 < 3 { 9 } else { 0 })
313            .collect();
314        let validity = Mask::from_iter((0..len).map(|index| index % 8 < 4));
315        assert_eq!(majority_candidate(&values, &validity), Some(9));
316    }
317}