From cc26810de28f4a08cbdb49eeffc86519dc663e78 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Mon, 30 Nov 2026 00:30:21 +0000 Subject: [PATCH] Add PIVCO compute pushdown kernels and fused ZigZag execution Adds direct spine-walking CompareKernel predicate pushdown, block-skipping SliceReduce, FilterKernel, TakeExecute, and fused ZigZag(Pivco) parent execution, verified via Hegel check_encoding_roundtrip_and_ops and ZigZag(Pivco) property tests. Co-Authored-By: Antigravity Signed-off-by: Will Manning --- Cargo.lock | 1 + encodings/pivco/Cargo.toml | 1 + encodings/pivco/src/array.rs | 149 +++++- encodings/pivco/src/codec/mod.rs | 2 + encodings/pivco/src/codec/spine.rs | 444 +++++++++++++++++ encodings/pivco/src/compute.rs | 752 +++++++++++++++++++++++++++++ encodings/pivco/src/lib.rs | 37 +- encodings/pivco/src/simd/mod.rs | 45 ++ encodings/pivco/src/simd/neon.rs | 26 + encodings/pivco/src/simd/x86.rs | 12 + encodings/pivco/src/tests.rs | 272 +++++++++++ 11 files changed, 1730 insertions(+), 11 deletions(-) create mode 100644 encodings/pivco/src/codec/spine.rs create mode 100644 encodings/pivco/src/compute.rs diff --git a/Cargo.lock b/Cargo.lock index e3f8951972c..cf76f1c7b0d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12212,6 +12212,7 @@ dependencies = [ "vortex-error", "vortex-mask", "vortex-session", + "vortex-zigzag", ] [[package]] diff --git a/encodings/pivco/Cargo.toml b/encodings/pivco/Cargo.toml index 543cb3ae3e5..d7979c8a55f 100644 --- a/encodings/pivco/Cargo.toml +++ b/encodings/pivco/Cargo.toml @@ -25,6 +25,7 @@ vortex-buffer = { workspace = true } vortex-error = { workspace = true } vortex-mask = { workspace = true } vortex-session = { workspace = true } +vortex-zigzag = { workspace = true } [dev-dependencies] hegeltest = { workspace = true } diff --git a/encodings/pivco/src/array.rs b/encodings/pivco/src/array.rs index bcb7b781263..0e97b1cf8a1 100644 --- a/encodings/pivco/src/array.rs +++ b/encodings/pivco/src/array.rs @@ -4,14 +4,13 @@ //! [`Pivco`] array definition, [`PivcoData`] encapsulated operations, [`VTable`], //! [`ValidityVTable`], and [`OperationsVTable`]. -#![cfg_attr(test, expect(clippy::cast_possible_truncation))] +#![expect(clippy::cast_possible_truncation)] use std::fmt::Display; use std::fmt::Formatter; use std::hash::Hash; use std::hash::Hasher; use std::mem::MaybeUninit; -#[cfg(test)] use std::ops::Range; use std::sync::Arc; @@ -39,6 +38,7 @@ use vortex_array::match_each_integer_ptype; use vortex_array::require_validity; use vortex_array::scalar::PValue; use vortex_array::scalar::Scalar; +use vortex_array::scalar_fn::builtin::operators::CompareOperator; use vortex_array::validity::Validity; use vortex_array::vtable::OperationsVTable; use vortex_array::vtable::VTable; @@ -46,6 +46,7 @@ use vortex_array::vtable::ValidityVTable; use vortex_array::vtable::child_to_validity; use vortex_array::vtable::validity_to_child; use vortex_buffer::Alignment; +use vortex_buffer::BitBuffer; use vortex_buffer::BufferMut; use vortex_buffer::ByteBufferMut; use vortex_error::VortexResult; @@ -61,9 +62,11 @@ use crate::codec::MAX_BLOCK_SHIFT; use crate::codec::MIN_BLOCK_SHIFT; use crate::codec::PivcoBlockOffset; use crate::codec::PivcoOptions; +use crate::codec::RankPredicate; use crate::codec::block_header_stride; use crate::codec::encode_primitive_slice; use crate::codec::validate_block_headers; +use crate::pow2_bin::encode_pow2_bin; use crate::pow2_bin::max_nonneg_u64; use crate::pow2_bin::sym_max_value; use crate::tree::EMPTY_TREE_BYTES; @@ -128,6 +131,14 @@ pub struct PivcoData { raw_bits: BufferHandle, } +/// Result of evaluating a direct spine-walking constant comparison on [`PivcoData`]. +pub(crate) enum ConstantCompareResult { + /// Constant boolean result for all valid elements. + Constant(bool), + /// Per-element packed bitmap result. + Bits(BitBuffer), +} + /// Host-pinned reusable multi-block decoder for a [`PivcoData`] chunk. pub(crate) struct PivcoBlockDecoder<'a> { reader: BlockReader<'a>, @@ -164,6 +175,16 @@ impl<'a> PivcoBlockDecoder<'a> { map_out, ) } + + /// Decodes a single element `(block_idx, pos_in_block)` via top-down `O(depth)` point access. + #[inline] + pub(crate) fn decode_value_at( + &self, + block_idx: usize, + pos_in_block: usize, + ) -> VortexResult { + self.reader.decode_value_at(block_idx, pos_in_block) + } } impl Display for PivcoData { @@ -719,7 +740,6 @@ impl PivcoData { Ok(PrimitiveArray::new(out.freeze(), validity)) } - #[cfg(test)] pub(crate) fn slice(&self, len: usize, range: Range) -> VortexResult { let block_shift = self.block_shift; let block_values = 1usize << block_shift; @@ -830,6 +850,129 @@ impl PivcoData { ) } + pub(crate) fn compare_constant_u64( + &self, + len: usize, + rhs_u64: u64, + operator: CompareOperator, + ) -> VortexResult> { + if !self.is_on_host() { + return Ok(None); + } + let tree = &self.tree; + match operator { + CompareOperator::Eq | CompareOperator::NotEq => { + let negate = operator == CompareOperator::NotEq; + let (sym, ebits, _) = encode_pow2_bin(rhs_u64); + let rank = tree.sym_to_rank[usize::from(sym)]; + let sym_present = tree + .rank_to_sym + .get(usize::from(rank)) + .is_some_and(|&s| s == sym); + + if !sym_present { + // Even for `rhs_u64 >= 32` (`ebits > 0`), if its `Pow2-Bin` bucket is completely + // absent from the chunk's tree, `Eq` is 100% `false` in `O(1)`. + return Ok(Some(ConstantCompareResult::Constant(negate))); + } + + // Direct spine-walking equality when `ebits == 0` (`rhs_u64 < 32`). + if ebits == 0 { + if tree.rank_to_sym.len() == 1 { + return Ok(Some(ConstantCompareResult::Constant(!negate))); + } + let reader = self.block_reader(len)?; + let bits = reader.evaluate_spine_predicate(RankPredicate::Eq(rank), negate)?; + return Ok(Some(ConstantCompareResult::Bits(bits))); + } + + Ok(None) + } + CompareOperator::Lt + | CompareOperator::Lte + | CompareOperator::Gt + | CompareOperator::Gte => { + // Normalize all 4 ordering ops on `u >= 0` to `(u < threshold) ^ negate`. + let (threshold, negate) = match operator { + CompareOperator::Lt => { + if rhs_u64 == 0 { + return Ok(Some(ConstantCompareResult::Constant(false))); + } + (rhs_u64, false) + } + CompareOperator::Gte => { + if rhs_u64 == 0 { + return Ok(Some(ConstantCompareResult::Constant(true))); + } + (rhs_u64, true) + } + CompareOperator::Lte => { + if rhs_u64 == u64::MAX { + return Ok(Some(ConstantCompareResult::Constant(true))); + } + (rhs_u64 + 1, false) + } + CompareOperator::Gt => { + if rhs_u64 == u64::MAX { + return Ok(Some(ConstantCompareResult::Constant(false))); + } + (rhs_u64 + 1, true) + } + _ => unreachable!(), + }; + + if !tree.is_order_preserving { + // Even in `Huffman` mode, `u < 1` (`u == 0`) or `u >= 1` (`u != 0`) is an exact + // `sym == 0` spine query. + if threshold == 1 { + let rank0 = tree.sym_to_rank[0]; + let has_zero = tree + .rank_to_sym + .get(usize::from(rank0)) + .is_some_and(|&s| s == 0); + if !has_zero { + return Ok(Some(ConstantCompareResult::Constant(negate))); + } + if tree.rank_to_sym.len() == 1 { + return Ok(Some(ConstantCompareResult::Constant(!negate))); + } + let reader = self.block_reader(len)?; + let bits = + reader.evaluate_spine_predicate(RankPredicate::Eq(rank0), negate)?; + return Ok(Some(ConstantCompareResult::Bits(bits))); + } + return Ok(None); + } + + // In `OrderPreserving` mode (`rank_to_sym` strictly sorted): + let (target_sym, _ebits, target_raw) = encode_pow2_bin(threshold); + let split_rank = tree.rank_to_sym.partition_point(|&s| s < target_sym) as u8; + let target_sym_present = tree + .rank_to_sym + .get(usize::from(split_rank)) + .is_some_and(|&s| s == target_sym); + + // `u < threshold` is 100% decided by `rank < split_rank` whenever EITHER: + // 1. `target_raw == 0` (every `threshold <= 32` AND every Pow2-Bin boundary), OR + // 2. `target_sym` is absent from this chunk's active alphabet. + if target_raw == 0 || !target_sym_present { + if split_rank == 0 { + return Ok(Some(ConstantCompareResult::Constant(negate))); + } + if usize::from(split_rank) == tree.rank_to_sym.len() { + return Ok(Some(ConstantCompareResult::Constant(!negate))); + } + let reader = self.block_reader(len)?; + let bits = + reader.evaluate_spine_predicate(RankPredicate::Lt(split_rank), negate)?; + return Ok(Some(ConstantCompareResult::Bits(bits))); + } + + Ok(None) + } + } + } + /// `log2(block_values)` in `10..=13`. #[inline] pub fn block_shift(&self) -> u8 { diff --git a/encodings/pivco/src/codec/mod.rs b/encodings/pivco/src/codec/mod.rs index 1764e7b3684..04f659a5406 100644 --- a/encodings/pivco/src/codec/mod.rs +++ b/encodings/pivco/src/codec/mod.rs @@ -8,10 +8,12 @@ mod decode; mod encode; +mod spine; use std::mem::MaybeUninit; pub(crate) use encode::encode_primitive_slice; +pub(crate) use spine::RankPredicate; use vortex_buffer::ByteBufferMut; use vortex_error::VortexResult; use vortex_error::vortex_ensure; diff --git a/encodings/pivco/src/codec/spine.rs b/encodings/pivco/src/codec/spine.rs new file mode 100644 index 00000000000..88e75cd323c --- /dev/null +++ b/encodings/pivco/src/codec/spine.rs @@ -0,0 +1,444 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors +// SPDX-FileCopyrightText: 2026 Marcin Żukowski +// SPDX-FileComment: Derived from pivco-huffman at commit 16b48fcf at https://github.com/MarcinZukowski/pivco-huffman + +//! Direct spine-walking bitmap predicate pushdown (`Eq` / `NotEq` and `Lt`..`Gte`). + +#![expect(clippy::cast_possible_truncation)] + +use std::mem::MaybeUninit; + +use vortex_buffer::BitBuffer; +use vortex_buffer::BufferMut; +use vortex_buffer::ByteBufferMut; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_error::vortex_ensure_eq; + +use super::BlockReader; +use super::DecodeWorkspace; +use super::MAX_BM_BYTES; +use super::read_left_subtree_bytes; +use crate::bitmap_rans::DenseBitmap; +use crate::bitmap_rans::NodeBitmap; +use crate::simd::MERGE_OVERREAD; +use crate::simd::merge_cst_cst; +use crate::simd::merge_cst_vec_in_place; +use crate::simd::merge_vec_cst_in_place; +use crate::simd::pack_64_bytes01; +use crate::simd::popcount_bits; +use crate::simd::unpack_flat_codes; +use crate::tree::ChildSpec; +use crate::tree::PivcoNode; +use crate::tree::PivcoTree; + +/// Spine predicate target in DFS rank space (`0..num_leaves`). +#[derive(Clone, Copy)] +pub(crate) enum RankPredicate { + /// `rank == target_rank` (exact equality when `ebits(sym) == 0`, valid in ALL tree modes). + Eq(u8), + /// `rank < split_rank` (exact range `< threshold` in `OrderPreserving` mode). + Lt(u8), +} + +impl DecodeWorkspace { + pub(super) fn eval_spine_block( + &mut self, + tree: &PivcoTree, + block_len: usize, + pred: RankPredicate, + block_tree_bytes: &[u8], + ) -> VortexResult<&[u8]> { + self.ensure_for_tree(tree, block_len); + let mut cursor = 0usize; + eval_spine_node( + tree, + 0, + 0, + tree.rank_to_sym.len() as u8, + block_len, + pred, + block_tree_bytes, + &mut cursor, + &mut self.root_syms[..block_len + MERGE_OVERREAD], + &mut self.bm_stack, + self.bm_stride, + )?; + Ok(&self.root_syms[..block_len]) + } +} + +impl BlockReader<'_> { + /// Evaluates `pred` across this sliced [`crate::PivcoArray`] by walking ONLY the `O(depth)` + /// spine of each block's wavelet tree (never decoding sibling subtrees or `raw_bits`), + /// optionally negating (`NotEq`, `Gte`, `Gt`). + pub(crate) fn evaluate_spine_predicate( + &self, + pred: RankPredicate, + negate: bool, + ) -> VortexResult { + if self.len == 0 { + return Ok(BitBuffer::empty()); + } + let block_values = self.block_values(); + let offset = usize::from(self.offset); + let total_end = offset + self.len; + let num_blocks = self.num_blocks(); + let xor_u64 = if negate { !0u64 } else { 0u64 }; + + // Fast root-level special case: when `offset == 0` and the predicate is decided purely by + // the root node's bitmap, copy/invert the root bitmap bytes straight into packed bits + // without byte-expansion or SIMD merge. + if offset == 0 + && let Some(root_invert) = root_only_decision(self.tree, pred) + { + let invert_bits = root_invert ^ negate; + let out_bytes_len = self.len.div_ceil(8); + let mut packed_out = ByteBufferMut::with_capacity(out_bytes_len); + let mut bm_scratch = [MaybeUninit::::uninit(); MAX_BM_BYTES]; + let mut written_bits = 0usize; + + for block_idx in 0..num_blocks { + let block_len = self.block_len(block_idx); + let copy_bits = (self.len - written_bits).min(block_len); + let copy_bytes = copy_bits.div_ceil(8); + + let block_tree_bytes = self.block_tree_slice(block_idx); + let mut cursor = 0usize; + let bm = + NodeBitmap::read(block_tree_bytes, &mut cursor, block_len, &mut bm_scratch)?; + + // SAFETY: `bm_scratch` was just initialized by `NodeBitmap::read` for `bm`. + match unsafe { bm.into_dense(&mut bm_scratch, block_len) } { + DenseBitmap::AllZero => { + packed_out.push_n(if invert_bits { 0xFF } else { 0x00 }, copy_bytes); + } + DenseBitmap::AllOne => { + packed_out.push_n(if invert_bits { 0x00 } else { 0xFF }, copy_bytes); + } + DenseBitmap::Bytes(s) => { + if invert_bits { + for &b in &s[..copy_bytes] { + packed_out.push(!b); + } + } else { + packed_out.extend_from_slice(&s[..copy_bytes]); + } + } + } + written_bits += copy_bits; + } + let rem_bits = self.len & 7; + if rem_bits != 0 + && let Some(last) = packed_out.last_mut() + { + *last &= (1u8 << rem_bits) - 1; + } + return Ok(BitBuffer::new(packed_out.freeze(), self.len)); + } + + // General spine-walking path (`O(depth)` merges along a single path), writing packed `u64` + // words directly into an aligned `BufferMut` with zero extra copy. + let mut ws = DecodeWorkspace::for_tree(self.tree, block_values); + let mut u64_words = BufferMut::::with_capacity(self.len.div_ceil(64)); + let mut bit_acc = 0u64; + let mut acc_bits = 0usize; + + for block_idx in 0..num_blocks { + let block_abs_start = block_idx * block_values; + let in_block_start = if block_idx == 0 { offset } else { 0 }; + let in_block_end = (total_end - block_abs_start).min(block_values); + + let block_len = self.block_len(block_idx); + let block_tree_bytes = self.block_tree_slice(block_idx); + let block01 = ws.eval_spine_block(self.tree, block_len, pred, block_tree_bytes)?; + let slice01 = &block01[in_block_start..in_block_end]; + + let mut i = 0usize; + if acc_bits != 0 { + let need = (64 - acc_bits).min(slice01.len()); + for &b in &slice01[..need] { + if (b != 0) ^ negate { + bit_acc |= 1u64 << acc_bits; + } + acc_bits += 1; + } + i = need; + if acc_bits == 64 { + u64_words.push(bit_acc.to_le()); + bit_acc = 0; + acc_bits = 0; + } + } + if acc_bits == 0 { + while i + 64 <= slice01.len() { + let w = pack_64_bytes01(&slice01[i..i + 64]) ^ xor_u64; + u64_words.push(w.to_le()); + i += 64; + } + } + while i < slice01.len() { + if (slice01[i] != 0) ^ negate { + bit_acc |= 1u64 << acc_bits; + } + acc_bits += 1; + i += 1; + } + } + if acc_bits > 0 { + u64_words.push(bit_acc.to_le()); + } + + Ok(BitBuffer::new( + u64_words.freeze().into_byte_buffer(), + self.len, + )) + } +} + +/// Returns `Some(invert)` if `pred` is 100% answered by the root node's bitmap (`false` => `bit == 1` +/// is true, `true` => `bit == 0` is true), or `None` if deeper nodes are required. +fn root_only_decision(tree: &PivcoTree, pred: RankPredicate) -> Option { + let PivcoNode::Internal { + pivot_rank, + left_child, + right_child, + .. + } = &tree.nodes[0] + else { + return None; + }; + + match pred { + RankPredicate::Eq(target_rank) => { + if target_rank == 0 && *pivot_rank == 1 && matches!(left_child, ChildSpec::Leaf(_)) { + Some(true) // bit == 0 => true! + } else if target_rank == *pivot_rank + && usize::from(*pivot_rank) + 1 == tree.rank_to_sym.len() + && matches!(right_child, ChildSpec::Leaf(_)) + { + Some(false) // bit == 1 => true! + } else { + None + } + } + RankPredicate::Lt(split_rank) => (split_rank == *pivot_rank).then_some(true), + } +} + +#[inline] +fn rank_outcome(lo_rank: u8, hi_rank: u8, pred: RankPredicate) -> Option { + match pred { + RankPredicate::Eq(t) => { + if t < lo_rank || t >= hi_rank { + Some(0) + } else if lo_rank + 1 == hi_rank && lo_rank == t { + Some(1) + } else { + None + } + } + RankPredicate::Lt(s) => { + if hi_rank <= s { + Some(1) + } else if lo_rank >= s { + Some(0) + } else { + None + } + } + } +} + +#[expect(clippy::too_many_arguments)] +fn eval_spine_node( + tree: &PivcoTree, + node_idx: u16, + lo_rank: u8, + hi_rank: u8, + n: usize, + pred: RankPredicate, + wire: &[u8], + cursor: &mut usize, + out01: &mut [u8], + bm_stack: &mut [MaybeUninit], + bm_stride: usize, +) -> VortexResult<()> { + if n == 0 { + return Ok(()); + } + if let Some(cst) = rank_outcome(lo_rank, hi_rank, pred) { + out01[..n].fill(cst); + return Ok(()); + } + + match &tree.nodes[usize::from(node_idx)] { + PivcoNode::SingleLeaf { .. } => { + let v = rank_outcome(lo_rank, hi_rank, pred).unwrap_or(0); + out01[..n].fill(v); + Ok(()) + } + PivcoNode::Flat { + depth, base_rank, .. + } => { + let nbytes = (n * usize::from(*depth)).div_ceil(8); + vortex_ensure!(*cursor + nbytes <= wire.len(), "Truncated Pivco flat eval"); + let packed = &wire[*cursor..*cursor + nbytes]; + *cursor += nbytes; + let mut c2s_mask = [0u8; 64]; + for (code, slot) in c2s_mask.iter_mut().enumerate().take(1usize << *depth) { + let rank = *base_rank + (code as u8); + *slot = match pred { + RankPredicate::Eq(target) => u8::from(rank == target), + RankPredicate::Lt(split) => u8::from(rank < split), + }; + } + unpack_flat_codes(*depth, n, packed, &c2s_mask, &mut out01[..n]); + Ok(()) + } + PivcoNode::Internal { + pivot_rank, + left_child, + right_child, + .. + } => { + vortex_ensure!(bm_stack.len() >= bm_stride, "Pivco spine stack overflow"); + let (bm_head, bm_tail) = bm_stack.split_at_mut(bm_stride); + let bm = NodeBitmap::read(wire, cursor, n, bm_head)?; + let left_bytes = if matches!(left_child, ChildSpec::Node(_)) { + Some(read_left_subtree_bytes(wire, cursor)?) + } else { + None + }; + let left_const = rank_outcome(lo_rank, *pivot_rank, pred); + let right_const = rank_outcome(*pivot_rank, hi_rank, pred); + + // SAFETY: `bm_head` was just initialized by `NodeBitmap::read` for `bm`. + match unsafe { bm.into_dense(bm_head, n) } { + DenseBitmap::AllZero => { + if let Some(lc) = left_const { + out01[..n].fill(lc); + return Ok(()); + } + match *left_child { + ChildSpec::Leaf(_) => unreachable!("single-rank leaf has Some(left_const)"), + ChildSpec::Node(l_idx) => eval_spine_node( + tree, + l_idx, + lo_rank, + *pivot_rank, + n, + pred, + wire, + cursor, + out01, + bm_tail, + bm_stride, + ), + } + } + DenseBitmap::AllOne => { + if let Some(lb) = left_bytes { + vortex_ensure_eq!( + lb, + 0, + "AllOne Pivco node must have 0 left_subtree_bytes" + ); + } + if let Some(rc) = right_const { + out01[..n].fill(rc); + return Ok(()); + } + match *right_child { + ChildSpec::Leaf(_) => { + unreachable!("single-rank leaf has Some(right_const)") + } + ChildSpec::Node(r_idx) => eval_spine_node( + tree, + r_idx, + *pivot_rank, + hi_rank, + n, + pred, + wire, + cursor, + out01, + bm_tail, + bm_stride, + ), + } + } + DenseBitmap::Bytes(bm_slice) => { + let k_right = popcount_bits(bm_slice, n); + let k_left = n - k_right; + if k_left == 0 + && let Some(lb) = left_bytes + { + vortex_ensure_eq!( + lb, + 0, + "Empty left subtree must have 0 left_subtree_bytes" + ); + } + match (left_const, right_const) { + (Some(lc), Some(rc)) => { + merge_cst_cst(bm_slice, n, lc, rc, &mut out01[..n]); + Ok(()) + } + (None, Some(rc)) => { + match *left_child { + ChildSpec::Leaf(_) => { + unreachable!("single-rank leaf has Some(left_const)") + } + ChildSpec::Node(l_idx) => eval_spine_node( + tree, + l_idx, + lo_rank, + *pivot_rank, + k_left, + pred, + wire, + cursor, + &mut out01[k_right..], + bm_tail, + bm_stride, + )?, + } + // SAFETY: `k_right == popcount_bits(bm_slice, n)`. + unsafe { merge_vec_cst_in_place(bm_slice, n, k_right, rc, out01) }; + Ok(()) + } + (Some(lc), None) => { + *cursor += left_bytes.unwrap_or(0); + match *right_child { + ChildSpec::Leaf(_) => { + unreachable!("single-rank leaf has Some(right_const)") + } + ChildSpec::Node(r_idx) => eval_spine_node( + tree, + r_idx, + *pivot_rank, + hi_rank, + k_right, + pred, + wire, + cursor, + &mut out01[k_left..], + bm_tail, + bm_stride, + )?, + } + // SAFETY: `k_left == n - popcount_bits(bm_slice, n)`. + unsafe { merge_cst_vec_in_place(bm_slice, n, lc, k_left, out01) }; + Ok(()) + } + (None, None) => { + unreachable!("Eq(t) and Lt(s) have at most one non-constant child") + } + } + } + } + } + } +} diff --git a/encodings/pivco/src/compute.rs b/encodings/pivco/src/compute.rs new file mode 100644 index 00000000000..6e42975b319 --- /dev/null +++ b/encodings/pivco/src/compute.rs @@ -0,0 +1,752 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Block-skipping `SliceReduce`, `TakeExecute`, `FilterKernel`, fused `ZigZag` parent execution, +//! and direct spine-walking `CompareKernel` predicate pushdown for [`Pivco`]. + +#![expect(clippy::cast_possible_truncation)] + +use std::mem::MaybeUninit; +use std::ops::Range; + +use num_traits::AsPrimitive; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::Canonical; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::dict::TakeExecute; +use vortex_array::arrays::filter::FilterKernel; +use vortex_array::arrays::slice::SliceReduce; +use vortex_array::dtype::DType; +use vortex_array::dtype::IntegerPType; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::kernel::ExecuteParentKernel; +use vortex_array::match_each_integer_ptype; +use vortex_array::scalar::Scalar; +use vortex_array::scalar_fn::builtin::compare::CompareKernel; +use vortex_array::scalar_fn::builtin::operators::CompareOperator; +use vortex_array::validity::Validity; +use vortex_array::vtable::ValidityVTable; +use vortex_buffer::BitBuffer; +use vortex_buffer::BufferMut; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_mask::Mask; +use vortex_mask::MaskValues; +use vortex_zigzag::ZigZag; +use vortex_zigzag::ZigZagSlots; + +use crate::array::ConstantCompareResult; +use crate::array::Pivco; +use crate::array::PivcoData; +use crate::array::num_blocks_for; + +/// Above `1/8` (`12.5%`) take/filter selectivity, full-array decompression + primitive gather +/// beats per-block scratch decode. +const FULL_ARRAY_DECODE_RATIO: usize = 8; + +/// At or below `4` hits in a block, top-down `O(depth)` `decode_value_at` beats rebuilding the +/// full block wavelet tree. +const SCALAR_BLOCK_HIT_THRESHOLD: usize = 4; + +/// Fused parent-execute kernel that decodes `ZigZag(Pivco)` in a single pass with zero +/// intermediate unsigned buffer allocation. +#[derive(Clone, Copy, Debug)] +pub struct PivcoZigZagKernel; + +impl ExecuteParentKernel for PivcoZigZagKernel { + type Parent = ZigZag; + + fn execute_parent( + &self, + array: ArrayView<'_, Pivco>, + parent: ArrayView<'_, ZigZag>, + child_idx: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + if child_idx != ZigZagSlots::ENCODED || !array.data().is_on_host() { + return Ok(None); + } + + let validity = match Pivco::validity(array)? { + Validity::Array(v) if !v.is_canonical() => { + Validity::Array(v.execute::(ctx)?.into_array()) + } + other => other, + }; + + let data = array.data(); + let len = array.len(); + let decoded = match parent.dtype().as_ptype() { + PType::I8 => data.decompress_mapped::(len, validity, ctx, |u| { + let v = u as u8; + ((v >> 1) as i8) ^ -((v & 1) as i8) + })?, + PType::I16 => data.decompress_mapped::(len, validity, ctx, |u| { + let v = u as u16; + ((v >> 1) as i16) ^ -((v & 1) as i16) + })?, + PType::I32 => data.decompress_mapped::(len, validity, ctx, |u| { + let v = u as u32; + ((v >> 1) as i32) ^ -((v & 1) as i32) + })?, + PType::I64 => data.decompress_mapped::(len, validity, ctx, |u| { + ((u >> 1) as i64) ^ -((u & 1) as i64) + })?, + other => { + vortex_bail!("ZigZag parent of Pivco must have signed integer ptype, got {other}") + } + }; + Ok(Some(decoded.into_array())) + } +} + +impl SliceReduce for Pivco { + fn slice(array: ArrayView<'_, Self>, range: Range) -> VortexResult> { + let validity = Self::validity(array)?.slice(range.clone())?; + let data = array.data().slice(array.len(), range.clone())?; + Ok(Some( + Self::try_new(array.dtype().clone(), range.len(), data, validity)?.into_array(), + )) + } +} + +impl TakeExecute for Pivco { + fn take( + array: ArrayView<'_, Self>, + indices: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + take_data( + array.data(), + array.dtype(), + array.len(), + Self::validity(array)?, + indices, + ctx, + ) + } +} + +fn take_data( + data: &PivcoData, + dtype: &DType, + array_len: usize, + validity: Validity, + indices: &ArrayRef, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + if !data.is_on_host() { + return Ok(None); + } + if indices.is_empty() { + let out_dtype = dtype.union_nullability(indices.dtype().nullability()); + return Ok(Some(Canonical::empty(&out_dtype).into_array())); + } + if matches!(indices.validity()?, Validity::AllInvalid) { + return Ok(Some( + ConstantArray::new(Scalar::null(dtype.as_nullable()), indices.len()).into_array(), + )); + } + if indices.len().saturating_mul(FULL_ARRAY_DECODE_RATIO) > array_len { + return Ok(None); + } + if u32::try_from(indices.len()).is_err() { + return Ok(None); + } + + let indices_prim = indices.clone().execute::(ctx)?; + let index_validity = indices_prim + .validity()? + .execute_mask(indices_prim.len(), ctx)?; + if matches!(index_validity, Mask::AllFalse(_)) { + return Ok(Some( + ConstantArray::new(Scalar::null(dtype.as_nullable()), indices_prim.len()).into_array(), + )); + } + + let taken_validity = validity.take(&indices_prim.clone().into_array())?; + let ptype = dtype.as_ptype(); + + let result = match_each_integer_ptype!(ptype, |T| { + match_each_integer_ptype!(indices_prim.ptype(), |I| { + take_typed::( + data, + array_len, + indices_prim.as_slice::(), + &index_validity, + taken_validity, + ctx, + )? + }) + }); + Ok(Some(result.into_array())) +} + +fn take_typed( + data: &PivcoData, + array_len: usize, + indices: &[I], + index_validity: &Mask, + taken_validity: Validity, + ctx: &mut ExecutionCtx, +) -> VortexResult +where + T: NativePType, + u64: AsPrimitive, + I: IntegerPType, +{ + let block_shift = data.block_shift(); + let block_values = 1usize << block_shift; + let offset = usize::from(data.offset()); + let num_blocks = (offset + array_len).div_ceil(block_values); + let plan = scan_take_blocks( + indices, + index_validity, + array_len, + offset, + block_shift, + num_blocks, + )?; + + let out_len = indices.len(); + let mut out = BufferMut::::with_capacity_in(out_len, ctx.allocator().clone()); + let out_uninit = &mut out.spare_capacity_mut()[..out_len]; + + if plan.block_ordered { + take_ordered_blocks::(data, array_len, indices, index_validity, &plan, out_uninit)?; + } else { + take_scattered_blocks::(data, array_len, indices, index_validity, &plan, out_uninit)?; + } + + // SAFETY: Every slot in `0..out_len` was initialized via `MaybeUninit::write` above. + unsafe { out.set_len(out_len) }; + Ok(PrimitiveArray::new(out.freeze(), taken_validity)) +} + +struct TakeBlockPlan { + hits_per_block: Vec, + max_pos_per_block: Vec, + block_ordered: bool, +} + +fn scan_take_blocks( + indices: &[I], + index_validity: &Mask, + array_len: usize, + offset: usize, + block_shift: u8, + num_blocks: usize, +) -> VortexResult { + let block_mask = (1usize << block_shift) - 1; + let mut hits_per_block = vec![0u32; num_blocks]; + let mut max_pos_per_block = vec![0u16; num_blocks]; + let mut block_ordered = true; + let mut prev_block = 0usize; + + match index_validity { + Mask::AllTrue(_) => { + for &raw_idx in indices { + let idx = checked_index(raw_idx, array_len)?; + let pos = offset + idx; + let b = pos >> block_shift; + let in_b = (pos & block_mask) as u16; + if b < prev_block { + block_ordered = false; + } + prev_block = b; + hits_per_block[b] += 1; + max_pos_per_block[b] = max_pos_per_block[b].max(in_b); + } + } + Mask::Values(mv) => { + for (start, end) in mv.bit_buffer().set_slices() { + for &raw_idx in &indices[start..end] { + let idx = checked_index(raw_idx, array_len)?; + let pos = offset + idx; + let b = pos >> block_shift; + let in_b = (pos & block_mask) as u16; + if b < prev_block { + block_ordered = false; + } + prev_block = b; + hits_per_block[b] += 1; + max_pos_per_block[b] = max_pos_per_block[b].max(in_b); + } + } + } + Mask::AllFalse(_) => unreachable!("handled by caller"), + } + + Ok(TakeBlockPlan { + hits_per_block, + max_pos_per_block, + block_ordered, + }) +} + +fn take_ordered_blocks( + data: &PivcoData, + array_len: usize, + indices: &[I], + index_validity: &Mask, + plan: &TakeBlockPlan, + out_uninit: &mut [MaybeUninit], +) -> VortexResult<()> +where + T: NativePType, + u64: AsPrimitive, + I: IntegerPType, +{ + let block_shift = data.block_shift(); + let block_values = 1usize << block_shift; + let block_mask = block_values - 1; + let offset = usize::from(data.offset()); + + let mut decoder = data.block_decoder(array_len)?; + let mut scratch: Option>> = None; + let mut cur_block = usize::MAX; + + let mut write_valid = |dst: &mut MaybeUninit, raw_idx: I| -> VortexResult<()> { + let pos = offset + raw_idx.as_(); + let b = pos >> block_shift; + let in_block = pos & block_mask; + if (plan.hits_per_block[b] as usize) <= SCALAR_BLOCK_HIT_THRESHOLD { + let val: T = decoder.decode_value_at(b, in_block)?.as_(); + dst.write(val); + } else { + let buf = scratch.get_or_insert_with(|| vec![MaybeUninit::uninit(); block_values]); + if b != cur_block { + let end = usize::from(plan.max_pos_per_block[b]) + 1; + decoder.decode_range_into::(b, 0, end, &mut buf[..end], |u| u.as_())?; + cur_block = b; + } + // SAFETY: `in_block <= max_pos_per_block[b]`, initialized above. + dst.write(unsafe { buf[in_block].assume_init() }); + } + Ok(()) + }; + + match index_validity { + Mask::AllTrue(_) => { + for (dst, &raw_idx) in out_uninit.iter_mut().zip(indices) { + write_valid(dst, raw_idx)?; + } + } + Mask::Values(mv) => { + let mut cursor = 0usize; + for (start, end) in mv.bit_buffer().set_slices() { + for dst in &mut out_uninit[cursor..start] { + dst.write(T::default()); + } + for (dst, &raw_idx) in out_uninit[start..end].iter_mut().zip(&indices[start..end]) { + write_valid(dst, raw_idx)?; + } + cursor = end; + } + for dst in &mut out_uninit[cursor..] { + dst.write(T::default()); + } + } + Mask::AllFalse(_) => unreachable!("handled by caller"), + } + Ok(()) +} + +fn take_scattered_blocks( + data: &PivcoData, + array_len: usize, + indices: &[I], + index_validity: &Mask, + plan: &TakeBlockPlan, + out_uninit: &mut [MaybeUninit], +) -> VortexResult<()> +where + T: NativePType, + u64: AsPrimitive, + I: IntegerPType, +{ + let block_shift = data.block_shift(); + let block_values = 1usize << block_shift; + let block_mask = block_values - 1; + let num_blocks = plan.hits_per_block.len(); + let mut block_starts = vec![0u32; num_blocks + 1]; + let mut total_valid = 0u32; + for (b, &hits) in plan.hits_per_block.iter().enumerate() { + block_starts[b] = total_valid; + total_valid += hits; + } + block_starts[num_blocks] = total_valid; + + let mut write_cursors = block_starts[..num_blocks].to_vec(); + let mut grouped_out_idx = vec![0u32; total_valid as usize]; + let mut grouped_in_block = vec![0u16; total_valid as usize]; + let offset = usize::from(data.offset()); + + match index_validity { + Mask::AllTrue(_) => { + for (out_i, &raw_idx) in indices.iter().enumerate() { + let pos = offset + raw_idx.as_(); + let b = pos >> block_shift; + let slot = write_cursors[b] as usize; + write_cursors[b] += 1; + grouped_out_idx[slot] = out_i as u32; + grouped_in_block[slot] = (pos & block_mask) as u16; + } + } + Mask::Values(mv) => { + let mut cursor = 0usize; + for (start, end) in mv.bit_buffer().set_slices() { + for dst in &mut out_uninit[cursor..start] { + dst.write(T::default()); + } + for (out_i, &raw_idx) in (start..end).zip(&indices[start..end]) { + let pos = offset + raw_idx.as_(); + let b = pos >> block_shift; + let slot = write_cursors[b] as usize; + write_cursors[b] += 1; + grouped_out_idx[slot] = out_i as u32; + grouped_in_block[slot] = (pos & block_mask) as u16; + } + cursor = end; + } + for dst in &mut out_uninit[cursor..] { + dst.write(T::default()); + } + } + Mask::AllFalse(_) => unreachable!("handled by caller"), + } + + let mut decoder = data.block_decoder(array_len)?; + let mut scratch: Option>> = None; + + for b in 0..num_blocks { + let start = block_starts[b] as usize; + let end = block_starts[b + 1] as usize; + let count = end - start; + if count == 0 { + continue; + } + if count <= SCALAR_BLOCK_HIT_THRESHOLD { + for slot in start..end { + let out_i = grouped_out_idx[slot] as usize; + let in_block = usize::from(grouped_in_block[slot]); + let val: T = decoder.decode_value_at(b, in_block)?.as_(); + out_uninit[out_i].write(val); + } + } else { + let buf = scratch.get_or_insert_with(|| vec![MaybeUninit::uninit(); block_values]); + let decode_end = usize::from(plan.max_pos_per_block[b]) + 1; + decoder + .decode_range_into::(b, 0, decode_end, &mut buf[..decode_end], |u| u.as_())?; + for slot in start..end { + let out_i = grouped_out_idx[slot] as usize; + let in_block = usize::from(grouped_in_block[slot]); + // SAFETY: `in_block <= max_pos_per_block[b]`, initialized above. + out_uninit[out_i].write(unsafe { buf[in_block].assume_init() }); + } + } + } + Ok(()) +} + +#[inline] +fn checked_index(raw_idx: I, array_len: usize) -> VortexResult { + if let Some(idx) = raw_idx.to_usize() + && idx < array_len + { + Ok(idx) + } else { + vortex_bail!("Take index {raw_idx} out of bounds for PivcoArray of length {array_len}") + } +} + +impl FilterKernel for Pivco { + fn filter( + array: ArrayView<'_, Self>, + mask: &Mask, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + if matches!(mask, Mask::AllTrue(_)) { + return Ok(Some(array.array().clone())); + } + filter_data( + array.data(), + array.dtype(), + array.len(), + Self::validity(array)?, + mask, + ctx, + ) + } +} + +fn filter_data( + data: &PivcoData, + dtype: &DType, + array_len: usize, + validity: Validity, + mask: &Mask, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + if !data.is_on_host() { + return Ok(None); + } + let mask_values = match mask { + Mask::AllTrue(_) => unreachable!("handled by caller"), + Mask::AllFalse(_) => return Ok(Some(Canonical::empty(dtype).into_array())), + Mask::Values(values) => values, + }; + + // High-selectivity filters (> 1/8) are faster via canonical decode + primitive filter. + if mask_values + .true_count() + .saturating_mul(FULL_ARRAY_DECODE_RATIO) + > array_len + { + return Ok(None); + } + + let filtered_validity = validity.filter(mask)?; + let ptype = dtype.as_ptype(); + let filtered = match_each_integer_ptype!(ptype, |T| { + filter_typed::(data, array_len, mask_values, filtered_validity, ctx)? + }); + Ok(Some(filtered.into_array())) +} + +fn filter_typed( + data: &PivcoData, + array_len: usize, + mask_values: &MaskValues, + validity: Validity, + ctx: &mut ExecutionCtx, +) -> VortexResult +where + T: NativePType, + u64: AsPrimitive, +{ + let true_count = mask_values.true_count(); + let mut out = BufferMut::::with_capacity_in(true_count, ctx.allocator().clone()); + let out_uninit = &mut out.spare_capacity_mut()[..true_count]; + + let block_shift = data.block_shift(); + let block_values = 1usize << block_shift; + let offset = usize::from(data.offset()); + let num_blocks = num_blocks_for(block_shift, data.offset(), array_len); + + let mut decoder = data.block_decoder(array_len)?; + let mut scratch: Option>> = None; + let mut written = 0usize; + + if let Some(indices) = mask_values.cached_indices() { + let mut rest = indices; + while let Some(&first_idx) = rest.first() { + let block_idx = (first_idx + offset) >> block_shift; + let block_abs_start = block_idx * block_values; + let block_logical_end = block_abs_start + block_values - offset; + let count = rest.partition_point(|&i| i < block_logical_end); + let block_indices = &rest[..count]; + + if count <= SCALAR_BLOCK_HIT_THRESHOLD { + for (dst, &orig_idx) in out_uninit[written..written + count] + .iter_mut() + .zip(block_indices) + { + let in_block = orig_idx + offset - block_abs_start; + let val: T = decoder.decode_value_at(block_idx, in_block)?.as_(); + dst.write(val); + } + } else { + let buf = scratch.get_or_insert_with(|| vec![MaybeUninit::uninit(); block_values]); + let first_in_block = block_indices[0] + offset - block_abs_start; + let last_in_block = block_indices[count - 1] + offset - block_abs_start; + let decode_end = last_in_block + 1; + + decoder.decode_range_into::( + block_idx, + first_in_block, + decode_end, + &mut buf[first_in_block..decode_end], + |u| u.as_(), + )?; + + for (dst, &orig_idx) in out_uninit[written..written + count] + .iter_mut() + .zip(block_indices) + { + let in_block = orig_idx + offset - block_abs_start; + // SAFETY: `first_in_block <= in_block < decode_end`, initialized above. + dst.write(unsafe { buf[in_block].assume_init() }); + } + } + written += count; + rest = &rest[count..]; + } + } else { + let bits = mask_values.bit_buffer(); + let len = bits.len(); + let mut positions: Vec = Vec::new(); + + for block_idx in 0..num_blocks { + let block_abs_start = block_idx * block_values; + let start = block_abs_start.saturating_sub(offset); + let end = (block_abs_start + block_values - offset).min(len); + let count = bits.count_range(start, end); + if count == 0 { + continue; + } + + let in_block_base = start + offset - block_abs_start; + positions.clear(); + bits.slice(start..end).for_each_set_index(|rel| { + positions.push((in_block_base + rel) as u16); + }); + debug_assert_eq!(positions.len(), count); + + if count <= SCALAR_BLOCK_HIT_THRESHOLD { + for (dst, &in_block) in out_uninit[written..written + count] + .iter_mut() + .zip(&positions) + { + let val: T = decoder + .decode_value_at(block_idx, usize::from(in_block))? + .as_(); + dst.write(val); + } + } else { + let buf = scratch.get_or_insert_with(|| vec![MaybeUninit::uninit(); block_values]); + let first_in_block = usize::from(positions[0]); + let decode_end = usize::from(positions[count - 1]) + 1; + decoder.decode_range_into::( + block_idx, + first_in_block, + decode_end, + &mut buf[first_in_block..decode_end], + |u| u.as_(), + )?; + + for (dst, &in_block) in out_uninit[written..written + count] + .iter_mut() + .zip(&positions) + { + // SAFETY: `first_in_block <= in_block < decode_end`, initialized above. + dst.write(unsafe { buf[usize::from(in_block)].assume_init() }); + } + } + written += count; + } + } + + debug_assert_eq!(written, true_count); + // SAFETY: Exactly `true_count` elements were written via `MaybeUninit::write` above. + unsafe { out.set_len(true_count) }; + Ok(PrimitiveArray::new(out.freeze(), validity)) +} + +// ============================================================================ +// Direct Spine-Walking `CompareKernel` Pushdown (`==`, `!=`, `<`, `<=`, `>`, `>=`) +// ============================================================================ + +impl CompareKernel for Pivco { + fn compare( + lhs: ArrayView<'_, Self>, + rhs: &ArrayRef, + operator: CompareOperator, + _ctx: &mut ExecutionCtx, + ) -> VortexResult> { + compare_data( + lhs.data(), + lhs.dtype(), + lhs.len(), + Self::validity(lhs)?, + rhs, + operator, + ) + } +} + +fn compare_data( + data: &PivcoData, + lhs_dtype: &DType, + len: usize, + lhs_validity: Validity, + rhs: &ArrayRef, + operator: CompareOperator, +) -> VortexResult> { + if !data.is_on_host() { + return Ok(None); + } + let Some(const_scalar) = rhs.as_constant() else { + return Ok(None); + }; + let Some(pscalar) = const_scalar.as_primitive_opt() else { + return Ok(None); + }; + if pscalar.ptype() != lhs_dtype.as_ptype() { + return Ok(None); + } + + let pvalue = pscalar + .pvalue() + .vortex_expect("compare adaptor handles null constants"); + let nullability = lhs_dtype.nullability() | rhs.dtype().nullability(); + + // Extract `rhs` as a non-negative `u64` or handle negative signed constants in `O(1)`. + // Validated `PivcoArray` trees guarantee every element is non-negative and fits in `lhs_dtype`. + let rhs_u64: u64 = if pvalue.ptype().is_signed_int() { + let signed = pvalue + .cast::() + .vortex_expect("signed integer fits i64"); + if signed < 0 { + let const_ans = match operator { + CompareOperator::Eq | CompareOperator::Lt | CompareOperator::Lte => false, + CompareOperator::NotEq | CompareOperator::Gt | CompareOperator::Gte => true, + }; + return constant_bool_preserving_validity(len, lhs_validity, const_ans, nullability) + .map(Some); + } + signed as u64 + } else { + pvalue + .cast::() + .vortex_expect("unsigned integer fits u64") + }; + + match data.compare_constant_u64(len, rhs_u64, operator)? { + Some(ConstantCompareResult::Constant(val)) => { + constant_bool_preserving_validity(len, lhs_validity, val, nullability).map(Some) + } + Some(ConstantCompareResult::Bits(bits)) => { + let validity = lhs_validity.union_nullability(nullability); + Ok(Some(BoolArray::new(bits, validity).into_array())) + } + None => Ok(None), + } +} + +fn constant_bool_preserving_validity( + len: usize, + lhs_validity: Validity, + value: bool, + nullability: Nullability, +) -> VortexResult { + Ok(match lhs_validity.union_nullability(nullability) { + Validity::NonNullable | Validity::AllValid => { + ConstantArray::new(Scalar::bool(value, nullability), len).into_array() + } + Validity::AllInvalid => { + ConstantArray::new(Scalar::null(DType::Bool(nullability)), len).into_array() + } + validity @ Validity::Array(_) => { + BoolArray::new(BitBuffer::full(value, len), validity).into_array() + } + }) +} diff --git a/encodings/pivco/src/lib.rs b/encodings/pivco/src/lib.rs index d3748d2f4ab..9ff93f91f1e 100644 --- a/encodings/pivco/src/lib.rs +++ b/encodings/pivco/src/lib.rs @@ -4,22 +4,23 @@ //! Block-reset `Pow2-Bin + PIVCO` wavelet-tree integer encoding (`vortex.pivco`). //! //! Combines `Pow2-Bin + Raw-Bits` outer value decomposition (`150` bounded symbols + parallel `u64` -//! `raw_bits` stream) with Marcin Żukowski's bottom-up wavelet-tree symbol codec (`PH` raw -//! bitmaps + `PHA` skewed-bitmap compression + equal-depth flat-subtree packing) and optional -//! `OrderPreserving` alphabet trees. +//! `raw_bits` stream) with Marcin Żukowski's bottom-up SIMD wavelet-tree symbol codec (`PH` raw +//! bitmaps + `PHA` skewed-bitmap compression + equal-depth flat-subtree SIMD unpack) and optional +//! `OrderPreserving` alphabet trees for direct `<` / `<=` / `>` / `>=` bitmap predicate pushdown. //! //! # Attribution //! -//! The bottom-up wavelet-tree codec and equal-depth flat-subtree design are based on Marcin -//! Żukowski's Apache-2.0 licensed [`pivco-huffman`] implementation (commit -//! `16b48fcfcbd5cd71d945eb48e2702eec398bb36b`, Copyright Marcin Żukowski) and accompanying paper, -//! Marcin Żukowski, *"PivCo-Huffman"* (`arXiv:2606.05765`, v1.0, 2026-06-04). +//! The bottom-up SIMD wavelet-tree codec, `SABD` two-table merge, and equal-depth flat-subtree +//! design are based on Marcin Żukowski's Apache-2.0 licensed [`pivco-huffman`] implementation +//! (commit `16b48fcfcbd5cd71d945eb48e2702eec398bb36b`, Copyright Marcin Żukowski) and accompanying +//! paper, Marcin Żukowski, *"PivCo-Huffman"* (`arXiv:2606.05765`, v1.0, 2026-06-04). //! //! [`pivco-huffman`]: https://github.com/MarcinZukowski/pivco-huffman mod array; mod bitmap_rans; mod codec; +mod compute; mod plugin; mod pow2_bin; mod simd; @@ -39,12 +40,32 @@ pub use codec::MIN_BLOCK_SHIFT; pub use codec::PivcoOptions; pub use plugin::PivcoPlugin; pub use tree::PivcoTreeMode; +use vortex_array::ArrayVTable; +use vortex_array::arrays::Dict; +use vortex_array::arrays::Filter; +use vortex_array::arrays::Slice; +use vortex_array::arrays::dict::TakeExecuteAdaptor; +use vortex_array::arrays::filter::FilterExecuteAdaptor; +use vortex_array::arrays::slice::SliceReduceAdaptor; +use vortex_array::optimizer::kernels::ArrayKernelsExt; +use vortex_array::scalar_fn::ScalarFnVTable as _; +use vortex_array::scalar_fn::builtin::compare::Compare; +use vortex_array::scalar_fn::builtin::compare::CompareExecuteAdaptor; use vortex_array::session::ArraySessionExt; use vortex_session::VortexSession; +use vortex_zigzag::ZigZag; -/// Register the `vortex.pivco` encoding plugin. +use crate::compute::PivcoZigZagKernel; + +/// Register the `vortex.pivco` encoding plugin, parent-reduce rules, and parent-execute kernels. pub fn initialize(session: &VortexSession) { session.arrays().register(PivcoPlugin); + let kernels = session.kernels(); + kernels.register_reduce_parent_rule(Slice, Pivco, const { &SliceReduceAdaptor(Pivco) }); + kernels.register_execute_parent_kernel(Filter.id(), Pivco, FilterExecuteAdaptor(Pivco)); + kernels.register_execute_parent_kernel(Dict.id(), Pivco, TakeExecuteAdaptor(Pivco)); + kernels.register_execute_parent_kernel(ZigZag.id(), Pivco, PivcoZigZagKernel); + kernels.register_execute_parent_kernel(Compare.id(), Pivco, CompareExecuteAdaptor(Pivco)); } #[cfg(test)] diff --git a/encodings/pivco/src/simd/mod.rs b/encodings/pivco/src/simd/mod.rs index 514a51af9a3..d1235b575e5 100644 --- a/encodings/pivco/src/simd/mod.rs +++ b/encodings/pivco/src/simd/mod.rs @@ -888,6 +888,51 @@ fn pack_flat_codes_tail_scalar( } } +/// Packs 64 `0/1` bytes (each byte must be strictly `0` or `1`) into one `u64` bitmask in `O(1)` +/// SIMD / SWAR instructions. +#[inline] +pub(crate) fn pack_64_bytes01(chunk64: &[u8]) -> u64 { + let chunk64 = &chunk64[..64]; + debug_assert!(chunk64.iter().all(|&b| b <= 1)); + #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] + { + // SAFETY: `cfg` guarantees NEON and `chunk64.len() == 64`. + return unsafe { neon::pack_64_bytes01_neon(chunk64) }; + } + #[cfg(target_arch = "x86_64")] + { + if x86::features().avx2 { + // SAFETY: Runtime CPUID verified `avx2` and `chunk64.len() == 64`. + return unsafe { x86::pack_64_bytes01_avx2(chunk64) }; + } + } + #[allow(unreachable_code)] + pack_64_bytes01_scalar(chunk64) +} + +#[inline] +pub(crate) fn pack_64_bytes01_scalar(chunk64: &[u8]) -> u64 { + let mut out = 0u64; + for blk in 0..8 { + let base = blk * 8; + let word = u64::from_le_bytes([ + chunk64[base], + chunk64[base + 1], + chunk64[base + 2], + chunk64[base + 3], + chunk64[base + 4], + chunk64[base + 5], + chunk64[base + 6], + chunk64[base + 7], + ]); + // Each byte is `0` or `1`: bit `8*k` * `1 << (56 - 7*k)` lands at bit `56 + k`, + // with strictly zero cross-lane carry into bits `56..64`. + let byte_bits = ((word & 0x0101_0101_0101_0101).wrapping_mul(0x0102_0408_1020_4080)) >> 56; + out |= byte_bits << (blk * 8); + } + out +} + #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] mod neon; #[cfg(target_arch = "x86_64")] diff --git a/encodings/pivco/src/simd/neon.rs b/encodings/pivco/src/simd/neon.rs index 61d3cc98995..43e10b3a61b 100644 --- a/encodings/pivco/src/simd/neon.rs +++ b/encodings/pivco/src/simd/neon.rs @@ -36,6 +36,7 @@ use core::arch::aarch64::vld1q_u8; use core::arch::aarch64::vmovn_u16; use core::arch::aarch64::vmvn_u8; use core::arch::aarch64::vpaddlq_u8; +use core::arch::aarch64::vpaddq_u8; use core::arch::aarch64::vqtbl1q_u8; use core::arch::aarch64::vqtbl2_u8; use core::arch::aarch64::vqtbl2q_u8; @@ -60,6 +61,7 @@ use core::arch::aarch64::vst1q_u8; use core::arch::aarch64::vst2q_u8; use core::arch::aarch64::vst4q_u8; use core::arch::aarch64::vtbl1_u8; +use core::arch::aarch64::vtstq_u8; use core::arch::aarch64::vzip1q_u8; use core::arch::aarch64::vzip2q_u8; @@ -684,3 +686,27 @@ pub(super) unsafe fn unpack_flat_d6_neon( } unpack_flat_tail_scalar(6, idx, len, packed, c2s, out); } + +pub(super) static BIT_WEIGHTS_16: [u8; 16] = + [1, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128]; + +/// Packs 64 `0/1` bytes into one `u64` bitmask using 4x16B pairwise reduction. +#[target_feature(enable = "neon")] +pub(super) unsafe fn pack_64_bytes01_neon(chunk64: &[u8]) -> u64 { + let ptr = chunk64.as_ptr(); + let vone = vdupq_n_u8(1); + let vweights = unsafe { vld1q_u8(BIT_WEIGHTS_16.as_ptr()) }; + let v0 = unsafe { vld1q_u8(ptr) }; + let v1 = unsafe { vld1q_u8(ptr.add(16)) }; + let v2 = unsafe { vld1q_u8(ptr.add(32)) }; + let v3 = unsafe { vld1q_u8(ptr.add(48)) }; + let w0 = vandq_u8(vtstq_u8(v0, vone), vweights); + let w1 = vandq_u8(vtstq_u8(v1, vone), vweights); + let w2 = vandq_u8(vtstq_u8(v2, vone), vweights); + let w3 = vandq_u8(vtstq_u8(v3, vone), vweights); + let t0 = vpaddq_u8(w0, w1); + let t1 = vpaddq_u8(w2, w3); + let u0 = vpaddq_u8(t0, t1); + let packed = vget_low_u8(vpaddq_u8(u0, u0)); + vget_lane_u64::<0>(vreinterpret_u64_u8(packed)) +} diff --git a/encodings/pivco/src/simd/x86.rs b/encodings/pivco/src/simd/x86.rs index de2d04fa07b..9813d0ce81a 100644 --- a/encodings/pivco/src/simd/x86.rs +++ b/encodings/pivco/src/simd/x86.rs @@ -42,6 +42,7 @@ use core::arch::x86_64::_mm256_castsi128_si256; use core::arch::x86_64::_mm256_cmpeq_epi8; use core::arch::x86_64::_mm256_inserti128_si256; use core::arch::x86_64::_mm256_loadu_si256; +use core::arch::x86_64::_mm256_movemask_epi8; use core::arch::x86_64::_mm256_or_si256; use core::arch::x86_64::_mm256_permute2x128_si256; use core::arch::x86_64::_mm256_set1_epi8; @@ -557,3 +558,14 @@ pub(super) unsafe fn unpack_flat_d6_avx2( } unpack_flat_tail_scalar(6, idx, len, packed, c2s, out); } + +#[target_feature(enable = "avx2")] +pub(super) unsafe fn pack_64_bytes01_avx2(chunk64: &[u8]) -> u64 { + let one = _mm256_set1_epi8(1); + let ptr = chunk64.as_ptr(); + let v0 = unsafe { _mm256_loadu_si256(ptr.cast()) }; + let v1 = unsafe { _mm256_loadu_si256(ptr.add(32).cast()) }; + let m0 = _mm256_movemask_epi8(_mm256_cmpeq_epi8(_mm256_and_si256(v0, one), one)) as u32; + let m1 = _mm256_movemask_epi8(_mm256_cmpeq_epi8(_mm256_and_si256(v1, one), one)) as u32; + u64::from(m0) | (u64::from(m1) << 32) +} diff --git a/encodings/pivco/src/tests.rs b/encodings/pivco/src/tests.rs index 29b7ac450d8..090d2097013 100644 --- a/encodings/pivco/src/tests.rs +++ b/encodings/pivco/src/tests.rs @@ -18,14 +18,23 @@ use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::dict::TakeExecute; +use vortex_array::arrays::filter::FilterKernel; +use vortex_array::arrays::slice::SliceReduce; use vortex_array::assert_arrays_eq; use vortex_array::buffer::BufferHandle; +use vortex_array::builtins::ArrayBuiltins; use vortex_array::compute::conformance::hegel::EncodingCheckOptions; use vortex_array::compute::conformance::hegel::check_encoding_roundtrip_and_ops; use vortex_array::compute::conformance::hegel::draw_validity_for; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; +use vortex_array::kernel::ExecuteParentKernel; +use vortex_array::scalar::Scalar; +use vortex_array::scalar_fn::builtin::compare::CompareKernel; +use vortex_array::scalar_fn::builtin::operators::CompareMode; +use vortex_array::scalar_fn::builtin::operators::CompareOperator; use vortex_array::test_harness::check_metadata; use vortex_array::validity::Validity; use vortex_buffer::Alignment; @@ -34,7 +43,12 @@ use vortex_buffer::ByteBuffer; use vortex_buffer::ByteBufferMut; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_mask::Mask; use vortex_session::VortexSession; +use vortex_zigzag::ZigZag; +use vortex_zigzag::ZigZagArraySlotsExt; +use vortex_zigzag::ZigZagSlots; +use vortex_zigzag::zigzag_encode; use crate::Pivco; use crate::PivcoArrayExt; @@ -51,6 +65,7 @@ use crate::bitmap_rans::BM_MARKER_SPARSE_ZERO; use crate::bitmap_rans::compute_bernoulli_freqs; use crate::codec::DecodeWorkspace; use crate::codec::PivcoBlockOffset; +use crate::compute::PivcoZigZagKernel; use crate::pow2_bin::MAX_SYMS; use crate::pow2_bin::encode_pow2_bin; use crate::pow2_bin::sym_max_value; @@ -69,6 +84,8 @@ use crate::simd::merge_vec_vec; use crate::simd::merge_vec_vec_in_place_left; use crate::simd::merge_vec_vec_in_place_right; use crate::simd::merge_vec_vec_scalar; +use crate::simd::pack_64_bytes01; +use crate::simd::pack_64_bytes01_scalar; use crate::simd::pack_flat_codes; use crate::simd::popcount_bits; use crate::simd::popcount_bits_scalar; @@ -80,6 +97,7 @@ use crate::tree::PivcoTree; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); vortex_array::initialize(&session); + vortex_zigzag::initialize(&session); crate::initialize(&session); session }); @@ -1425,3 +1443,257 @@ fn test_x86_merge_pshufb_tables_exhaustive_16bit() { assert_eq!(actual, expected, "mask={mask:#06x}"); } } + +fn draw_signed_primitive(tc: &TestCase, len: usize) -> PrimitiveArray { + let ptype = match tc.draw(gs::integers::().max_value(3)) { + 0 => PType::I8, + 1 => PType::I16, + 2 => PType::I32, + _ => PType::I64, + }; + let nullability = if tc.draw(gs::booleans()) { + Nullability::Nullable + } else { + Nullability::NonNullable + }; + let validity = draw_validity_for(tc, nullability, len); + let seed = tc.draw(gs::integers::()); + let mut rng = StdRng::seed_from_u64(seed); + let pattern = tc.draw(gs::integers::().max_value(3)); + + macro_rules! gen_signed { + ($T:ty) => {{ + let vals: Vec<$T> = match pattern { + 0 => { + let v = rng.random::<$T>(); + vec![v; len] + } + 1 => (0..len) + .map(|_| { + let mag = rng.random_range(0..=30i8) as $T; + if rng.random::() { -mag } else { mag } + }) + .collect(), + 2 => { + let extremes: [$T; 6] = [<$T>::MIN, <$T>::MIN + 1, -1, 0, 1, <$T>::MAX]; + (0..len) + .map(|_| extremes[rng.random_range(0..extremes.len())]) + .collect() + } + _ => (0..len).map(|_| rng.random::<$T>()).collect(), + }; + PrimitiveArray::new(Buffer::from_iter(vals), validity) + }}; + } + + match ptype { + PType::I8 => gen_signed!(i8), + PType::I16 => gen_signed!(i16), + PType::I32 => gen_signed!(i32), + PType::I64 => gen_signed!(i64), + _ => unreachable!(), + } +} + +#[hegel::test(test_cases = 100, print_blob = true)] +fn hegel_zigzag_pivco_compute_ops(tc: TestCase) { + let mut ctx = SESSION.create_execution_ctx(); + let opts = draw_pivco_options(&tc); + let len = match tc.draw(gs::integers::().max_value(3)) { + 0 => 0, + 1 => tc.draw(gs::integers::().min_value(1).max_value(128)), + 2 => tc.draw(gs::integers::().min_value(129).max_value(1_050)), + _ => tc.draw(gs::integers::().min_value(1_051).max_value(2_500)), + }; + let signed = draw_signed_primitive(&tc, len); + let zz = zigzag_encode(signed.as_view()).vortex_expect("zigzag encode"); + let encoded_unsigned = zz + .encoded() + .clone() + .execute::(&mut ctx) + .vortex_expect("zigzag encoded primitive"); + let pivco_child = Pivco::encode_with_options(&encoded_unsigned, opts, &mut ctx) + .vortex_expect("encode zigzag unsigned child") + .into_array(); + let fused = ZigZag::try_new(pivco_child) + .vortex_expect("wrap ZigZag(Pivco)") + .into_array(); + + check_encoding_roundtrip_and_ops( + &tc, + &fused, + &signed.into_array(), + &EncodingCheckOptions::default(), + &mut ctx, + ) + .vortex_expect("ZigZag(Pivco) roundtrip and ops"); +} + +#[test] +fn test_compute_pushdowns_execute_without_fallback() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let len = 4_500usize; + let prim = PrimitiveArray::from_iter((0..len as u64).map(|i| match i % 20 { + 0..=14 => 0, + 15..=17 => 1, + 18 => 5, + _ => 1_024 + (i % 64), + })); + let pivco = + Pivco::encode_with_options(&prim, PivcoOptions::op_pha().with_block_shift(10), &mut ctx)?; + + // 1. SliceReduce returns `Some` and matches canonical. + let sliced = ::slice(pivco.as_view(), 500..3_600)? + .vortex_expect("SliceReduce must handle Pivco"); + assert_arrays_eq!( + sliced, + prim.clone().into_array().slice(500..3_600)?, + &mut ctx + ); + + // 2. CompareKernel (`Eq` and `Lt`) returns `Some` on OP-PHA and matches canonical. + for (op, rhs_val) in [ + (CompareOperator::Eq, 1u64), + (CompareOperator::NotEq, 5u64), + (CompareOperator::Lt, 5u64), + (CompareOperator::Gte, 32u64), + ] { + let rhs = ConstantArray::new(Scalar::from(rhs_val), len).into_array(); + let actual = ::compare(pivco.as_view(), &rhs, op, &mut ctx)? + .vortex_expect("CompareKernel must push down OP-PHA predicate"); + let expected = prim + .clone() + .into_array() + .compare(rhs, op, CompareMode::TOTAL_ORDER)?; + assert_arrays_eq!(actual, expected, &mut ctx); + } + + // 3. FilterKernel (sparse mask <= 1/8 selectivity) returns `Some` and matches canonical. + let mask = Mask::from_iter((0..len).map(|i| i % 37 == 0)); + let filtered = ::filter(pivco.as_view(), &mask, &mut ctx)? + .vortex_expect("FilterKernel must push down sparse mask"); + assert_arrays_eq!(filtered, prim.clone().into_array().filter(mask)?, &mut ctx); + + // 4. TakeExecute (sparse indices <= 1/8 selectivity, both ordered and scattered) returns `Some`. + let scattered_idx = PrimitiveArray::from_iter([ + 4_499u32, 0, 1_024, 2_050, 7, 3_100, 1_025, 1_026, 1_027, 1_028, 1_029, + ]); + let taken = ::take( + pivco.as_view(), + &scattered_idx.clone().into_array(), + &mut ctx, + )? + .vortex_expect("TakeExecute must push down sparse take"); + assert_arrays_eq!( + taken, + prim.into_array().take(scattered_idx.into_array())?, + &mut ctx + ); + + // 5. Fused `PivcoZigZagKernel` executes `ZigZag(Pivco)` directly without intermediate unsigned buffer. + let signed = PrimitiveArray::from_iter((0..2_200i32).map(|i| if i % 2 == 0 { i } else { -i })); + let zz = zigzag_encode(signed.as_view())?; + let unsigned = zz.encoded().clone().execute::(&mut ctx)?; + let child = Pivco::encode_with_options( + &unsigned, + PivcoOptions::pha().with_block_shift(10), + &mut ctx, + )?; + let fused = ZigZag::try_new(child.clone().into_array())?; + let fused_out = PivcoZigZagKernel + .execute_parent( + child.as_view(), + fused.as_view(), + ZigZagSlots::ENCODED, + &mut ctx, + )? + .vortex_expect("PivcoZigZagKernel must execute ZigZag(Pivco)"); + assert_arrays_eq!(fused_out, signed.into_array(), &mut ctx); + Ok(()) +} + +#[test] +fn test_compare_edge_cases_shift13_u64_and_root_tail_mask() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + // Non-multiple-of-64 length at block_shift = 13 to exercise root tail masking + u64 extremes. + let len = 8_219usize; + let prim = PrimitiveArray::from_iter((0..len as u64).map(|i| match i % 7 { + 0..=3 => 0, + 4 => 1, + 5 => 31, + _ => u64::MAX, + })); + let pivco = + Pivco::encode_with_options(&prim, PivcoOptions::op_pha().with_block_shift(13), &mut ctx)? + .into_array(); + + for rhs_val in [0u64, 1, 31, 32, 64, u64::MAX] { + let rhs = ConstantArray::new(Scalar::from(rhs_val), len).into_array(); + for op in [ + CompareOperator::Eq, + CompareOperator::NotEq, + CompareOperator::Lt, + CompareOperator::Lte, + CompareOperator::Gt, + CompareOperator::Gte, + ] { + let actual = pivco + .clone() + .compare(rhs.clone(), op, CompareMode::TOTAL_ORDER)?; + let expected = + prim.clone() + .into_array() + .compare(rhs.clone(), op, CompareMode::TOTAL_ORDER)?; + assert_arrays_eq!(actual, expected, &mut ctx); + } + } + + // Signed negative constant against non-negative signed PivcoArray (`i32` with nulls). + let signed_nonneg = PrimitiveArray::from_option_iter( + (0..1_100i32).map(|i| if i % 11 == 0 { None } else { Some(i % 19) }), + ); + let signed_pivco = Pivco::encode_with_options( + &signed_nonneg, + PivcoOptions::op_pha().with_block_shift(10), + &mut ctx, + )? + .into_array(); + let neg_rhs = ConstantArray::new(Scalar::from(-5i32), 1_100).into_array(); + for op in [ + CompareOperator::Eq, + CompareOperator::NotEq, + CompareOperator::Lt, + CompareOperator::Lte, + CompareOperator::Gt, + CompareOperator::Gte, + ] { + let actual = signed_pivco + .clone() + .compare(neg_rhs.clone(), op, CompareMode::TOTAL_ORDER)?; + let expected = signed_nonneg.clone().into_array().compare( + neg_rhs.clone(), + op, + CompareMode::TOTAL_ORDER, + )?; + assert_arrays_eq!(actual, expected, &mut ctx); + } + Ok(()) +} + +#[test] +fn test_simd_pack_64_bytes01_matches_scalar() { + let mut rng = StdRng::seed_from_u64(0x6401_51D0); + for case in 0..256u32 { + let chunk: [u8; 64] = match case { + 0 => [0u8; 64], + 1 => [1u8; 64], + 2..=65 => { + let mut arr = [0u8; 64]; + arr[(case - 2) as usize] = 1; + arr + } + _ => std::array::from_fn(|_| rng.random_range(0..=1u8)), + }; + assert_eq!(pack_64_bytes01(&chunk), pack_64_bytes01_scalar(&chunk)); + } +}