From 236cf8dd3910a286a5f3446b3cfaf2052ed140b7 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Mon, 23 Nov 2026 20:41:22 -0500 Subject: [PATCH] Add Affine integer encoding and default-ready AffineScheme Adds the per-chunk FastLanes Affine encoding (fastlanes.affine) with fused BitPacked/Dict decompression, chunk-pruned filter/take/compare compute kernels, and a default-ready BtrBlocks AffineScheme gated behind the unstable edition and excluded in CUDA mode. Replaces multi-mode trial cascades with a direct residual bit-width and outlier-patch pre-estimator so rejected columns incur negligible encode overhead while preserving the two-tier boundary with FoR.v2 and excluding RunEnd/BoolRunEnd ends and dictionary codes. Co-authored-by: Joe Isaacs Signed-off-by: Will Manning --- encodings/fastlanes/Cargo.toml | 4 + encodings/fastlanes/benches/affine_decode.rs | 185 +++ .../src/affine/array/affine_compress.rs | 1103 +++++++++++++++++ .../src/affine/array/affine_decompress.rs | 734 +++++++++++ encodings/fastlanes/src/affine/array/mod.rs | 142 +++ .../fastlanes/src/affine/compute/compare.rs | 834 +++++++++++++ .../fastlanes/src/affine/compute/filter.rs | 590 +++++++++ encodings/fastlanes/src/affine/compute/mod.rs | 257 ++++ .../fastlanes/src/affine/compute/take.rs | 550 ++++++++ encodings/fastlanes/src/affine/mod.rs | 24 + encodings/fastlanes/src/affine/plugin.rs | 149 +++ encodings/fastlanes/src/affine/tests.rs | 1048 ++++++++++++++++ .../fastlanes/src/affine/vtable/kernels.rs | 22 + encodings/fastlanes/src/affine/vtable/mod.rs | 226 ++++ .../fastlanes/src/affine/vtable/operations.rs | 65 + .../fastlanes/src/affine/vtable/rules.rs | 17 + .../fastlanes/src/affine/vtable/slice.rs | 36 + .../fastlanes/src/affine/vtable/validity.rs | 15 + encodings/fastlanes/src/lib.rs | 5 + scripts/codspeed_bench_counts.json | 1 + vortex-btrblocks/src/builder.rs | 8 +- .../src/schemes/integer/affine.rs | 738 +++++++++++ vortex-btrblocks/src/schemes/integer/mod.rs | 2 + vortex-btrblocks/src/session.rs | 2 + vortex-btrblocks/src/tests.rs | 6 + vortex-btrblocks/tests/for_config.rs | 2 +- vortex-compressor/src/compressor/mod.rs | 8 + .../src/declarations/unstable/mod.rs | 5 +- vortex-file/src/open.rs | 9 +- vortex-file/src/strategy.rs | 13 +- vortex-file/src/tests.rs | 15 +- .../editions/unstable/unstable2026.10.0.toml | 2 + 32 files changed, 6797 insertions(+), 20 deletions(-) create mode 100644 encodings/fastlanes/benches/affine_decode.rs create mode 100644 encodings/fastlanes/src/affine/array/affine_compress.rs create mode 100644 encodings/fastlanes/src/affine/array/affine_decompress.rs create mode 100644 encodings/fastlanes/src/affine/array/mod.rs create mode 100644 encodings/fastlanes/src/affine/compute/compare.rs create mode 100644 encodings/fastlanes/src/affine/compute/filter.rs create mode 100644 encodings/fastlanes/src/affine/compute/mod.rs create mode 100644 encodings/fastlanes/src/affine/compute/take.rs create mode 100644 encodings/fastlanes/src/affine/mod.rs create mode 100644 encodings/fastlanes/src/affine/plugin.rs create mode 100644 encodings/fastlanes/src/affine/tests.rs create mode 100644 encodings/fastlanes/src/affine/vtable/kernels.rs create mode 100644 encodings/fastlanes/src/affine/vtable/mod.rs create mode 100644 encodings/fastlanes/src/affine/vtable/operations.rs create mode 100644 encodings/fastlanes/src/affine/vtable/rules.rs create mode 100644 encodings/fastlanes/src/affine/vtable/slice.rs create mode 100644 encodings/fastlanes/src/affine/vtable/validity.rs create mode 100644 vortex-btrblocks/src/schemes/integer/affine.rs diff --git a/encodings/fastlanes/Cargo.toml b/encodings/fastlanes/Cargo.toml index 62d029d57dd..1b50076ec7e 100644 --- a/encodings/fastlanes/Cargo.toml +++ b/encodings/fastlanes/Cargo.toml @@ -96,6 +96,10 @@ harness = false name = "for_decode" harness = false +[[bench]] +name = "affine_decode" +harness = false + [[bench]] name = "patched_search" harness = false diff --git a/encodings/fastlanes/benches/affine_decode.rs b/encodings/fastlanes/benches/affine_decode.rs new file mode 100644 index 00000000000..fdf78cdfc63 --- /dev/null +++ b/encodings/fastlanes/benches/affine_decode.rs @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Benchmarks decoding Affine arrays over a BitPacked residual child, in each mode, against +//! per-chunk FoR on the same data. +//! +//! Every benchmark carries `#[cpu_features]`, so it is measured on each walltime CPU-feature leg +//! rather than in simulation: the loops under test are auto-vectorized, so the build decides +//! their speed. +//! +//! Run with `cargo bench -p vortex-fastlanes --bench affine_decode`. + +#![expect(clippy::unwrap_used)] + +use std::sync::LazyLock; + +use divan::Bencher; +use divan::counter::ItemsCount; +use mimalloc::MiMalloc; +use num_traits::AsPrimitive; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::session::AggregateFnSession; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::match_each_integer_ptype; +use vortex_array::memory::MemorySession; +use vortex_array::optimizer::kernels::KernelSession; +use vortex_array::session::ArraySession; +use vortex_array::test_harness::mark_optimized; +use vortex_error::vortex_panic; +use vortex_fastlanes::Affine; +use vortex_fastlanes::AffineArrayExt; +use vortex_fastlanes::AffineArraySlotsExt; +use vortex_fastlanes::AffineOptions; +use vortex_fastlanes::BitPacked; +use vortex_fastlanes::FoR; +use vortex_fastlanes::FoRArrayExt; +use vortex_fastlanes::FoRArraySlotsExt; +use vortex_fastlanes::FoRReferences; +use vortex_session::VortexSession; + +#[global_allocator] +static GLOBAL: MiMalloc = MiMalloc; + +fn main() { + LazyLock::force(&SESSION); + divan::main(); +} + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty() + .with::() + .with::() + .with::() + .with::(); + vortex_fastlanes::initialize(&session); + session +}); + +const LEN: usize = 64 * 1024; + +/// A deterministic xorshift stream of 16-bit noise. +fn noise() -> impl FnMut() -> i64 { + let mut x = 0x1234_5678u64; + move || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + (x % 65_536) as i64 + } +} + +/// Microsecond timestamps on a one-millisecond grid with 16 bits of spread per chunk, which a +/// common divisor narrows. +fn grid() -> PrimitiveArray { + let mut noise = noise(); + PrimitiveArray::from_iter( + (0..LEN as i64) + .map(|i| 1_672_531_200_000_000 + (i / 1024) * 1_000_000_000 + noise() * 1_000), + ) +} + +/// Nanosecond timestamps on a one-minute grid with 16 bits of jitter, which a slope fits. +fn trend() -> PrimitiveArray { + let mut noise = noise(); + PrimitiveArray::from_iter( + (0..LEN as i64).map(|i| 1_700_000_000_000_000_000 + i * 60_000_000_000 + noise()), + ) +} + +fn bit_width(array: &ArrayRef) -> u8 { + let mut ctx = SESSION.create_execution_ctx(); + let p = array.clone().execute::(&mut ctx).unwrap(); + let max = match_each_integer_ptype!(p.ptype(), |T| { + p.as_slice::() + .iter() + .map(|&v| AsPrimitive::::as_(v)) + .max() + .unwrap_or(0) + }); + u8::try_from(u64::BITS - max.leading_zeros()).unwrap() +} + +/// Bit-pack `residuals`, leaving them unpacked when they fill their type, as the compressor does. +fn pack(residuals: &ArrayRef) -> ArrayRef { + let width = bit_width(residuals); + if usize::from(width) >= residuals.dtype().as_ptype().bit_width() { + return residuals.clone(); + } + let mut ctx = SESSION.create_execution_ctx(); + BitPacked::encode(residuals, width, &mut ctx) + .unwrap() + .into_array() +} + +fn affine(values: &PrimitiveArray, options: AffineOptions) -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + let affine = Affine::encode(values, options, &mut ctx).unwrap(); + Affine::try_new( + pack(affine.encoded()), + affine.references().clone(), + affine.scales().clone(), + affine.slopes().clone(), + affine.offset(), + affine.slope_shift(), + ) + .unwrap() + .into_array() +} + +fn per_chunk_for(values: &PrimitiveArray) -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + let for_array = FoR::encode_chunked(values.clone(), &mut ctx).unwrap(); + let FoRReferences::Blocked(references) = for_array.references() else { + vortex_panic!("every chunk has its own reference"); + }; + FoR::try_new_chunked(pack(for_array.encoded()), references.clone(), 0) + .unwrap() + .into_array() +} + +fn run(bencher: Bencher, array: ArrayRef) { + mark_optimized(&array, &SESSION).unwrap(); + bencher + .counter(ItemsCount::new(LEN)) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| (*array).clone().execute::(ctx).unwrap()); +} + +#[vortex_bench_support::cpu_features] +#[divan::bench] +fn for_chunked_grid(bencher: Bencher) { + run(bencher, per_chunk_for(&grid())); +} + +#[vortex_bench_support::cpu_features] +#[divan::bench] +fn affine_for_grid(bencher: Bencher) { + run(bencher, affine(&grid(), AffineOptions::FOR)); +} + +#[vortex_bench_support::cpu_features] +#[divan::bench] +fn affine_scale_grid(bencher: Bencher) { + run(bencher, affine(&grid(), AffineOptions::SCALE)); +} + +#[vortex_bench_support::cpu_features] +#[divan::bench] +fn for_chunked_trend(bencher: Bencher) { + run(bencher, per_chunk_for(&trend())); +} + +#[vortex_bench_support::cpu_features] +#[divan::bench] +fn affine_slope_trend(bencher: Bencher) { + run(bencher, affine(&trend(), AffineOptions::SLOPE)); +} + +#[vortex_bench_support::cpu_features] +#[divan::bench] +fn affine_all_trend(bencher: Bencher) { + run(bencher, affine(&trend(), AffineOptions::ALL)); +} diff --git a/encodings/fastlanes/src/affine/array/affine_compress.rs b/encodings/fastlanes/src/affine/array/affine_compress.rs new file mode 100644 index 00000000000..949750a6780 --- /dev/null +++ b/encodings/fastlanes/src/affine/array/affine_compress.rs @@ -0,0 +1,1103 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use num_traits::AsPrimitive; +use num_traits::PrimInt; +use num_traits::WrappingSub; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::Nullability; +use vortex_array::match_each_integer_ptype; +use vortex_array::scalar::PValue; +use vortex_array::scalar::Scalar; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_mask::Mask; + +use crate::Affine; +use crate::AffineArray; +use crate::FL_CHUNK_SIZE; +use crate::affine::array::slope_term_split; +use crate::affine::array::split_slope; + +/// Which parts of the model [`Affine::encode`] may fit. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AffineOptions { + /// Divide each chunk's residuals by their greatest common divisor. + pub scale: bool, + /// Fit a linear trend to each chunk. + pub slope: bool, + /// Fit only the least-squares slope, always, as LeCo-fix does, instead of choosing the + /// narrowest of several slopes and a zero slope. Requires `slope`. + pub least_squares: bool, +} + +impl AffineOptions { + /// Per-chunk references only, equivalent to chunked FoR. + pub const FOR: Self = Self { + scale: false, + slope: false, + least_squares: false, + }; + /// Per-chunk references and common divisors. + pub const SCALE: Self = Self { + scale: true, + slope: false, + least_squares: false, + }; + /// Per-chunk references and linear trends. + pub const SLOPE: Self = Self { + scale: false, + slope: true, + least_squares: false, + }; + /// Per-chunk references, linear trends and common divisors. + pub const ALL: Self = Self { + scale: true, + slope: true, + least_squares: false, + }; + /// LeCo-fix's model: a least-squares line per chunk, with an exact fixed-point slope. + pub const LECO: Self = Self { + scale: false, + slope: true, + least_squares: true, + }; +} + +/// Direct residual bit-width + outlier patch cost estimates (in bits/value) for each candidate +/// [`AffineOptions`] mode over a sample of chunks. +#[derive(Clone, Copy, Debug)] +pub struct AffineModeEstimates { + /// Estimated bits/value for [`AffineOptions::FOR`]. + pub for_bits: f64, + /// Estimated bits/value for [`AffineOptions::SCALE`]. + pub scale_bits: f64, + /// Estimated bits/value for [`AffineOptions::SLOPE`]. + pub slope_bits: f64, + /// Estimated bits/value for [`AffineOptions::ALL`]. + pub all_bits: f64, +} + +/// The default number of fractional bits in fitted slopes. +const DEFAULT_SLOPE_SHIFT: u8 = 16; + +/// Maximum number of slope candidates tried per chunk: zero + 3 integer + 3 fractional fits. +const MAX_SLOPE_CANDIDATES: usize = 7; + +/// Valid positions within a chunk, avoiding per-chunk index allocations when all rows are valid. +#[derive(Clone, Copy)] +enum ValidPositions<'a> { + All(usize), + Indices(&'a [usize]), +} + +impl<'a> ValidPositions<'a> { + #[inline] + fn len(self) -> usize { + match self { + Self::All(len) => len, + Self::Indices(indices) => indices.len(), + } + } + + #[inline] + fn is_empty(self) -> bool { + self.len() == 0 + } +} + +/// Stack-allocated list of candidate fixed-point slopes for one chunk. +struct SlopeCandidates { + slopes: [i64; MAX_SLOPE_CANDIDATES], + len: usize, +} + +impl SlopeCandidates { + fn new_zero() -> Self { + Self { + slopes: [0; MAX_SLOPE_CANDIDATES], + len: 1, + } + } + + fn single(slope: i64) -> Self { + let mut slopes = [0; MAX_SLOPE_CANDIDATES]; + slopes[0] = slope; + Self { slopes, len: 1 } + } + + fn push_unique(&mut self, slope: i64) { + if !self.slopes[..self.len].contains(&slope) { + self.slopes[self.len] = slope; + self.len += 1; + } + } + + fn as_slice(&self) -> &[i64] { + &self.slopes[..self.len] + } +} + +impl Affine { + /// Encode `array`, fitting the parts of the model that `options` enables to each chunk. + /// + /// For every chunk the encoder tries a zero slope and, when enabled, slopes from the median + /// delta, the endpoints and a least-squares fit, each rounded to an integer and to fixed point. + /// It picks the slope whose residuals pack into the fewest bits, preferring a zero slope and an + /// integer slope on ties. The reference is the smallest residual, and the scale is the greatest + /// common divisor of the residuals above it. + pub fn encode( + array: &PrimitiveArray, + options: AffineOptions, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let validity = array.validity()?; + let mask = validity.execute_mask(array.len(), ctx)?; + match_each_integer_ptype!(array.ptype(), |T| { + encode_typed::(array.as_slice::(), validity, &mask, options) + }) + } + + /// Estimate compressed bits per value for `FOR`, `SCALE`, `SLOPE`, and `ALL` directly in + /// memory over up to `sample_chunks` evenly spaced chunks without running child cascades. + /// + /// Each mode's estimate models bit-packing + outlier patch cost from the sampled residual + /// bit-width histogram plus the per-chunk parameter overhead (`references`, `scales`, + /// `slopes`). + pub fn estimate_modes( + array: &PrimitiveArray, + sample_chunks: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let mask = array.validity()?.execute_mask(array.len(), ctx)?; + match_each_integer_ptype!(array.ptype(), |T| { + Ok(estimate_modes_typed::( + array.as_slice::(), + &mask, + sample_chunks, + )) + }) + } +} + +/// The fitted parameters of one chunk. +#[derive(Clone, Copy)] +struct ChunkModel { + reference: T, + scale: u64, + slope: i64, +} + +fn encode_typed( + values: &[T], + validity: Validity, + mask: &Mask, + options: AffineOptions, +) -> VortexResult +where + T: NativePType + PrimInt + WrappingSub + AsPrimitive + Into, + i64: AsPrimitive, + u64: AsPrimitive, +{ + let width_mask = width_mask::(); + let num_chunks = values.len().div_ceil(FL_CHUNK_SIZE); + let slope_shift = if options.slope { + choose_slope_shift(values, mask) + } else { + 0 + }; + + let mut encoded = BufferMut::::with_capacity(values.len()); + let mut references = BufferMut::::with_capacity(num_chunks); + let mut scales = BufferMut::::with_capacity(num_chunks); + let mut slopes = BufferMut::::with_capacity(num_chunks); + let mut previous_reference = T::zero(); + let mut valid_buf = Vec::with_capacity(FL_CHUNK_SIZE); + let mut residual_scratch = [T::zero(); FL_CHUNK_SIZE]; + let mut delta_scratch = [0f64; FL_CHUNK_SIZE]; + let all_valid = matches!(mask, Mask::AllTrue(_)); + + for (chunk_idx, chunk) in values.chunks(FL_CHUNK_SIZE).enumerate() { + let start = chunk_idx * FL_CHUNK_SIZE; + let valid = if all_valid { + ValidPositions::All(chunk.len()) + } else { + valid_buf.clear(); + valid_buf.extend((0..chunk.len()).filter(|&j| mask.value(start + j))); + ValidPositions::Indices(&valid_buf) + }; + + let model = if valid.is_empty() { + // Reuse the previous reference so the references compress into runs. + ChunkModel { + reference: previous_reference, + scale: 1, + slope: 0, + } + } else { + fit_chunk( + chunk, + valid, + options, + slope_shift, + &mut residual_scratch, + &mut delta_scratch, + ) + }; + previous_reference = model.reference; + + write_chunk_residuals(chunk, valid, model, slope_shift, width_mask, &mut encoded); + references.push(model.reference); + scales.push(model.scale.as_()); + slopes.push(model.slope); + } + + Affine::try_new( + narrow_residuals::(&encoded, validity), + constant_or_primitive(references.freeze()), + constant_or_primitive(scales.freeze()), + constant_or_primitive(slopes.freeze()), + 0, + slope_shift, + ) +} + +/// Write the encoded residuals of one chunk, specializing common `(scale, slope)` cases to avoid +/// unnecessary 64-bit divisions and slope evaluations. +fn write_chunk_residuals( + chunk: &[T], + valid: ValidPositions<'_>, + model: ChunkModel, + slope_shift: u8, + width_mask: u64, + encoded: &mut BufferMut, +) where + T: NativePType + PrimInt + WrappingSub + AsPrimitive, + i64: AsPrimitive, +{ + let scale = model.scale; + let is_unit_scale = scale == 1; + let scale_shift = scale.is_power_of_two().then(|| scale.trailing_zeros()); + let divide = |residual: u64| -> u64 { + if is_unit_scale { + residual + } else if let Some(shift) = scale_shift { + residual >> shift + } else { + residual / scale + } + }; + + match valid { + ValidPositions::All(_) => { + if model.slope == 0 { + if is_unit_scale { + encoded.extend_trusted( + chunk + .iter() + .map(|&v| v.wrapping_sub(&model.reference).as_() & width_mask), + ); + } else if let Some(shift) = scale_shift { + encoded.extend_trusted( + chunk.iter().map(|&v| { + (v.wrapping_sub(&model.reference).as_() & width_mask) >> shift + }), + ); + } else { + encoded.extend_trusted( + chunk.iter().map(|&v| { + (v.wrapping_sub(&model.reference).as_() & width_mask) / scale + }), + ); + } + } else { + let (whole, frac) = split_slope(model.slope, slope_shift); + let mut whole_j = 0i64; + let mut frac_j = 0u32; + for &v in chunk { + let term: T = whole_j.wrapping_add(i64::from(frac_j >> slope_shift)).as_(); + let residual: u64 = + v.wrapping_sub(&term).wrapping_sub(&model.reference).as_() & width_mask; + encoded.push(divide(residual)); + whole_j = whole_j.wrapping_add(whole); + frac_j = frac_j.wrapping_add(frac); + } + } + } + ValidPositions::Indices(valid_indices) => { + let mut valid_iter = valid_indices.iter().peekable(); + if model.slope == 0 { + for (j, &v) in chunk.iter().enumerate() { + if valid_iter.next_if(|&&vj| vj == j).is_some() { + let residual: u64 = v.wrapping_sub(&model.reference).as_() & width_mask; + encoded.push(divide(residual)); + } else { + encoded.push(0); + } + } + } else { + let (whole, frac) = split_slope(model.slope, slope_shift); + for (j, &v) in chunk.iter().enumerate() { + if valid_iter.next_if(|&&vj| vj == j).is_some() { + let term: T = slope_term_split(whole, frac, j, slope_shift).as_(); + let residual: u64 = + v.wrapping_sub(&term).wrapping_sub(&model.reference).as_() & width_mask; + encoded.push(divide(residual)); + } else { + encoded.push(0); + } + } + } + } + } +} + +/// Running histogram and parameter bounds for one candidate mode during [`estimate_modes_typed`]. +struct ModeAccumulator { + hist: [usize; 65], + max_residual: u64, + min_ref: T, + max_ref: T, + refs_constant: bool, + min_scale: u64, + max_scale: u64, + scales_constant: bool, + min_slope: i64, + max_slope: i64, + slopes_constant: bool, + chunks: usize, +} + +impl ModeAccumulator { + fn new() -> Self { + Self { + hist: [0; 65], + max_residual: 0, + min_ref: T::zero(), + max_ref: T::zero(), + refs_constant: true, + min_scale: 1, + max_scale: 1, + scales_constant: true, + min_slope: 0, + max_slope: 0, + slopes_constant: true, + chunks: 0, + } + } + + fn record_model(&mut self, model: ChunkModel) { + if self.chunks == 0 { + self.min_ref = model.reference; + self.max_ref = model.reference; + self.min_scale = model.scale; + self.max_scale = model.scale; + self.min_slope = model.slope; + self.max_slope = model.slope; + } else { + if model.reference != self.min_ref { + self.refs_constant = false; + } + if model.reference < self.min_ref { + self.min_ref = model.reference; + } + if model.reference > self.max_ref { + self.max_ref = model.reference; + } + if model.scale != self.min_scale { + self.scales_constant = false; + } + self.min_scale = self.min_scale.min(model.scale); + self.max_scale = self.max_scale.max(model.scale); + if model.slope != self.min_slope { + self.slopes_constant = false; + } + self.min_slope = self.min_slope.min(model.slope); + self.max_slope = self.max_slope.max(model.slope); + } + self.chunks += 1; + } + + fn add_chunk_hist(&mut self, chunk_hist: &[usize; 65], chunk_max: u64) { + for (dst, &count) in self.hist.iter_mut().zip(chunk_hist) { + *dst += count; + } + self.max_residual = self.max_residual.max(chunk_max); + } + + fn estimated_bits_per_value(&self, total_len: usize) -> f64 + where + T: WrappingSub + AsPrimitive, + { + if total_len == 0 { + return 0.0; + } + let max_bytes = size_of::(); + let res_bytes = match u64::BITS - self.max_residual.leading_zeros() { + 0..=8 => 1, + 9..=16 => 2, + 17..=32 => 4, + _ => 8, + } + .min(max_bytes); + let bytes_per_exception = res_bytes + 4; + let max_bw = res_bytes * 8; + + let mut num_packed = 0usize; + let mut best_bytes = total_len * bytes_per_exception; + for (bw, &freq) in self.hist[..=max_bw].iter().enumerate() { + let packed_bytes = (bw * total_len).div_ceil(8); + num_packed += freq; + let exception_bytes = (total_len - num_packed) * bytes_per_exception; + best_bytes = best_bytes.min(packed_bytes + exception_bytes); + } + + let mut total_bits = (best_bytes * 8) as f64; + let chunks = self.chunks as f64; + if !self.refs_constant { + let span = self.max_ref.wrapping_sub(&self.min_ref).as_() & width_mask::(); + total_bits += chunks * f64::from(u64::BITS - span.leading_zeros()); + } + if !self.scales_constant { + let span = self.max_scale.wrapping_sub(self.min_scale); + total_bits += chunks * f64::from(u64::BITS - span.leading_zeros()); + } + if !self.slopes_constant { + let span = self.max_slope.wrapping_sub(self.min_slope) as u64; + total_bits += chunks * f64::from(u64::BITS - span.leading_zeros()); + } + total_bits / total_len as f64 + } +} + +/// Evaluate all four modes (`FOR`, `SCALE`, `SLOPE`, `ALL`) in one pass over up to +/// `sample_chunks` evenly spaced chunks. +fn estimate_modes_typed(values: &[T], mask: &Mask, sample_chunks: usize) -> AffineModeEstimates +where + T: NativePType + PrimInt + WrappingSub + AsPrimitive, + i64: AsPrimitive, +{ + let num_chunks = values.len().div_ceil(FL_CHUNK_SIZE); + if num_chunks == 0 || sample_chunks == 0 { + return AffineModeEstimates { + for_bits: 0.0, + scale_bits: 0.0, + slope_bits: 0.0, + all_bits: 0.0, + }; + } + + let k = num_chunks.min(sample_chunks); + let sampled_chunk_idx = |i: usize| -> usize { + if num_chunks <= sample_chunks { + i + } else { + i * num_chunks / sample_chunks + } + }; + + let all_valid = matches!(mask, Mask::AllTrue(_)); + let slope_shift = choose_slope_shift_sampled(values, mask, num_chunks, sample_chunks); + let width_mask = width_mask::(); + + let mut acc_for = ModeAccumulator::::new(); + let mut acc_scale = ModeAccumulator::::new(); + let mut acc_slope = ModeAccumulator::::new(); + let mut acc_all = ModeAccumulator::::new(); + + let mut valid_buf = Vec::with_capacity(FL_CHUNK_SIZE); + let mut residuals = [T::zero(); FL_CHUNK_SIZE]; + let mut deltas = [0f64; FL_CHUNK_SIZE]; + let mut total_len = 0usize; + let mut prev_refs = [T::zero(); 4]; + + for i in 0..k { + let chunk_idx = sampled_chunk_idx(i); + let start = chunk_idx * FL_CHUNK_SIZE; + let end = (start + FL_CHUNK_SIZE).min(values.len()); + let chunk = &values[start..end]; + total_len += chunk.len(); + + let valid = if all_valid { + ValidPositions::All(chunk.len()) + } else { + valid_buf.clear(); + valid_buf.extend((0..chunk.len()).filter(|&j| mask.value(start + j))); + ValidPositions::Indices(&valid_buf) + }; + + if valid.is_empty() { + let mut empty_hist = [0usize; 65]; + empty_hist[0] = chunk.len(); + for (acc, prev_ref) in [ + (&mut acc_for, prev_refs[0]), + (&mut acc_scale, prev_refs[1]), + (&mut acc_slope, prev_refs[2]), + (&mut acc_all, prev_refs[3]), + ] { + acc.record_model(ChunkModel { + reference: prev_ref, + scale: 1, + slope: 0, + }); + acc.add_chunk_hist(&empty_hist, 0); + } + continue; + } + + let invalid_count = chunk.len() - valid.len(); + + // 1. Evaluate zero-slope models (`FOR` and `SCALE`) together in one pass. + let (for_bits_c, for_model, scale_bits_c, scale_model) = + evaluate_pair(chunk, valid, 0, slope_shift, &mut residuals); + let (for_hist, for_max) = residuals_histogram( + &residuals[..valid.len()], + for_model.reference, + 1, + width_mask, + invalid_count, + ); + let (scale_hist, scale_max) = if scale_model.scale == 1 { + (for_hist, for_max) + } else { + residuals_histogram( + &residuals[..valid.len()], + scale_model.reference, + scale_model.scale, + width_mask, + invalid_count, + ) + }; + + acc_for.record_model(for_model); + acc_for.add_chunk_hist(&for_hist, for_max); + prev_refs[0] = for_model.reference; + + acc_scale.record_model(scale_model); + acc_scale.add_chunk_hist(&scale_hist, scale_max); + prev_refs[1] = scale_model.reference; + + // 2. Evaluate non-zero slope candidates once for both `SLOPE` and `ALL`. + let mut best_slope = (for_bits_c, for_model); + let mut best_all = (scale_bits_c, scale_model); + let candidates = + slope_candidates(chunk, valid, AffineOptions::SLOPE, slope_shift, &mut deltas); + for &slope in &candidates.as_slice()[1..] { + let (s_bits, s_model, a_bits, a_model) = + evaluate_pair(chunk, valid, slope, slope_shift, &mut residuals); + if s_bits < best_slope.0 { + best_slope = (s_bits, s_model); + } + if a_bits < best_all.0 { + best_all = (a_bits, a_model); + } + } + + let (slope_hist, slope_max) = if best_slope.1.slope == 0 { + (for_hist, for_max) + } else { + fill_slope_residuals( + chunk, + valid, + best_slope.1.slope, + slope_shift, + &mut residuals, + ); + residuals_histogram( + &residuals[..valid.len()], + best_slope.1.reference, + 1, + width_mask, + invalid_count, + ) + }; + acc_slope.record_model(best_slope.1); + acc_slope.add_chunk_hist(&slope_hist, slope_max); + prev_refs[2] = best_slope.1.reference; + + let (all_hist, all_max) = if best_all.1.slope == 0 { + (scale_hist, scale_max) + } else if best_all.1.slope == best_slope.1.slope && best_all.1.scale == 1 { + (slope_hist, slope_max) + } else { + if best_all.1.slope != best_slope.1.slope { + fill_slope_residuals(chunk, valid, best_all.1.slope, slope_shift, &mut residuals); + } + residuals_histogram( + &residuals[..valid.len()], + best_all.1.reference, + best_all.1.scale, + width_mask, + invalid_count, + ) + }; + acc_all.record_model(best_all.1); + acc_all.add_chunk_hist(&all_hist, all_max); + prev_refs[3] = best_all.1.reference; + } + + AffineModeEstimates { + for_bits: acc_for.estimated_bits_per_value(total_len), + scale_bits: acc_scale.estimated_bits_per_value(total_len), + slope_bits: acc_slope.estimated_bits_per_value(total_len), + all_bits: acc_all.estimated_bits_per_value(total_len), + } +} + +/// Build the 65-bin bit-width histogram and max residual for one chunk's slope-removed values. +fn residuals_histogram( + residuals: &[T], + reference: T, + scale: u64, + width_mask: u64, + invalid_count: usize, +) -> ([usize; 65], u64) +where + T: NativePType + WrappingSub + AsPrimitive, +{ + let mut hist = [0usize; 65]; + hist[0] = invalid_count; + let mut max_val = 0u64; + if scale == 1 { + for &r in residuals { + let above = r.wrapping_sub(&reference).as_() & width_mask; + max_val = max_val.max(above); + hist[(u64::BITS - above.leading_zeros()) as usize] += 1; + } + } else if scale.is_power_of_two() { + let shift = scale.trailing_zeros(); + for &r in residuals { + let above = (r.wrapping_sub(&reference).as_() & width_mask) >> shift; + max_val = max_val.max(above); + hist[(u64::BITS - above.leading_zeros()) as usize] += 1; + } + } else { + for &r in residuals { + let above = (r.wrapping_sub(&reference).as_() & width_mask) / scale; + max_val = max_val.max(above); + hist[(u64::BITS - above.leading_zeros()) as usize] += 1; + } + } + (hist, max_val) +} + +/// Fill `residuals[..valid.len()]` with `chunk[j] - slope_term(slope, j, shift)` and return its +/// minimum (`reference`). +fn fill_slope_residuals( + chunk: &[T], + valid: ValidPositions<'_>, + slope: i64, + slope_shift: u8, + residuals: &mut [T; FL_CHUNK_SIZE], +) -> T +where + T: NativePType + PrimInt + WrappingSub, + i64: AsPrimitive, +{ + match valid { + ValidPositions::All(len) => { + if slope == 0 { + let dst = &mut residuals[..len]; + dst.copy_from_slice(&chunk[..len]); + dst.iter().copied().min().unwrap_or_else(T::zero) + } else { + let (whole, frac) = split_slope(slope, slope_shift); + let mut whole_j = 0i64; + let mut frac_j = 0u32; + let mut min_val = T::max_value(); + for (dst, &v) in residuals[..len].iter_mut().zip(&chunk[..len]) { + let term: T = whole_j.wrapping_add(i64::from(frac_j >> slope_shift)).as_(); + let r = v.wrapping_sub(&term); + *dst = r; + if r < min_val { + min_val = r; + } + whole_j = whole_j.wrapping_add(whole); + frac_j = frac_j.wrapping_add(frac); + } + min_val + } + } + ValidPositions::Indices(indices) => { + if slope == 0 { + let mut min_val = T::max_value(); + for (dst, &j) in residuals[..indices.len()].iter_mut().zip(indices) { + let r = chunk[j]; + *dst = r; + if r < min_val { + min_val = r; + } + } + min_val + } else { + let (whole, frac) = split_slope(slope, slope_shift); + let mut min_val = T::max_value(); + for (dst, &j) in residuals[..indices.len()].iter_mut().zip(indices) { + let term: T = slope_term_split(whole, frac, j, slope_shift).as_(); + let r = chunk[j].wrapping_sub(&term); + *dst = r; + if r < min_val { + min_val = r; + } + } + min_val + } + } + } +} + +/// Evaluate both unscaled (`scale = 1`) and scaled (`scale = gcd`) models for `slope` in one pass. +fn evaluate_pair( + chunk: &[T], + valid: ValidPositions<'_>, + slope: i64, + slope_shift: u8, + residuals: &mut [T; FL_CHUNK_SIZE], +) -> (u32, ChunkModel, u32, ChunkModel) +where + T: NativePType + PrimInt + WrappingSub + AsPrimitive, + i64: AsPrimitive, +{ + let width_mask = width_mask::(); + let reference = fill_slope_residuals(chunk, valid, slope, slope_shift, residuals); + + let mut max = 0u64; + let mut gcd = 0u64; + for &r in &residuals[..valid.len()] { + let above: u64 = r.wrapping_sub(&reference).as_() & width_mask; + max = max.max(above); + if gcd != 1 { + gcd = gcd_u64(gcd, above); + } + } + let scale = gcd.max(1); + let unscaled_bits = u64::BITS - max.leading_zeros(); + let scaled_bits = u64::BITS - (max / scale).leading_zeros(); + ( + unscaled_bits, + ChunkModel { + reference, + scale: 1, + slope, + }, + scaled_bits, + ChunkModel { + reference, + scale, + slope, + }, + ) +} + +/// Fit the model with the narrowest residuals to the `valid` positions of `chunk`. +fn fit_chunk( + chunk: &[T], + valid: ValidPositions<'_>, + options: AffineOptions, + slope_shift: u8, + residuals: &mut [T; FL_CHUNK_SIZE], + deltas: &mut [f64; FL_CHUNK_SIZE], +) -> ChunkModel +where + T: NativePType + PrimInt + WrappingSub + AsPrimitive, + i64: AsPrimitive, +{ + let mut best: Option<(u32, ChunkModel)> = None; + let candidates = slope_candidates(chunk, valid, options, slope_shift, deltas); + for &slope in candidates.as_slice() { + let (bits, model) = evaluate(chunk, valid, slope, options.scale, slope_shift, residuals); + if best.is_none_or(|(best_bits, _)| bits < best_bits) { + best = Some((bits, model)); + } + } + best.map(|(_, model)| model) + .vortex_expect("the zero slope is always a candidate") +} + +/// The bit width of the residuals of `slope`, and the model that produces them. +fn evaluate( + chunk: &[T], + valid: ValidPositions<'_>, + slope: i64, + use_scale: bool, + slope_shift: u8, + residuals: &mut [T; FL_CHUNK_SIZE], +) -> (u32, ChunkModel) +where + T: NativePType + PrimInt + WrappingSub + AsPrimitive, + i64: AsPrimitive, +{ + let width_mask = width_mask::(); + let reference = fill_slope_residuals(chunk, valid, slope, slope_shift, residuals); + + let mut max = 0u64; + let mut gcd = 0u64; + if use_scale { + for &r in &residuals[..valid.len()] { + let above: u64 = r.wrapping_sub(&reference).as_() & width_mask; + max = max.max(above); + if gcd != 1 { + gcd = gcd_u64(gcd, above); + } + } + } else { + for &r in &residuals[..valid.len()] { + let above: u64 = r.wrapping_sub(&reference).as_() & width_mask; + max = max.max(above); + } + } + let scale = if use_scale { gcd.max(1) } else { 1 }; + let bits = u64::BITS - (max / scale).leading_zeros(); + ( + bits, + ChunkModel { + reference, + scale, + slope, + }, + ) +} + +/// Candidate fixed-point slopes for a chunk, starting with zero, then integer slopes, then +/// fractional ones, so that ties keep the simpler model. +fn slope_candidates( + chunk: &[T], + valid: ValidPositions<'_>, + options: AffineOptions, + slope_shift: u8, + deltas: &mut [f64; FL_CHUNK_SIZE], +) -> SlopeCandidates { + let mut candidates = SlopeCandidates::new_zero(); + if !options.slope || valid.len() < 2 { + return candidates; + } + + let (median, endpoint, least_squares) = match valid { + ValidPositions::All(len) => { + let mut prev = chunk[0].to_f64().unwrap_or(0.0); + let first = prev; + let mut sum_y = first; + for (k, &v) in chunk[1..len].iter().enumerate() { + let y = v.to_f64().unwrap_or(0.0); + deltas[k] = y - prev; + sum_y += y; + prev = y; + } + let delta_count = len - 1; + let mid = delta_count / 2; + deltas[..delta_count].select_nth_unstable_by(mid, f64::total_cmp); + let median = deltas[mid]; + let endpoint = (prev - first) / (delta_count as f64); + + let n = len as f64; + let mean_x = (delta_count as f64) * 0.5; + let mean_y = sum_y / n; + let (mut sxy, mut sxx) = (0.0, 0.0); + for (j, &v) in chunk[..len].iter().enumerate() { + let dx = j as f64 - mean_x; + let dy = v.to_f64().unwrap_or(0.0) - mean_y; + sxy += dx * dy; + sxx += dx * dx; + } + let least_squares = if sxx == 0.0 { 0.0 } else { sxy / sxx }; + (median, endpoint, least_squares) + } + ValidPositions::Indices(indices) => { + let count = indices.len(); + let mut prev_x = indices[0] as f64; + let mut prev_y = chunk[indices[0]].to_f64().unwrap_or(0.0); + let (first_x, first_y) = (prev_x, prev_y); + let mut sum_x = prev_x; + let mut sum_y = prev_y; + for (slot, &pos) in indices[1..].iter().enumerate() { + let x_val = pos as f64; + let y_val = chunk[pos].to_f64().unwrap_or(0.0); + deltas[slot] = (y_val - prev_y) / (x_val - prev_x); + sum_x += x_val; + sum_y += y_val; + prev_x = x_val; + prev_y = y_val; + } + let delta_count = count - 1; + let mid = delta_count / 2; + deltas[..delta_count].select_nth_unstable_by(mid, f64::total_cmp); + let median = deltas[mid]; + let endpoint = (prev_y - first_y) / (prev_x - first_x); + + let mean_x = sum_x / (count as f64); + let mean_y = sum_y / (count as f64); + let (mut sxy, mut sxx) = (0.0, 0.0); + for &pos in indices { + let dx = pos as f64 - mean_x; + let dy = chunk[pos].to_f64().unwrap_or(0.0) - mean_y; + sxy += dx * dy; + sxx += dx * dx; + } + let least_squares = if sxx == 0.0 { 0.0 } else { sxy / sxx }; + (median, endpoint, least_squares) + } + }; + + let unit = f64::from(1u32 << slope_shift); + if options.least_squares { + let slope = (least_squares * unit).round(); + return SlopeCandidates::single( + if slope.is_finite() && slope.abs() * (FL_CHUNK_SIZE as f64) < i64::MAX as f64 { + slope as i64 + } else { + 0 + }, + ); + } + let fits = [median, endpoint, least_squares]; + let integer = fits.iter().map(|s| s.round() * unit); + let fractional = fits.iter().map(|s| (s * unit).round()); + for slope in integer.chain(fractional) { + // Slopes whose term could overflow `i64` would only ever give wide residuals. + if slope.is_finite() && slope.abs() * (FL_CHUNK_SIZE as f64) < i64::MAX as f64 { + candidates.push_unique(slope as i64); + } + } + candidates +} + +/// Pick the number of fractional slope bits, so that the steepest chunk's slope term still fits +/// in `i64` across a whole chunk. +fn choose_slope_shift(values: &[T], mask: &Mask) -> u8 { + let all_valid = matches!(mask, Mask::AllTrue(_)); + let mut steepest = 0f64; + for (chunk_idx, chunk) in values.chunks(FL_CHUNK_SIZE).enumerate() { + let start = chunk_idx * FL_CHUNK_SIZE; + let (first, last) = if all_valid { + ((!chunk.is_empty()).then_some(0), chunk.len().checked_sub(1)) + } else { + ( + (0..chunk.len()).find(|&j| mask.value(start + j)), + (0..chunk.len()).rev().find(|&j| mask.value(start + j)), + ) + }; + if let (Some(first), Some(last)) = (first, last) + && last > first + { + let rise = chunk[last].to_f64().unwrap_or(0.0) - chunk[first].to_f64().unwrap_or(0.0); + steepest = steepest.max((rise / (last - first) as f64).abs()); + } + } + slope_shift_from_steepest(steepest) +} + +fn choose_slope_shift_sampled( + values: &[T], + mask: &Mask, + num_chunks: usize, + sample_chunks: usize, +) -> u8 { + let all_valid = matches!(mask, Mask::AllTrue(_)); + let k = num_chunks.min(sample_chunks); + let mut steepest = 0f64; + for i in 0..k { + let chunk_idx = if num_chunks <= sample_chunks { + i + } else { + i * num_chunks / sample_chunks + }; + let start = chunk_idx * FL_CHUNK_SIZE; + let end = (start + FL_CHUNK_SIZE).min(values.len()); + let chunk = &values[start..end]; + let (first, last) = if all_valid { + ((!chunk.is_empty()).then_some(0), chunk.len().checked_sub(1)) + } else { + ( + (0..chunk.len()).find(|&j| mask.value(start + j)), + (0..chunk.len()).rev().find(|&j| mask.value(start + j)), + ) + }; + if let (Some(first), Some(last)) = (first, last) + && last > first + { + let rise = chunk[last].to_f64().unwrap_or(0.0) - chunk[first].to_f64().unwrap_or(0.0); + steepest = steepest.max((rise / (last - first) as f64).abs()); + } + } + slope_shift_from_steepest(steepest) +} + +#[inline] +fn slope_shift_from_steepest(steepest: f64) -> u8 { + // Leave one bit of headroom below `i64::MAX` for rounding. + let headroom = 62.0 - (FL_CHUNK_SIZE as f64).log2() - (steepest + 1.0).log2(); + headroom.clamp(0.0, f64::from(DEFAULT_SLOPE_SHIFT)) as u8 +} + +fn gcd_u64(mut a: u64, mut b: u64) -> u64 { + while b != 0 { + (a, b) = (b, a % b); + } + a +} + +/// The mask that keeps the low `T::BITS` bits of a `u64`. +fn width_mask() -> u64 { + match size_of::() { + 8 => u64::MAX, + bytes => (1u64 << (bytes * 8)) - 1, + } +} + +/// The residuals as the narrowest unsigned integer array that holds the largest of them, and is no +/// wider than the array's type. Narrow residuals unpack into narrow lanes and multiply as +/// `32 x 32 -> 64` bits, which decodes much faster than full-width residuals. +fn narrow_residuals(encoded: &[u64], validity: Validity) -> ArrayRef +where + u64: AsPrimitive, +{ + let max_bytes = size_of::(); + let max = encoded.iter().copied().max().unwrap_or(0); + let bytes = match u64::BITS - max.leading_zeros() { + 0..=8 => 1, + 9..=16 => 2, + 17..=32 => 4, + _ => 8, + } + .min(max_bytes); + match if bytes == max_bytes { 0 } else { bytes } { + 1 => PrimitiveArray::new( + encoded.iter().map(|&e| e as u8).collect::>(), + validity, + ), + 2 => PrimitiveArray::new( + encoded.iter().map(|&e| e as u16).collect::>(), + validity, + ), + 4 => PrimitiveArray::new( + encoded.iter().map(|&e| e as u32).collect::>(), + validity, + ), + // As wide as the array's type: keep that type, so decoding reuses FoR's fused kernels. + _ => PrimitiveArray::new( + encoded.iter().map(|&e| e.as_()).collect::>(), + validity, + ), + } + .into_array() +} + +/// A constant array when every value matches, otherwise a primitive array. +fn constant_or_primitive>(values: Buffer) -> ArrayRef { + match values.first() { + Some(&first) if values.iter().all(|&v| v == first) => ConstantArray::new( + Scalar::primitive(first, Nullability::NonNullable), + values.len(), + ) + .into_array(), + _ => PrimitiveArray::new(values, Validity::NonNullable).into_array(), + } +} diff --git a/encodings/fastlanes/src/affine/array/affine_decompress.rs b/encodings/fastlanes/src/affine/array/affine_decompress.rs new file mode 100644 index 00000000000..e4989d8cef1 --- /dev/null +++ b/encodings/fastlanes/src/affine/array/affine_decompress.rs @@ -0,0 +1,734 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::iter; +use std::mem; +use std::mem::MaybeUninit; +use std::ops::Range; + +use fastlanes::BitPacking; +use fastlanes::FoR; +use num_traits::AsPrimitive; +use num_traits::PrimInt; +use num_traits::WrappingAdd; +use num_traits::WrappingMul; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::Dict; +use vortex_array::arrays::Primitive; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::dict::DictArraySlotsExt; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::PhysicalPType; +use vortex_array::match_each_integer_ptype; +use vortex_array::match_each_unsigned_integer_ptype; +use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; + +use crate::Affine; +use crate::AffineArray; +use crate::BitPacked; +use crate::BitPackedArrayExt; +use crate::FL_CHUNK_SIZE; +use crate::affine::array::AffineArrayExt; +use crate::affine::array::AffineArraySlotsExt; +use crate::affine::array::slope_term; +use crate::affine::array::slope_term_split; +use crate::affine::array::split_slope; +use crate::unpack_iter::for_each_packed_chunk; + +/// One parameter per chunk: either shared by every chunk or read from a primitive child. +pub(crate) enum ChunkParam { + Constant(T), + PerChunk(Buffer), +} + +impl ChunkParam { + /// Read a per-chunk parameter child, which must be constant or primitive. + pub(crate) fn from_child(child: &ArrayRef) -> Self { + match child.as_constant() { + Some(scalar) => Self::Constant( + scalar + .as_primitive() + .typed_value::() + .vortex_expect("Affine parameters are non-nullable"), + ), + None => Self::PerChunk(child.as_::().into_owned().into_buffer::()), + } + } + + /// Execute a per-chunk parameter child if it is not already constant. + pub(crate) fn execute_from_child( + child: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + match child.as_constant() { + Some(scalar) => Ok(Self::Constant( + scalar + .as_primitive() + .typed_value::() + .vortex_expect("Affine parameters are non-nullable"), + )), + None => Ok(Self::PerChunk( + child + .clone() + .execute::(ctx)? + .into_buffer::(), + )), + } + } + + #[inline] + pub(crate) fn get(&self, chunk: usize) -> T { + match self { + Self::Constant(value) => *value, + Self::PerChunk(values) => values[chunk], + } + } +} + +/// Decode an Affine array whose non-constant parameters are primitive, and whose `encoded` child +/// is primitive, dictionary-encoded, or bit-packed with the same offset. +pub fn decompress(array: &AffineArray, ctx: &mut ExecutionCtx) -> VortexResult { + if let Some(dict) = array.encoded().as_opt::() + && dict.values().len() <= MAX_FUSED_DICT_VALUES + { + let codes = dict.codes().clone().execute::(ctx)?; + let values = dict.values().clone().execute::(ctx)?; + if codes.all_valid(ctx)? && values.all_valid(ctx)? { + return match_each_integer_ptype!(array.ptype(), |T| { + match_each_unsigned_integer_ptype!(codes.ptype(), |C| { + decompress_dict::(array, &codes, &values, ctx) + }) + }); + } + } + if array.encoded().is::() { + // Not fusable: decode the dictionary, then the residuals as usual. + let encoded = array + .encoded() + .clone() + .execute::(ctx)? + .into_array(); + let array = Affine::try_new( + encoded, + array.references().clone(), + array.scales().clone(), + array.slopes().clone(), + array.offset(), + array.slope_shift(), + )?; + return decompress(&array, ctx); + } + let encoded_ptype = array.encoded().dtype().as_ptype(); + if encoded_ptype.byte_width() < array.ptype().byte_width() { + return match_each_integer_ptype!(array.ptype(), |T| { + match_each_unsigned_integer_ptype!(encoded_ptype, |U| { + decompress_narrow::(array, ctx) + }) + }); + } + match array.encoded().as_opt::() { + Some(bp) if bp.offset() == array.offset() => { + match_each_integer_ptype!(array.ptype(), |T| { + fused_decompress_typed::(array, bp, ctx) + }) + } + _ => match_each_integer_ptype!(array.ptype(), |T| { decompress_typed::(array, ctx) }), + } +} + +fn decompress_typed(array: &AffineArray, _ctx: &mut ExecutionCtx) -> VortexResult +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, +{ + let encoded = array.encoded().as_::().into_owned(); + if encoded.is_empty() { + return Ok(encoded); + } + let validity = encoded.validity()?; + let params = Params::::new(array); + let mut values = encoded.into_buffer::().into_mut(); + // The first chunk may be partial when the array was sliced. + let first_len = (FL_CHUNK_SIZE - params.offset).min(values.len()); + let (first, rest) = values.split_at_mut(first_len); + let chunks = + iter::once((params.offset, first)).chain(rest.chunks_mut(FL_CHUNK_SIZE).map(|c| (0, c))); + for (chunk_idx, (start, chunk)) in chunks.enumerate() { + params.apply_chunk(chunk_idx, start, chunk); + } + Ok(PrimitiveArray::new(values.freeze(), validity)) +} + +/// Unpack each bit-packed chunk straight into the output and apply its model while it is in L1. +/// +/// Chunks whose scale is one and slope is zero decode with FastLanes' fused unpack-and-add, exactly +/// like [`FoR`](crate::FoR). Partial first and last chunks unpack into a scratch chunk. +fn fused_decompress_typed( + array: &AffineArray, + bp: ArrayView<'_, BitPacked>, + ctx: &mut ExecutionCtx, +) -> VortexResult +where + T: PhysicalPType + + AsPrimitive + + PrimInt + + WrappingAdd + + WrappingMul, + i64: AsPrimitive, +{ + let len = bp.len(); + let params = Params::::new(array); + let offset = usize::from(bp.offset()); + let mut values = BufferMut::::with_capacity_in(len, ctx.allocator().clone()); + // SAFETY: `T::Physical` is `T` with the same size and alignment, and every unpack below + // initializes the whole destination before it is read. + let output = unsafe { + mem::transmute::<&mut [MaybeUninit], &mut [T::Physical]>( + &mut values.spare_capacity_mut()[..len], + ) + }; + let mut scratch = [T::Physical::default(); FL_CHUNK_SIZE]; + for_each_bitpacked_chunk::(bp, |packed, bit_width, range| { + let chunk_idx = range.start / FL_CHUNK_SIZE; + // `range` counts from the start of the first chunk, and the output starts at `offset`. + let skip = offset.saturating_sub(range.start); + let dst = &mut output[range.start + skip - offset..range.end - offset]; + if dst.len() == FL_CHUNK_SIZE { + if params.is_flat(chunk_idx) { + let reference = params.references.get(chunk_idx).as_(); + // SAFETY: `packed` holds one chunk at `bit_width` and `dst` is a whole chunk. + unsafe { FoR::unchecked_unfor_pack(bit_width, packed, reference, dst) }; + } else { + // SAFETY: as above. + unsafe { BitPacking::unchecked_unpack(bit_width, packed, dst) }; + params.apply_chunk(chunk_idx, 0, physical_as_logical::(dst)); + } + } else { + // SAFETY: `packed` holds one chunk at `bit_width` and `scratch` is a whole chunk. + unsafe { BitPacking::unchecked_unpack(bit_width, packed, &mut scratch) }; + let chunk = &mut scratch[skip..range.len()]; + params.apply_chunk(chunk_idx, skip, physical_as_logical::(chunk)); + dst.copy_from_slice(chunk); + } + })?; + // SAFETY: the loop above initialized every value. + unsafe { values.set_len(len) }; + + if let Some(patches) = bp.patches() { + let indices = patches.indices().clone().execute::(ctx)?; + let patch_values = patches.values().clone().execute::(ctx)?; + let patch_values = patch_values.as_slice::(); + match_each_unsigned_integer_ptype!(indices.ptype(), |P| { + for (&index, &value) in indices.as_slice::

().iter().zip(patch_values) { + let index =

>::as_(index) - patches.offset(); + let position = offset + index; + values[index] = + params.decode(position / FL_CHUNK_SIZE, position % FL_CHUNK_SIZE, value); + } + }); + } + Ok(PrimitiveArray::new(values.freeze(), bp.validity()?)) +} + +/// Call `f` with each packed chunk of `bp`, its bit width, and its range of positions counted from +/// the start of the first chunk. +fn for_each_bitpacked_chunk( + bp: ArrayView<'_, BitPacked>, + mut f: impl FnMut(&[T::Physical], usize, Range), +) -> VortexResult<()> +where + T::Physical: BitPacking, +{ + let packed = bp.packed_slice::(); + let offset = usize::from(bp.offset()); + let bit_width = usize::from(bp.bit_width()); + for_each_packed_chunk::(packed, bit_width, offset, bp.len(), |packed, range| { + f(packed, bit_width, range) + }) +} + +/// Decode residuals stored in the unsigned type `U`, narrower than the array's type `T`. +/// +/// Each chunk unpacks into a narrow scratch chunk that stays in L1, then one pass widens, scales, +/// adds the reference and slope, and writes every output value once. +fn decompress_narrow( + array: &AffineArray, + ctx: &mut ExecutionCtx, +) -> VortexResult +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul + AsPrimitive, + i64: AsPrimitive, + u64: AsPrimitive, + U: PhysicalPType + BitPacking + AsPrimitive + AsPrimitive, +{ + let len = array.len(); + if len == 0 { + return Ok(PrimitiveArray::new( + Buffer::::empty(), + array.encoded().validity()?, + )); + } + let params = Params::::new(array); + let mut values = BufferMut::::with_capacity_in(len, ctx.allocator().clone()); + let output = &mut values.spare_capacity_mut()[..len]; + + let validity = match array.encoded().as_opt::() { + Some(bp) if bp.offset() == array.offset() => { + let offset = usize::from(bp.offset()); + let mut scratch = [U::default(); FL_CHUNK_SIZE]; + for_each_bitpacked_chunk::(bp, |packed, bit_width, range| { + // SAFETY: `packed` holds one chunk at `bit_width` and `scratch` is a whole chunk. + unsafe { BitPacking::unchecked_unpack(bit_width, packed, &mut scratch) }; + // `range` counts from the start of the first chunk; the output starts at `offset`. + let skip = offset.saturating_sub(range.start); + let dst = &mut output[range.start + skip - offset..range.end - offset]; + let chunk_idx = range.start / FL_CHUNK_SIZE; + params.apply_narrow(chunk_idx, skip, &scratch[skip..range.len()], dst); + })?; + // SAFETY: the loop above initialized every value. + unsafe { values.set_len(len) }; + if let Some(patches) = bp.patches() { + let indices = patches.indices().clone().execute::(ctx)?; + let patch_values = patches.values().clone().execute::(ctx)?; + let patch_values = patch_values.as_slice::(); + match_each_unsigned_integer_ptype!(indices.ptype(), |P| { + for (&index, &value) in indices.as_slice::

().iter().zip(patch_values) { + let index =

>::as_(index) - patches.offset(); + let position = offset + index; + values[index] = params.decode( + position / FL_CHUNK_SIZE, + position % FL_CHUNK_SIZE, + value.as_(), + ); + } + }); + } + bp.validity()? + } + _ => { + let encoded = array.encoded().as_::().into_owned(); + let residuals = encoded.as_slice::(); + let first_len = (FL_CHUNK_SIZE - params.offset).min(len); + let (first_src, rest_src) = residuals.split_at(first_len); + let (first_dst, rest_dst) = output.split_at_mut(first_len); + let chunks = iter::once((params.offset, first_src, first_dst)).chain( + rest_src + .chunks(FL_CHUNK_SIZE) + .zip(rest_dst.chunks_mut(FL_CHUNK_SIZE)) + .map(|(src, dst)| (0, src, dst)), + ); + for (chunk_idx, (start, src, dst)) in chunks.enumerate() { + params.apply_narrow(chunk_idx, start, src, dst); + } + // SAFETY: the loop above initialized every value. + unsafe { values.set_len(len) }; + encoded.validity()? + } + }; + Ok(PrimitiveArray::new(values.freeze(), validity)) +} + +/// The largest dictionary [`decompress_dict`] scales per chunk: building the table costs one +/// multiply-add per entry per chunk, at most a quarter of one per value. +const MAX_FUSED_DICT_VALUES: usize = 256; + +/// Decode dictionary-encoded residuals without materializing them. +/// +/// Per chunk, the dictionary is scaled and offset once into a table, `table[k] = values[k] * +/// scale + reference`, so each value is one lookup plus the slope term. +fn decompress_dict( + array: &AffineArray, + codes: &PrimitiveArray, + values: &PrimitiveArray, + ctx: &mut ExecutionCtx, +) -> VortexResult +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, + C: NativePType + AsPrimitive, +{ + let len = array.len(); + let validity = array.encoded().validity()?; + if len == 0 { + return Ok(PrimitiveArray::new(Buffer::::empty(), validity)); + } + let params = Params::::new(array); + // Residuals of any integer type, as `T` by the same truncation the other paths use. + let residuals: Vec = match_each_integer_ptype!(values.ptype(), |V| { + values + .as_slice::() + .iter() + .map(|&v| >::as_(AsPrimitive::::as_(v))) + .collect() + }); + let codes = codes.as_slice::(); + let mut table = vec![T::zero(); residuals.len()]; + let mut out = BufferMut::::with_capacity_in(len, ctx.allocator().clone()); + let output = &mut out.spare_capacity_mut()[..len]; + + let first_len = (FL_CHUNK_SIZE - params.offset).min(len); + let (first_codes, rest_codes) = codes.split_at(first_len); + let (first_dst, rest_dst) = output.split_at_mut(first_len); + let chunks = iter::once((params.offset, first_codes, first_dst)).chain( + rest_codes + .chunks(FL_CHUNK_SIZE) + .zip(rest_dst.chunks_mut(FL_CHUNK_SIZE)) + .map(|(codes, dst)| (0, codes, dst)), + ); + for (chunk_idx, (start, codes, dst)) in chunks.enumerate() { + let reference = params.references.get(chunk_idx); + let scale = params.scales.get(chunk_idx); + for (entry, &residual) in table.iter_mut().zip(&residuals) { + *entry = residual.wrapping_mul(&scale).wrapping_add(&reference); + } + let slope = params.slopes.get(chunk_idx); + if slope == 0 { + for (o, &code) in dst.iter_mut().zip(codes) { + o.write(table[code.as_()]); + } + } else { + let (whole, frac) = split_slope(slope, params.shift); + let mut whole_j = slope_term_split(whole, 0, start, 0); + let mut frac_j = frac.wrapping_mul(start as u32); + for (o, &code) in dst.iter_mut().zip(codes) { + let term = whole_j.wrapping_add(i64::from(frac_j >> params.shift)); + o.write(table[code.as_()].wrapping_add(&term.as_())); + whole_j = whole_j.wrapping_add(whole); + frac_j = frac_j.wrapping_add(frac); + } + } + } + // SAFETY: the loop above initialized every value. + unsafe { out.set_len(len) }; + Ok(PrimitiveArray::new(out.freeze(), validity)) +} + +/// View unpacked physical values as the array's logical type. +#[inline] +pub(crate) fn physical_as_logical(values: &mut [T::Physical]) -> &mut [T] { + // SAFETY: `T::Physical` is `T` with the same size and alignment, and the model's wrapping + // arithmetic is the same in two's complement whichever signedness `T` has. + unsafe { mem::transmute::<&mut [T::Physical], &mut [T]>(values) } +} + +pub(crate) struct Params { + pub(crate) references: ChunkParam, + pub(crate) scales: ChunkParam, + pub(crate) slopes: ChunkParam, + pub(crate) offset: usize, + pub(crate) shift: u8, +} + +impl Params { + pub(crate) fn new(array: &AffineArray) -> Self { + Self { + references: ChunkParam::from_child(array.references()), + scales: ChunkParam::from_child(array.scales()), + slopes: ChunkParam::from_child(array.slopes()), + offset: usize::from(array.offset()), + shift: array.slope_shift(), + } + } + + /// Execute any non-constant parameter children so kernels can index parameters per chunk. + pub(crate) fn execute( + array: ArrayView<'_, Affine>, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + Ok(Self { + references: ChunkParam::execute_from_child(array.references(), ctx)?, + scales: ChunkParam::execute_from_child(array.scales(), ctx)?, + slopes: ChunkParam::execute_from_child(array.slopes(), ctx)?, + offset: usize::from(array.offset()), + shift: array.slope_shift(), + }) + } + + /// Whether every chunk shares one constant reference, one constant scale, and a zero slope. + #[inline] + pub(crate) fn all_constant_flat(&self) -> bool { + matches!(self.references, ChunkParam::Constant(_)) + && matches!(self.scales, ChunkParam::Constant(_)) + && matches!(self.slopes, ChunkParam::Constant(0)) + } + + /// Whether every chunk has a zero slope. + #[inline] + pub(crate) fn slopes_are_zero(&self) -> bool { + matches!(self.slopes, ChunkParam::Constant(0)) + } +} + +impl Params +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, +{ + /// Whether chunk `chunk_idx` has a scale of one and a slope of zero, so it is plain FoR. + #[inline] + pub(crate) fn is_flat(&self, chunk_idx: usize) -> bool { + self.scales.get(chunk_idx) == T::one() && self.slopes.get(chunk_idx) == 0 + } + + /// Turn the residuals of chunk `chunk_idx`, whose first value sits at position `start` within + /// the chunk, into values in place. + /// + /// The loops are written to auto-vectorize; a target with AVX-512 gets native 64-bit + /// multiplies. + #[inline] + pub(crate) fn apply_chunk(&self, chunk_idx: usize, start: usize, chunk: &mut [T]) { + let scale = self.scales.get(chunk_idx); + let slope = self.slopes.get(chunk_idx); + match (scale == T::one(), slope == 0) { + (true, true) => self.apply::(chunk_idx, start, chunk), + (false, true) => self.apply::(chunk_idx, start, chunk), + (true, false) => self.apply::(chunk_idx, start, chunk), + (false, false) => self.apply::(chunk_idx, start, chunk), + } + } + + /// `SCALE` and `SLOPE` drop the multiply and the slope term for chunks whose scale is one or + /// whose slope is zero. + #[expect( + clippy::inline_always, + reason = "the per-mode loop must inline into its dispatch to vectorize per chunk" + )] + #[inline(always)] + fn apply( + &self, + chunk_idx: usize, + start: usize, + chunk: &mut [T], + ) { + let reference = self.references.get(chunk_idx); + let scale = self.scales.get(chunk_idx); + let (whole, frac) = split_slope(self.slopes.get(chunk_idx), self.shift); + let shift = self.shift; + // Running sums of `whole * j` and `frac * j`, equal to `slope_term_split` at every `j` by + // the same wrapping arithmetic, keep the loop free of 64-bit multiplies. + let mut whole_j = slope_term_split(whole, 0, start, 0); + let mut frac_j = frac.wrapping_mul(start as u32); + for value in chunk.iter_mut() { + let mut v = *value; + if SCALE { + v = v.wrapping_mul(&scale); + } + v = v.wrapping_add(&reference); + if SLOPE { + let term = whole_j.wrapping_add(i64::from(frac_j >> shift)); + v = v.wrapping_add(&term.as_()); + whole_j = whole_j.wrapping_add(whole); + frac_j = frac_j.wrapping_add(frac); + } + *value = v; + } + } + + /// Write the values of chunk `chunk_idx`, whose first value sits at position `start` within + /// the chunk, from residuals `src` of the narrower type `U` into `dst`. + #[inline] + pub(crate) fn apply_narrow( + &self, + chunk_idx: usize, + start: usize, + src: &[U], + dst: &mut [MaybeUninit], + ) where + T: AsPrimitive, + u64: AsPrimitive, + U: Copy + AsPrimitive, + { + let scale = self.scales.get(chunk_idx); + let flat = self.slopes.get(chunk_idx) == 0; + // Residuals of at most 32 bits times a scale below 2^32 multiply as 32 x 32 -> 64 bits, + // one instruction on every x86 target. + let narrow_mul = + size_of::() <= 4 && >::as_(scale) <= u64::from(u32::MAX); + match (scale == T::one(), flat, narrow_mul) { + (true, true, _) => self.narrow::(chunk_idx, start, src, dst), + (true, false, _) => self.narrow::(chunk_idx, start, src, dst), + (false, true, true) => self.narrow::(chunk_idx, start, src, dst), + (false, false, true) => self.narrow::(chunk_idx, start, src, dst), + (false, true, false) => { + self.narrow::(chunk_idx, start, src, dst) + } + (false, false, false) => { + self.narrow::(chunk_idx, start, src, dst) + } + } + } + + /// Decode selected residuals `src` at in-chunk positions `indices` of `chunk_idx` into `dst`. + #[inline] + pub(crate) fn apply_selected_narrow( + &self, + chunk_idx: usize, + indices: &[usize], + src: &[U], + dst: &mut [MaybeUninit], + ) where + T: AsPrimitive, + u64: AsPrimitive, + U: Copy + AsPrimitive, + { + let slope = self.slopes.get(chunk_idx); + if slope == 0 { + self.apply_narrow(chunk_idx, 0, src, dst); + return; + } + let reference = self.references.get(chunk_idx); + let scale = self.scales.get(chunk_idx); + let shift = self.shift; + let (whole, frac) = split_slope(slope, shift); + if scale == T::one() { + for ((out, &e), &j) in dst.iter_mut().zip(src).zip(indices) { + let term: T = slope_term_split(whole, frac, j, shift).as_(); + let e_t: T = >::as_(e.as_()); + out.write(e_t.wrapping_add(&reference).wrapping_add(&term)); + } + } else { + for ((out, &e), &j) in dst.iter_mut().zip(src).zip(indices) { + let term: T = slope_term_split(whole, frac, j, shift).as_(); + let e_t: T = >::as_(e.as_()); + out.write( + e_t.wrapping_mul(&scale) + .wrapping_add(&reference) + .wrapping_add(&term), + ); + } + } + } + + /// Gather and decode selected in-chunk positions `indices` from unpacked chunk `chunk_src`. + #[inline] + pub(crate) fn apply_gather_narrow( + &self, + chunk_idx: usize, + indices: &[usize], + chunk_src: &[U; FL_CHUNK_SIZE], + dst: &mut [MaybeUninit], + ) where + T: AsPrimitive, + u64: AsPrimitive, + U: Copy + AsPrimitive, + { + let reference = self.references.get(chunk_idx); + let scale = self.scales.get(chunk_idx); + let slope = self.slopes.get(chunk_idx); + let shift = self.shift; + if slope == 0 { + if scale == T::one() { + for (out, &j) in dst.iter_mut().zip(indices) { + let e_t: T = >::as_(chunk_src[j].as_()); + out.write(e_t.wrapping_add(&reference)); + } + } else { + for (out, &j) in dst.iter_mut().zip(indices) { + let e_t: T = >::as_(chunk_src[j].as_()); + out.write(e_t.wrapping_mul(&scale).wrapping_add(&reference)); + } + } + } else { + let (whole, frac) = split_slope(slope, shift); + if scale == T::one() { + for (out, &j) in dst.iter_mut().zip(indices) { + let term: T = slope_term_split(whole, frac, j, shift).as_(); + let e_t: T = >::as_(chunk_src[j].as_()); + out.write(e_t.wrapping_add(&reference).wrapping_add(&term)); + } + } else { + for (out, &j) in dst.iter_mut().zip(indices) { + let term: T = slope_term_split(whole, frac, j, shift).as_(); + let e_t: T = >::as_(chunk_src[j].as_()); + out.write( + e_t.wrapping_mul(&scale) + .wrapping_add(&reference) + .wrapping_add(&term), + ); + } + } + } + } + + #[expect( + clippy::inline_always, + reason = "the per-mode loop must inline into its dispatch to vectorize per chunk" + )] + #[inline(always)] + fn narrow( + &self, + chunk_idx: usize, + start: usize, + src: &[U], + dst: &mut [MaybeUninit], + ) where + T: AsPrimitive, + u64: AsPrimitive, + U: Copy + AsPrimitive, + { + let reference = self.references.get(chunk_idx); + let scale = self.scales.get(chunk_idx); + let scale32 = u64::from(>::as_(scale) as u32); + let (whole, frac) = split_slope(self.slopes.get(chunk_idx), self.shift); + let shift = self.shift; + let mut whole_j = slope_term_split(whole, 0, start, 0); + let mut frac_j = frac.wrapping_mul(start as u32); + for (out, &e) in dst.iter_mut().zip(src) { + let mut v: T = if SCALE && NARROW_MUL { + // Exact in u64 and truncated to `T`, which equals `T`'s wrapping multiply. + let e = u64::from(>::as_(e) as u32); + (e * scale32).as_() + } else if SCALE { + >::as_(e.as_()).wrapping_mul(&scale) + } else { + >::as_(e.as_()) + }; + v = v.wrapping_add(&reference); + if SLOPE { + let term = whole_j.wrapping_add(i64::from(frac_j >> shift)); + v = v.wrapping_add(&term.as_()); + whole_j = whole_j.wrapping_add(whole); + frac_j = frac_j.wrapping_add(frac); + } + out.write(v); + } + } + + pub(crate) fn decode(&self, chunk_idx: usize, j: usize, encoded: T) -> T { + decode_one( + encoded, + self.references.get(chunk_idx), + self.scales.get(chunk_idx), + self.slopes.get(chunk_idx), + j, + self.shift, + ) + } +} + +/// Decode the single element at chunk `chunk`, in-chunk position `j`, from its residual. +#[inline] +pub(crate) fn decode_one( + encoded: T, + reference: T, + scale: T, + slope: i64, + j: usize, + shift: u8, +) -> T +where + T: PrimInt + WrappingAdd + WrappingMul + 'static, + i64: AsPrimitive, +{ + encoded + .wrapping_mul(&scale) + .wrapping_add(&reference) + .wrapping_add(&slope_term(slope, j, shift).as_()) +} diff --git a/encodings/fastlanes/src/affine/array/mod.rs b/encodings/fastlanes/src/affine/array/mod.rs new file mode 100644 index 00000000000..5219c3ac027 --- /dev/null +++ b/encodings/fastlanes/src/affine/array/mod.rs @@ -0,0 +1,142 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::fmt::Display; +use std::fmt::Formatter; + +use vortex_array::ArrayRef; +use vortex_array::TypedArrayRef; +use vortex_array::array_slots; +use vortex_array::dtype::PType; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; + +use crate::FL_CHUNK_SIZE; + +pub mod affine_compress; +pub mod affine_decompress; + +#[array_slots(crate::Affine)] +pub struct AffineSlots { + /// The residuals left after removing each chunk's model, divided by the chunk's scale. + #[slot(0)] + pub encoded: ArrayRef, + /// One reference per [`FL_CHUNK_SIZE`]-element chunk, of the array's integer type. + #[slot(1)] + pub references: ArrayRef, + /// One scale per chunk, of the array's integer type. + #[slot(2)] + pub scales: ArrayRef, + /// One fixed-point slope per chunk, as `i64` in units of `2^-slope_shift`. + #[slot(3)] + pub slopes: ArrayRef, +} + +/// Affine-encoded array: a per-chunk linear model plus a scaled residual. +/// +/// Element `i` sits at position `p = offset + i`, in chunk `c = p / FL_CHUNK_SIZE` at position +/// `j = p % FL_CHUNK_SIZE`, and decodes as +/// +/// ```text +/// value = encoded[i] * scales[c] + references[c] + ((slopes[c] * j) >> slope_shift) +/// ``` +/// +/// All arithmetic wraps in the array's integer type, except the slope term, which is computed in +/// `i64` with wrapping multiplication and an arithmetic shift before truncating to the array's +/// type. Both encoder and decoder compute the same terms, so the encoding is lossless for any +/// parameters. +/// +/// The children select the mode. Constant `scales` of one and constant `slopes` of zero reduce to +/// per-chunk [`FoR`](crate::FoR). A scale above one divides out a common divisor, such as the step +/// of timestamps on a fixed grid. A slope removes a linear trend, such as row ids or regularly +/// sampled timestamps. +#[derive(Clone, Debug)] +pub struct AffineData { + pub(super) offset: u16, + pub(super) slope_shift: u8, +} + +pub trait AffineArrayExt: TypedArrayRef { + /// The position of the first element within the first chunk. + fn offset(&self) -> u16 { + self.offset + } + + /// The number of fractional bits in each slope. + fn slope_shift(&self) -> u8 { + self.slope_shift + } + + #[inline] + fn ptype(&self) -> PType { + self.dtype().as_ptype() + } +} + +impl> AffineArrayExt for T {} + +impl Display for AffineData { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!( + f, + "offset: {}, slope_shift: {}", + self.offset, self.slope_shift + ) + } +} + +/// The largest supported slope shift. It keeps a slope's fractional part below `2^16`, so the +/// fractional term `frac * j` of [`slope_term`] fits in a `u32` for every in-chunk position. +pub const MAX_SLOPE_SHIFT: u8 = 16; + +impl AffineData { + pub(crate) fn try_new(offset: u16, slope_shift: u8) -> VortexResult { + vortex_ensure!( + usize::from(offset) < FL_CHUNK_SIZE, + "Affine offset must be less than {FL_CHUNK_SIZE}, got {offset}" + ); + vortex_ensure!( + slope_shift <= MAX_SLOPE_SHIFT, + "Affine slope shift must be at most {MAX_SLOPE_SHIFT}, got {slope_shift}" + ); + Ok(Self { + offset, + slope_shift, + }) + } +} + +/// The number of chunks spanned by `len` elements starting at `offset` within the first chunk. +pub(crate) fn num_chunks(offset: u16, len: usize) -> usize { + (usize::from(offset) + len).div_ceil(FL_CHUNK_SIZE) +} + +/// The slope term that the model adds at position `j` of a chunk: `slope * j / 2^shift`, rounded +/// down. +/// +/// The slope splits into a whole part and a fractional part below `2^shift`, so the term is +/// `whole * j + ((frac * j) >> shift)`. The fractional product fits in a `u32` and both shifts and +/// products are uniform across a chunk, which lets the decode loop vectorize on targets without +/// 64-bit arithmetic shifts. Encoder and decoder both use this definition, so the encoding stays +/// exact for any slope. +#[inline] +pub(crate) fn slope_term(slope: i64, j: usize, shift: u8) -> i64 { + let (whole, frac) = split_slope(slope, shift); + slope_term_split(whole, frac, j, shift) +} + +/// The whole and fractional parts of a fixed-point slope. +#[inline] +pub(crate) fn split_slope(slope: i64, shift: u8) -> (i64, u32) { + let frac_mask = (1u64 << shift) - 1; + (slope >> shift, (slope as u64 & frac_mask) as u32) +} + +/// [`slope_term`] from a slope already split by [`split_slope`]. +#[inline] +pub(crate) fn slope_term_split(whole: i64, frac: u32, j: usize, shift: u8) -> i64 { + let j32 = j as u32; + whole + .wrapping_mul(j as i64) + .wrapping_add(i64::from(frac.wrapping_mul(j32) >> shift)) +} diff --git a/encodings/fastlanes/src/affine/compute/compare.rs b/encodings/fastlanes/src/affine/compute/compare.rs new file mode 100644 index 00000000000..260474d5d34 --- /dev/null +++ b/encodings/fastlanes/src/affine/compute/compare.rs @@ -0,0 +1,834 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Chunk-pruned constant comparison kernel for [`Affine`]. +//! +//! For each 1,024-element chunk, exact `i128` interval arithmetic verifies whether the affine +//! transform stays within `T`'s representable range `[T::MIN, T::MAX]` (no wraparound). When it +//! does: +//! - Chunks whose interval lies wholly on one side of `rhs`, or whose `scale` does not divide +//! `rhs - ref` for `Eq`/`NotEq`, short-circuit to a constant bool without unpacking. +//! - Flat (`slope == 0`) candidate chunks rewrite the comparison via exact integer division to a +//! direct residual threshold, using FastLanes' fused `BitPackingCompare::unchecked_unpack_cmp` +//! straight on packed bits. +//! - Sloped or wrapping candidate chunks decode into an L1 scratch buffer and pack the boolean +//! results directly into words. +//! +//! Any `BitPacked` patches overwrite their exact bits afterwards so every chunk benefits from +//! packed-range pruning even when patches are present. + +use std::mem::MaybeUninit; + +use fastlanes::BitPacking; +use fastlanes::BitPackingCompare; +use fastlanes::FastLanesComparable; +use fastlanes::transpose_bits; +use num_traits::AsPrimitive; +use num_traits::PrimInt; +use num_traits::WrappingAdd; +use num_traits::WrappingMul; +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::Primitive; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::PhysicalPType; +use vortex_array::match_each_integer_ptype; +use vortex_array::match_each_unsigned_integer_ptype; +use vortex_array::patches::Patches; +use vortex_array::scalar::Scalar; +use vortex_array::scalar_fn::builtin::binary::CompareKernel; +use vortex_array::scalar_fn::builtin::operators::CompareOperator; +use vortex_array::validity::Validity; +use vortex_buffer::BitBuffer; +use vortex_buffer::BitBufferMut; +use vortex_buffer::BufferMut; +use vortex_buffer::pack_bools_into_words; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; + +use super::resolve_aligned_bitpacked; +use crate::Affine; +use crate::BitPacked; +use crate::BitPackedArrayExt; +use crate::FL_CHUNK_SIZE; +use crate::affine::array::AffineArraySlotsExt; +use crate::affine::array::affine_decompress::Params; +use crate::affine::array::num_chunks; +use crate::affine::array::slope_term; +use crate::affine::array::split_slope; + +const U64_BITS: usize = u64::BITS as usize; +const WORDS_PER_CHUNK: usize = FL_CHUNK_SIZE / U64_BITS; + +/// Primitive comparison run directly on unpacked unsigned residuals. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum BaseCompare { + Eq, + Gt, +} + +/// Per-chunk strategy for comparing an `Affine` chunk against a constant `rhs`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ChunkComparePlan { + /// Every unpatched value in the chunk yields the same boolean answer. + Constant(bool), + /// Flat no-wrap chunk rewritten to `base(residual, threshold) ^ negate`. + FusedPacked { + base: BaseCompare, + threshold: u64, + negate: bool, + }, + /// Sloped or wrapping chunk that must decode into scratch and compare in `T`. + DecodeAndCompare, +} + +impl CompareKernel for Affine { + fn compare( + lhs: ArrayView<'_, Self>, + rhs: &ArrayRef, + operator: CompareOperator, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + let Some(constant) = rhs.as_constant() else { + return Ok(None); + }; + let Some(constant_prim) = constant.as_primitive_opt() else { + return Ok(None); + }; + let lhs_ptype = lhs.dtype().as_ptype(); + if constant_prim.ptype() != lhs_ptype { + return Ok(None); + } + + let nullability = lhs.dtype().nullability() | rhs.dtype().nullability(); + if lhs.is_empty() { + return Ok(Some( + Canonical::empty(&DType::Bool(nullability)).into_array(), + )); + } + if constant.is_null() { + return Ok(Some( + ConstantArray::new(Scalar::null(DType::Bool(nullability)), lhs.len()).into_array(), + )); + } + let validity = lhs.validity()?.union_nullability(nullability); + if matches!(validity, Validity::AllInvalid) { + return Ok(Some( + ConstantArray::new(Scalar::null(DType::Bool(nullability)), lhs.len()).into_array(), + )); + } + + match_each_integer_ptype!(lhs_ptype, |T| { + let rhs_val: T = constant_prim + .typed_value::() + .vortex_expect("non-null constant matches lhs ptype"); + compare_constant_typed::(lhs, rhs_val, operator, validity, ctx) + }) + } +} + +fn compare_constant_typed( + lhs: ArrayView<'_, Affine>, + rhs: T, + operator: CompareOperator, + validity: Validity, + ctx: &mut ExecutionCtx, +) -> VortexResult> +where + T: PhysicalPType< + Physical: BitPacking + + BitPackingCompare + + FastLanesComparable + + AsPrimitive, + > + NativePType + + PrimInt + + WrappingAdd + + WrappingMul + + AsPrimitive + + AsPrimitive, + i64: AsPrimitive, + u64: AsPrimitive, +{ + if let Some(bp_arr) = resolve_aligned_bitpacked(lhs, ctx)? { + let bp = bp_arr.as_::(); + let bit_width = bp.bit_width(); + let params = Params::::execute(lhs, ctx)?; + let encoded_ptype = bp.dtype().as_ptype(); + let result = match_each_unsigned_integer_ptype!(encoded_ptype.to_unsigned(), |U| { + compare_bitpacked_typed::( + lhs.len(), + bp, + bit_width, + ¶ms, + rhs, + operator, + validity, + ctx, + )? + }); + return Ok(Some(result)); + } + + if let Some(prim) = lhs.encoded().as_opt::() { + let params = Params::::execute(lhs, ctx)?; + let encoded_ptype = prim.ptype(); + let result = if encoded_ptype.byte_width() < T::PTYPE.byte_width() { + match_each_unsigned_integer_ptype!(encoded_ptype, |U| { + compare_primitive_narrow::( + prim.as_slice::(), + ¶ms, + rhs, + operator, + validity, + ctx, + ) + }) + } else { + compare_primitive_same_width::( + prim.as_slice::(), + ¶ms, + rhs, + operator, + validity, + ctx, + ) + }; + return Ok(Some(result)); + } + + Ok(None) +} + +#[expect( + clippy::too_many_arguments, + reason = "typed bitpacked compare execution parameters" +)] +fn compare_bitpacked_typed( + len: usize, + bp: ArrayView<'_, BitPacked>, + bit_width: u8, + params: &Params, + rhs: T, + operator: CompareOperator, + validity: Validity, + ctx: &mut ExecutionCtx, +) -> VortexResult +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul + AsPrimitive + AsPrimitive, + i64: AsPrimitive, + u64: AsPrimitive, + U: PhysicalPType + + BitPacking + + BitPackingCompare + + FastLanesComparable + + AsPrimitive, + u64: AsPrimitive, +{ + let offset = params.offset; + let total_chunks = num_chunks(offset as u16, len); + let max_packed: i128 = if bit_width == 64 { + i128::from(u64::MAX) + } else { + (1i128 << bit_width) - 1 + }; + + // Without patches, check if every chunk short-circuits to the same constant boolean. + if bp.patches().is_none() + && let Some(constant_answer) = + all_chunks_constant(len, offset, total_chunks, params, max_packed, rhs, operator) + { + return Ok(make_constant_bool( + constant_answer, + len, + validity, + ctx.allocator().clone(), + )); + } + + let bit_width = usize::from(bit_width); + let packed = bp.packed_slice::(); + let packed_chunk_len = FL_CHUNK_SIZE * bit_width / (8 * size_of::()); + + let mut words: BufferMut = + BufferMut::zeroed_in(total_chunks * WORDS_PER_CHUNK, ctx.allocator().clone()); + { + let words_slice = words.as_mut_slice(); + let mut lane_major = [0u64; WORDS_PER_CHUNK]; + let mut scratch_u = [U::default(); FL_CHUNK_SIZE]; + let mut scratch_t = [const { MaybeUninit::::uninit() }; FL_CHUNK_SIZE]; + + for chunk_idx in 0..total_chunks { + let j_lo = if chunk_idx == 0 { offset } else { 0 }; + let j_hi = (offset + len - chunk_idx * FL_CHUNK_SIZE).min(FL_CHUNK_SIZE); + let plan = + classify_chunk::(params, chunk_idx, max_packed, j_lo, j_hi - 1, rhs, operator); + let out = words_slice[chunk_idx * WORDS_PER_CHUNK..] + .first_chunk_mut::() + .vortex_expect("over-allocated buffer holds a full block per chunk"); + + match plan { + ChunkComparePlan::Constant(false) => {} + ChunkComparePlan::Constant(true) => out.fill(u64::MAX), + ChunkComparePlan::FusedPacked { + base, + threshold, + negate, + } if bit_width > 0 => { + let packed_chunk = &packed[chunk_idx * packed_chunk_len..][..packed_chunk_len]; + let threshold_u: U = threshold.as_(); + match base { + BaseCompare::Eq => { + // SAFETY: `packed_chunk` holds one chunk at `bit_width` bits. + unsafe { + U::unchecked_unpack_cmp::( + bit_width, + packed_chunk, + &mut lane_major, + U::is_eq, + threshold_u, + ); + } + } + BaseCompare::Gt => { + // SAFETY: `packed_chunk` holds one chunk at `bit_width` bits. + unsafe { + U::unchecked_unpack_cmp::( + bit_width, + packed_chunk, + &mut lane_major, + U::is_gt, + threshold_u, + ); + } + } + } + transpose_bits::(&lane_major, out); + if negate { + out.iter_mut().for_each(|word| *word = !*word); + } + } + ChunkComparePlan::FusedPacked { .. } | ChunkComparePlan::DecodeAndCompare => { + if bit_width == 0 { + scratch_u[j_lo..j_hi].fill(U::zero()); + } else { + let packed_chunk = + &packed[chunk_idx * packed_chunk_len..][..packed_chunk_len]; + // SAFETY: `packed_chunk` holds one chunk at `bit_width` bits. + unsafe { + BitPacking::unchecked_unpack(bit_width, packed_chunk, &mut scratch_u); + } + } + let count = j_hi - j_lo; + params.apply_narrow( + chunk_idx, + j_lo, + &scratch_u[j_lo..j_hi], + &mut scratch_t[..count], + ); + // SAFETY: `apply_narrow` initialized `scratch_t[..count]`. + let decoded = unsafe { scratch_t[..count].assume_init_ref() }; + pack_bools_into_words( + words_slice, + chunk_idx * FL_CHUNK_SIZE + j_lo, + count, + |i| eval_compare(decoded[i], rhs, operator), + ); + } + } + } + } + + let mut bits = BitBufferMut::from_buffer(words.into_byte_buffer(), offset, len); + + if let Some(patches) = bp.patches() { + apply_compare_patches::(&mut bits, &patches, params, rhs, operator, ctx)?; + } + + Ok(BoolArray::new(bits.freeze(), validity).into_array()) +} + +fn compare_primitive_narrow( + src: &[U], + params: &Params, + rhs: T, + operator: CompareOperator, + validity: Validity, + ctx: &mut ExecutionCtx, +) -> ArrayRef +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul + AsPrimitive + AsPrimitive, + i64: AsPrimitive, + u64: AsPrimitive, + U: NativePType + PrimInt + AsPrimitive, + u64: AsPrimitive, +{ + let len = src.len(); + let offset = params.offset; + let total_chunks = num_chunks(offset as u16, len); + let max_e = i128::from(>::as_(U::max_value())); + + if let Some(constant_answer) = + all_chunks_constant(len, offset, total_chunks, params, max_e, rhs, operator) + { + return make_constant_bool(constant_answer, len, validity, ctx.allocator().clone()); + } + + let mut words: BufferMut = + BufferMut::zeroed_in(total_chunks * WORDS_PER_CHUNK, ctx.allocator().clone()); + { + let words_slice = words.as_mut_slice(); + let mut scratch_t = [const { MaybeUninit::::uninit() }; FL_CHUNK_SIZE]; + let mut src_pos = 0usize; + + for chunk_idx in 0..total_chunks { + let j_lo = if chunk_idx == 0 { offset } else { 0 }; + let j_hi = (offset + len - chunk_idx * FL_CHUNK_SIZE).min(FL_CHUNK_SIZE); + let count = j_hi - j_lo; + let chunk_src = &src[src_pos..src_pos + count]; + src_pos += count; + + let plan = classify_chunk::(params, chunk_idx, max_e, j_lo, j_hi - 1, rhs, operator); + match plan { + ChunkComparePlan::Constant(false) => {} + ChunkComparePlan::Constant(true) => { + words_slice[chunk_idx * WORDS_PER_CHUNK..][..WORDS_PER_CHUNK].fill(u64::MAX); + } + ChunkComparePlan::FusedPacked { + base, + threshold, + negate, + } => { + let threshold_u: U = threshold.as_(); + let bit_start = chunk_idx * FL_CHUNK_SIZE + j_lo; + match (base, negate) { + (BaseCompare::Eq, false) => { + pack_bools_into_words(words_slice, bit_start, count, |i| { + chunk_src[i] == threshold_u + }); + } + (BaseCompare::Eq, true) => { + pack_bools_into_words(words_slice, bit_start, count, |i| { + chunk_src[i] != threshold_u + }); + } + (BaseCompare::Gt, false) => { + pack_bools_into_words(words_slice, bit_start, count, |i| { + chunk_src[i] > threshold_u + }); + } + (BaseCompare::Gt, true) => { + pack_bools_into_words(words_slice, bit_start, count, |i| { + chunk_src[i] <= threshold_u + }); + } + } + } + ChunkComparePlan::DecodeAndCompare => { + params.apply_narrow(chunk_idx, j_lo, chunk_src, &mut scratch_t[..count]); + // SAFETY: `apply_narrow` initialized `scratch_t[..count]`. + let decoded = unsafe { scratch_t[..count].assume_init_ref() }; + pack_bools_into_words( + words_slice, + chunk_idx * FL_CHUNK_SIZE + j_lo, + count, + |i| eval_compare(decoded[i], rhs, operator), + ); + } + } + } + } + + let bits = BitBufferMut::from_buffer(words.into_byte_buffer(), offset, len); + BoolArray::new(bits.freeze(), validity).into_array() +} + +fn compare_primitive_same_width( + src: &[T], + params: &Params, + rhs: T, + operator: CompareOperator, + validity: Validity, + ctx: &mut ExecutionCtx, +) -> ArrayRef +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul + AsPrimitive, + i64: AsPrimitive, +{ + let len = src.len(); + let offset = params.offset; + let total_chunks = num_chunks(offset as u16, len); + let unsigned_max_e = T::PTYPE.is_unsigned_int().then(|| T::max_value().as_()); + + let mut words: BufferMut = + BufferMut::zeroed_in(total_chunks * WORDS_PER_CHUNK, ctx.allocator().clone()); + { + let words_slice = words.as_mut_slice(); + let mut scratch_t = [T::zero(); FL_CHUNK_SIZE]; + let mut src_pos = 0usize; + + for chunk_idx in 0..total_chunks { + let j_lo = if chunk_idx == 0 { offset } else { 0 }; + let j_hi = (offset + len - chunk_idx * FL_CHUNK_SIZE).min(FL_CHUNK_SIZE); + let count = j_hi - j_lo; + let chunk_src = &src[src_pos..src_pos + count]; + src_pos += count; + + let plan = if let Some(max_e) = unsigned_max_e { + classify_chunk::(params, chunk_idx, max_e, j_lo, j_hi - 1, rhs, operator) + } else if params.scales.get(chunk_idx) == T::zero() && params.slopes.get(chunk_idx) == 0 + { + ChunkComparePlan::Constant(eval_compare( + params.references.get(chunk_idx), + rhs, + operator, + )) + } else { + ChunkComparePlan::DecodeAndCompare + }; + + match plan { + ChunkComparePlan::Constant(false) => {} + ChunkComparePlan::Constant(true) => { + words_slice[chunk_idx * WORDS_PER_CHUNK..][..WORDS_PER_CHUNK].fill(u64::MAX); + } + ChunkComparePlan::FusedPacked { .. } | ChunkComparePlan::DecodeAndCompare => { + scratch_t[..count].copy_from_slice(chunk_src); + params.apply_chunk(chunk_idx, j_lo, &mut scratch_t[..count]); + pack_bools_into_words( + words_slice, + chunk_idx * FL_CHUNK_SIZE + j_lo, + count, + |i| eval_compare(scratch_t[i], rhs, operator), + ); + } + } + } + } + + let bits = BitBufferMut::from_buffer(words.into_byte_buffer(), offset, len); + BoolArray::new(bits.freeze(), validity).into_array() +} + +fn apply_compare_patches( + bits: &mut BitBufferMut, + patches: &Patches, + params: &Params, + rhs: T, + operator: CompareOperator, + ctx: &mut ExecutionCtx, +) -> VortexResult<()> +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, +{ + let patch_indices = patches.indices().clone().execute::(ctx)?; + let patch_values = patches.values().clone().execute::(ctx)?; + let patch_offset = patches.offset(); + + match_each_unsigned_integer_ptype!(patch_indices.ptype(), |P| { + apply_compare_patches_indices::( + bits, + patch_indices.as_slice::

(), + patch_offset, + &patch_values, + params, + rhs, + operator, + ) + }); + Ok(()) +} + +fn apply_compare_patches_indices( + bits: &mut BitBufferMut, + patch_indices: &[P], + patch_offset: usize, + patch_values: &PrimitiveArray, + params: &Params, + rhs: T, + operator: CompareOperator, +) where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, + P: Copy + AsPrimitive, +{ + match_each_integer_ptype!(patch_values.ptype(), |V| { + apply_compare_patches_typed::( + bits, + patch_indices, + patch_offset, + patch_values.as_slice::(), + params, + rhs, + operator, + ) + }); +} + +fn apply_compare_patches_typed( + bits: &mut BitBufferMut, + patch_indices: &[P], + patch_offset: usize, + patch_values: &[V], + params: &Params, + rhs: T, + operator: CompareOperator, +) where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, + P: Copy + AsPrimitive, + V: NativePType + AsPrimitive, +{ + for (&p_idx, &p_val) in patch_indices.iter().zip(patch_values) { + let local_idx = p_idx.as_() - patch_offset; + let pos = params.offset + local_idx; + let residual: T = >::as_(p_val.as_()); + let val = params.decode(pos / FL_CHUNK_SIZE, pos % FL_CHUNK_SIZE, residual); + bits.set_to(local_idx, eval_compare(val, rhs, operator)); + } +} + +fn all_chunks_constant( + len: usize, + offset: usize, + total_chunks: usize, + params: &Params, + max_e: i128, + rhs: T, + operator: CompareOperator, +) -> Option +where + T: NativePType + PrimInt + AsPrimitive, +{ + let mut answer: Option = None; + for chunk_idx in 0..total_chunks { + let j_lo = if chunk_idx == 0 { offset } else { 0 }; + let j_hi = (offset + len - chunk_idx * FL_CHUNK_SIZE).min(FL_CHUNK_SIZE); + match classify_chunk::(params, chunk_idx, max_e, j_lo, j_hi - 1, rhs, operator) { + ChunkComparePlan::Constant(b) => match answer { + None => answer = Some(b), + Some(prev) if prev == b => {} + Some(_) => return None, + }, + ChunkComparePlan::FusedPacked { .. } | ChunkComparePlan::DecodeAndCompare => { + return None; + } + } + } + answer +} + +fn make_constant_bool( + value: bool, + len: usize, + validity: Validity, + allocator: vortex_buffer::BufferAllocatorRef, +) -> ArrayRef { + if validity.definitely_no_nulls() { + let scalar = Scalar::bool(value, validity.nullability()); + ConstantArray::new(scalar, len).into_array() + } else { + BoolArray::new(BitBuffer::full_in(value, len, allocator), validity).into_array() + } +} + +#[inline] +fn eval_compare(lhs: T, rhs: T, operator: CompareOperator) -> bool { + match operator { + CompareOperator::Eq => lhs.is_eq(rhs), + CompareOperator::NotEq => !lhs.is_eq(rhs), + CompareOperator::Lt => lhs.is_lt(rhs), + CompareOperator::Lte => lhs.is_le(rhs), + CompareOperator::Gt => lhs.is_gt(rhs), + CompareOperator::Gte => lhs.is_ge(rhs), + } +} + +/// Classifies chunk `chunk_idx` assuming unpatched residuals lie in `0..=max_e` and active +/// in-chunk positions lie in `j_lo..=j_hi`. +/// +/// Exact `i128` interval arithmetic verifies that every `(e, j)` pair produces a value inside +/// `[T::MIN, T::MAX]`, guaranteeing modular wrapping in `T` agrees with mathematical integers. +fn classify_chunk( + params: &Params, + chunk_idx: usize, + max_e: i128, + j_lo: usize, + j_hi: usize, + rhs: T, + operator: CompareOperator, +) -> ChunkComparePlan +where + T: NativePType + PrimInt + AsPrimitive, +{ + let t_min: i128 = T::min_value().as_(); + let t_max: i128 = T::max_value().as_(); + let r: i128 = params.references.get(chunk_idx).as_(); + let s: i128 = params.scales.get(chunk_idx).as_(); + let slope = params.slopes.get(chunk_idx); + let rhs_i: i128 = rhs.as_(); + + let Some(end_val) = s.checked_mul(max_e).and_then(|prod| r.checked_add(prod)) else { + return ChunkComparePlan::DecodeAndCompare; + }; + let (base_lo, base_hi) = if r <= end_val { + (r, end_val) + } else { + (end_val, r) + }; + + if slope != 0 { + return classify_sloped_chunk( + base_lo, + base_hi, + slope, + params.shift, + j_lo, + j_hi, + t_min, + t_max, + rhs_i, + operator, + ); + } + + classify_flat_chunk(r, s, base_lo, base_hi, t_min, t_max, rhs_i, operator) +} + +#[expect( + clippy::too_many_arguments, + reason = "interval bounds classification helper" +)] +fn classify_sloped_chunk( + base_lo: i128, + base_hi: i128, + slope: i64, + shift: u8, + j_lo: usize, + j_hi: usize, + t_min: i128, + t_max: i128, + rhs_i: i128, + operator: CompareOperator, +) -> ChunkComparePlan { + let (whole, _frac) = split_slope(slope, shift); + // Ensure `whole * j + ((frac * j) >> shift)` never wraps in `i64` for `j < FL_CHUNK_SIZE`. + if i128::from(whole).abs() * (FL_CHUNK_SIZE as i128) + (FL_CHUNK_SIZE as i128) + >= i128::from(i64::MAX) + { + return ChunkComparePlan::DecodeAndCompare; + } + let t0 = i128::from(slope_term(slope, j_lo, shift)); + let t1 = i128::from(slope_term(slope, j_hi, shift)); + let (t_lo, t_hi) = if t0 <= t1 { (t0, t1) } else { (t1, t0) }; + let (Some(lo), Some(hi)) = (base_lo.checked_add(t_lo), base_hi.checked_add(t_hi)) else { + return ChunkComparePlan::DecodeAndCompare; + }; + if lo < t_min || hi > t_max { + return ChunkComparePlan::DecodeAndCompare; + } + classify_interval_only(lo, hi, rhs_i, operator).map_or( + ChunkComparePlan::DecodeAndCompare, + ChunkComparePlan::Constant, + ) +} + +#[expect( + clippy::too_many_arguments, + reason = "flat interval classification helper" +)] +fn classify_flat_chunk( + r: i128, + s: i128, + lo: i128, + hi: i128, + t_min: i128, + t_max: i128, + rhs_i: i128, + operator: CompareOperator, +) -> ChunkComparePlan { + if lo < t_min || hi > t_max { + return ChunkComparePlan::DecodeAndCompare; + } + if let Some(constant) = classify_interval_only(lo, hi, rhs_i, operator) { + return ChunkComparePlan::Constant(constant); + } + + // `lo < hi`, so `s != 0` and `rhs_i` falls inside `[lo, hi]`. + match operator { + CompareOperator::Eq | CompareOperator::NotEq => { + let negate = matches!(operator, CompareOperator::NotEq); + let diff = rhs_i - r; + if diff % s != 0 { + return ChunkComparePlan::Constant(negate); + } + ChunkComparePlan::FusedPacked { + base: BaseCompare::Eq, + threshold: (diff / s) as u64, + negate, + } + } + CompareOperator::Lt | CompareOperator::Gte => { + let is_lt = matches!(operator, CompareOperator::Lt); + let (threshold, negate) = if s > 0 { + (((rhs_i - r - 1) / s) as u64, is_lt) + } else { + (((r - rhs_i) / (-s)) as u64, !is_lt) + }; + ChunkComparePlan::FusedPacked { + base: BaseCompare::Gt, + threshold, + negate, + } + } + CompareOperator::Lte | CompareOperator::Gt => { + let is_lte = matches!(operator, CompareOperator::Lte); + let (threshold, negate) = if s > 0 { + (((rhs_i - r) / s) as u64, is_lte) + } else { + (((r - rhs_i - 1) / (-s)) as u64, !is_lte) + }; + ChunkComparePlan::FusedPacked { + base: BaseCompare::Gt, + threshold, + negate, + } + } + } +} + +/// Returns `Some(answer)` if the closed value interval `[lo, hi]` decides `val rhs_i` for +/// every element in the chunk. +#[inline] +fn classify_interval_only( + lo: i128, + hi: i128, + rhs_i: i128, + operator: CompareOperator, +) -> Option { + match operator { + CompareOperator::Eq if rhs_i < lo || rhs_i > hi => Some(false), + CompareOperator::Eq if lo == hi => Some(true), + CompareOperator::NotEq if rhs_i < lo || rhs_i > hi => Some(true), + CompareOperator::NotEq if lo == hi => Some(false), + CompareOperator::Lt if hi < rhs_i => Some(true), + CompareOperator::Lt if lo >= rhs_i => Some(false), + CompareOperator::Lte if hi <= rhs_i => Some(true), + CompareOperator::Lte if lo > rhs_i => Some(false), + CompareOperator::Gt if lo > rhs_i => Some(true), + CompareOperator::Gt if hi <= rhs_i => Some(false), + CompareOperator::Gte if lo >= rhs_i => Some(true), + CompareOperator::Gte if hi < rhs_i => Some(false), + _ => None, + } +} diff --git a/encodings/fastlanes/src/affine/compute/filter.rs b/encodings/fastlanes/src/affine/compute/filter.rs new file mode 100644 index 00000000000..0142d274509 --- /dev/null +++ b/encodings/fastlanes/src/affine/compute/filter.rs @@ -0,0 +1,590 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Chunk-pruned `filter` kernel for [`Affine`]. + +use fastlanes::BitPacking; +use fastlanes::FoR; +use num_traits::AsPrimitive; +use num_traits::PrimInt; +use num_traits::WrappingAdd; +use num_traits::WrappingMul; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::Canonical; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::Primitive; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::filter::FilterKernel; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::PhysicalPType; +use vortex_array::match_each_integer_ptype; +use vortex_array::match_each_unsigned_integer_ptype; +use vortex_array::patches::Patches; +use vortex_buffer::Buffer; +use vortex_buffer::BufferAllocatorRef; +use vortex_buffer::BufferMut; +use vortex_buffer::filter::filter_chunked; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_mask::Mask; +use vortex_mask::MaskValues; + +use super::AffineNarrowBitPackedChunks; +use super::AffineSameWidthBitPackedChunks; +use super::resolve_aligned_bitpacked; +use crate::Affine; +use crate::BitPacked; +use crate::BitPackedArrayExt; +use crate::FL_CHUNK_SIZE; +use crate::affine::array::AffineArrayExt; +use crate::affine::array::AffineArraySlotsExt; +use crate::affine::array::affine_decompress::Params; +use crate::affine::array::slope_term_split; +use crate::affine::array::split_slope; + +impl FilterKernel for Affine { + fn filter( + array: ArrayView<'_, Self>, + mask: &Mask, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + let mask_values = match mask { + Mask::AllTrue(_) => return Ok(Some(array.array().clone())), + Mask::AllFalse(_) => return Ok(Some(Canonical::empty(array.dtype()).into_array())), + Mask::Values(values) => values, + }; + + if let Some(bp_arr) = resolve_aligned_bitpacked(array, ctx)? { + let bp = bp_arr.as_::(); + let bit_width = bp.bit_width(); + return match_each_integer_ptype!(array.ptype(), |T| { + filter_bitpacked_typed::(array, bp, bit_width, mask, mask_values, ctx).map(Some) + }); + } + + let filtered_encoded = array + .encoded() + .filter(mask.clone())? + .execute::(ctx)?; + match_each_integer_ptype!(array.ptype(), |T| { + filter_residuals_typed::(array, filtered_encoded, mask_values, ctx).map(Some) + }) + } +} + +fn filter_bitpacked_typed( + array: ArrayView<'_, Affine>, + bp: ArrayView<'_, BitPacked>, + bit_width: u8, + mask: &Mask, + mask_values: &MaskValues, + ctx: &mut ExecutionCtx, +) -> VortexResult +where + T: PhysicalPType> + + AsPrimitive + + AsPrimitive + + PrimInt + + WrappingAdd + + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, +{ + let params = Params::::execute(array, ctx)?; + let validity = array.validity()?.filter(mask)?; + let encoded_ptype = bp.dtype().as_ptype(); + let bit_width = usize::from(bit_width); + + let values = if encoded_ptype.byte_width() < T::PTYPE.byte_width() { + match_each_unsigned_integer_ptype!(encoded_ptype, |U| { + filter_bitpacked_narrow::(bp, bit_width, ¶ms, mask_values, ctx.allocator()) + }) + } else { + let chunks = AffineSameWidthBitPackedChunks::::new( + bp.packed_slice::(), + bit_width, + ¶ms, + ); + filter_chunked( + &chunks, + params.offset, + mask_values.selection(), + ctx.allocator(), + ) + }; + + let values = match bp.patches() { + Some(patches) => { + let mut values_mut = values.into_mut(); + apply_filtered_patches::(&mut values_mut, &patches, ¶ms, mask_values, ctx)?; + values_mut.freeze() + } + None => values, + }; + + Ok(PrimitiveArray::new(values, validity).into_array()) +} + +fn filter_bitpacked_narrow( + bp: ArrayView<'_, BitPacked>, + bit_width: usize, + params: &Params, + mask_values: &MaskValues, + allocator: &BufferAllocatorRef, +) -> Buffer +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul + AsPrimitive, + i64: AsPrimitive, + u64: AsPrimitive, + U: PhysicalPType + BitPacking + AsPrimitive, +{ + let chunks = + AffineNarrowBitPackedChunks::::new(bp.packed_slice::(), bit_width, params); + filter_chunked(&chunks, params.offset, mask_values.selection(), allocator) +} + +/// Apply surviving [`BitPacked`] patches to `values` after `filter_chunked`, decoding each +/// surviving patch residual with the model of its original `(chunk, j)` position. +fn apply_filtered_patches( + values: &mut [T], + patches: &Patches, + params: &Params, + mask_values: &MaskValues, + ctx: &mut ExecutionCtx, +) -> VortexResult<()> +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, +{ + let patch_indices = patches.indices().clone().execute::(ctx)?; + let patch_offset = patches.offset(); + + // Fast paths when patch values need no decompression: write straight into `values`. + if let Some(constant) = patches.values().as_constant() { + if constant.is_null() { + return Ok(()); + } + let patch_val = scalar_residual_as_t::(constant); + match_each_unsigned_integer_ptype!(patch_indices.ptype(), |P| { + visit_surviving_patches( + patch_indices.as_slice::

(), + patch_offset, + mask_values, + |out_idx, orig_idx, _patch_slot| { + let pos = params.offset + orig_idx; + values[out_idx] = + params.decode(pos / FL_CHUNK_SIZE, pos % FL_CHUNK_SIZE, patch_val); + }, + ); + }); + return Ok(()); + } + + if let Some(prim_vals) = patches.values().as_opt::() { + return match_each_unsigned_integer_ptype!(patch_indices.ptype(), |P| { + apply_primitive_patch_values::( + values, + patch_indices.as_slice::

(), + patch_offset, + prim_vals, + params, + mask_values, + ); + Ok(()) + }); + } + + // Compressed patch values: find surviving slots first so sparse filters avoid decoding all + // patches. + let mut hits: Vec<(usize, usize, u64)> = Vec::new(); + match_each_unsigned_integer_ptype!(patch_indices.ptype(), |P| { + visit_surviving_patches( + patch_indices.as_slice::

(), + patch_offset, + mask_values, + |out_idx, orig_idx, patch_slot| { + hits.push((out_idx, orig_idx, patch_slot as u64)); + }, + ); + }); + if hits.is_empty() { + return Ok(()); + } + + if hits.len().saturating_mul(8) < patches.num_patches() { + let slot_indices: Buffer = hits.iter().map(|&(_, _, slot)| slot).collect(); + let taken_vals = patches + .values() + .take(PrimitiveArray::from_iter(slot_indices).into_array())? + .execute::(ctx)?; + match_each_integer_ptype!(taken_vals.ptype(), |V| { + apply_taken_patch_hits::(values, &hits, taken_vals.as_slice::(), params); + }); + } else { + let all_vals = patches.values().clone().execute::(ctx)?; + match_each_integer_ptype!(all_vals.ptype(), |V| { + apply_all_patch_hits::(values, &hits, all_vals.as_slice::(), params); + }); + } + Ok(()) +} + +fn scalar_residual_as_t(scalar: &vortex_array::scalar::Scalar) -> T +where + T: NativePType, + u64: AsPrimitive, +{ + let prim = scalar.as_primitive(); + if prim.ptype() == T::PTYPE { + prim.typed_value::() + .vortex_expect("patch values are non-null") + } else { + >::as_(prim.as_::().vortex_expect("patch values are non-null")) + } +} + +fn apply_primitive_patch_values( + values: &mut [T], + patch_indices: &[P], + patch_offset: usize, + prim_vals: ArrayView<'_, Primitive>, + params: &Params, + mask_values: &MaskValues, +) where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, + P: Copy + AsPrimitive, +{ + match_each_integer_ptype!(prim_vals.ptype(), |V| { + apply_primitive_patch_values_typed::( + values, + patch_indices, + patch_offset, + prim_vals.as_slice::(), + params, + mask_values, + ) + }); +} + +fn apply_primitive_patch_values_typed( + values: &mut [T], + patch_indices: &[P], + patch_offset: usize, + patch_values: &[V], + params: &Params, + mask_values: &MaskValues, +) where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, + P: Copy + AsPrimitive, + V: NativePType + AsPrimitive, +{ + visit_surviving_patches( + patch_indices, + patch_offset, + mask_values, + |out_idx, orig_idx, patch_slot| { + let pos = params.offset + orig_idx; + let residual: T = >::as_(patch_values[patch_slot].as_()); + values[out_idx] = params.decode(pos / FL_CHUNK_SIZE, pos % FL_CHUNK_SIZE, residual); + }, + ); +} + +fn apply_taken_patch_hits( + values: &mut [T], + hits: &[(usize, usize, u64)], + taken_values: &[V], + params: &Params, +) where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, + V: NativePType + AsPrimitive, +{ + for (&(out_idx, orig_idx, _), &val) in hits.iter().zip(taken_values) { + let pos = params.offset + orig_idx; + let residual: T = >::as_(val.as_()); + values[out_idx] = params.decode(pos / FL_CHUNK_SIZE, pos % FL_CHUNK_SIZE, residual); + } +} + +fn apply_all_patch_hits( + values: &mut [T], + hits: &[(usize, usize, u64)], + all_values: &[V], + params: &Params, +) where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, + V: NativePType + AsPrimitive, +{ + for &(out_idx, orig_idx, slot) in hits { + let pos = params.offset + orig_idx; + let residual: T = >::as_(all_values[slot as usize].as_()); + values[out_idx] = params.decode(pos / FL_CHUNK_SIZE, pos % FL_CHUNK_SIZE, residual); + } +} + +/// Calls `on_hit(out_idx, orig_idx, patch_slot)` for every patch whose array-local index is set +/// in `mask_values`. +fn visit_surviving_patches>( + patch_indices: &[P], + patch_offset: usize, + mask_values: &MaskValues, + mut on_hit: impl FnMut(usize, usize, usize), +) { + let patch_count = patch_indices.len(); + let true_count = mask_values.true_count(); + + if patch_count > true_count.saturating_mul(16) + || (mask_values.cached_indices().is_some() && true_count <= patch_count) + { + let mut cursor = 0usize; + for (out_idx, &orig_idx) in mask_values.indices().iter().enumerate() { + if cursor >= patch_count { + break; + } + let target = orig_idx + patch_offset; + let mut step = 1usize; + while cursor + step < patch_count && patch_indices[cursor + step].as_() < target { + cursor += step; + step <<= 1; + } + let hi = (cursor + step + 1).min(patch_count); + cursor += patch_indices[cursor..hi].partition_point(|&pi| pi.as_() < target); + if cursor < patch_count && patch_indices[cursor].as_() == target { + on_hit(out_idx, orig_idx, cursor); + cursor += 1; + } + } + } else { + let bits = mask_values.bit_buffer(); + let mut prev_idx = 0usize; + let mut out_idx = 0usize; + for (patch_slot, &pi) in patch_indices.iter().enumerate() { + let orig_idx = pi.as_() - patch_offset; + if bits.value(orig_idx) { + out_idx += bits.count_range(prev_idx, orig_idx); + prev_idx = orig_idx; + on_hit(out_idx, orig_idx, patch_slot); + } + } + } +} + +/// Apply the affine model to already-filtered residuals from a non-BitPacked child. +fn filter_residuals_typed( + array: ArrayView<'_, Affine>, + filtered_encoded: PrimitiveArray, + mask_values: &MaskValues, + ctx: &mut ExecutionCtx, +) -> VortexResult +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul + AsPrimitive, + i64: AsPrimitive, + u64: AsPrimitive, +{ + let params = Params::::execute(array, ctx)?; + let validity = filtered_encoded.validity()?; + let encoded_ptype = filtered_encoded.ptype(); + + let values = if encoded_ptype == T::PTYPE { + let mut values = filtered_encoded.into_buffer::().into_mut(); + apply_filtered_in_place(&mut values, ¶ms, mask_values); + values.freeze() + } else { + match_each_unsigned_integer_ptype!(encoded_ptype, |U| { + apply_filtered_narrow::( + filtered_encoded.as_slice::(), + ¶ms, + mask_values, + ctx.allocator(), + ) + }) + }; + + Ok(PrimitiveArray::new(values, validity).into_array()) +} + +fn apply_filtered_in_place(values: &mut [T], params: &Params, mask_values: &MaskValues) +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, +{ + if params.all_constant_flat() { + params.apply_chunk(0, 0, values); + return; + } + + if params.slopes_are_zero() { + apply_filtered_flat_chunks(mask_values, params.offset, |chunk_idx, out_start, count| { + params.apply_chunk(chunk_idx, 0, &mut values[out_start..out_start + count]); + }); + return; + } + + let offset = params.offset; + let shift = params.shift; + visit_mask_chunks( + mask_values, + offset, + |chunk_idx, out_start, chunk_positions| { + let reference = params.references.get(chunk_idx); + let scale = params.scales.get(chunk_idx); + let slope = params.slopes.get(chunk_idx); + if slope == 0 { + let count = chunk_positions.len(); + params.apply_chunk(chunk_idx, 0, &mut values[out_start..out_start + count]); + } else { + let (whole, frac) = split_slope(slope, shift); + for (val, &j) in values[out_start..].iter_mut().zip(chunk_positions) { + let term: T = slope_term_split(whole, frac, j, shift).as_(); + *val = val + .wrapping_mul(&scale) + .wrapping_add(&reference) + .wrapping_add(&term); + } + } + }, + ); +} + +fn apply_filtered_narrow( + src: &[U], + params: &Params, + mask_values: &MaskValues, + allocator: &BufferAllocatorRef, +) -> Buffer +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul + AsPrimitive, + i64: AsPrimitive, + u64: AsPrimitive, + U: Copy + AsPrimitive, +{ + let len = src.len(); + let mut out = BufferMut::::with_capacity_in(len, allocator.clone()); + let dst = &mut out.spare_capacity_mut()[..len]; + + if params.all_constant_flat() { + params.apply_narrow(0, 0, src, dst); + } else if params.slopes_are_zero() { + apply_filtered_flat_chunks(mask_values, params.offset, |chunk_idx, out_start, count| { + params.apply_narrow( + chunk_idx, + 0, + &src[out_start..out_start + count], + &mut dst[out_start..out_start + count], + ); + }); + } else { + visit_mask_chunks( + mask_values, + params.offset, + |chunk_idx, out_start, positions| { + let count = positions.len(); + params.apply_selected_narrow( + chunk_idx, + positions, + &src[out_start..out_start + count], + &mut dst[out_start..out_start + count], + ); + }, + ); + } + + // SAFETY: every element in `0..len` was initialized above. + unsafe { out.set_len(len) }; + out.freeze() +} + +/// Calls `on_chunk(chunk_idx, out_start, count)` for each chunk containing at least one selected +/// row, using fast word-level popcount when the mask is a bitmap. +fn apply_filtered_flat_chunks( + mask_values: &MaskValues, + offset: usize, + mut on_chunk: impl FnMut(usize, usize, usize), +) { + if let Some(indices) = mask_values.cached_indices() { + let mut out_start = 0usize; + let mut rest = indices; + while let Some(&first) = rest.first() { + let chunk_idx = (first + offset) / FL_CHUNK_SIZE; + let chunk_end = (chunk_idx + 1) * FL_CHUNK_SIZE - offset; + let count = rest.partition_point(|&i| i < chunk_end); + on_chunk(chunk_idx, out_start, count); + out_start += count; + rest = &rest[count..]; + } + return; + } + + let bits = mask_values.bit_buffer(); + let len = bits.len(); + let num_chunks = (offset + len).div_ceil(FL_CHUNK_SIZE); + let mut out_start = 0usize; + for chunk_idx in 0..num_chunks { + let chunk_start = chunk_idx * FL_CHUNK_SIZE; + let start = chunk_start.saturating_sub(offset); + let end = (chunk_start + FL_CHUNK_SIZE - offset).min(len); + let count = bits.count_range(start, end); + if count > 0 { + on_chunk(chunk_idx, out_start, count); + out_start += count; + } + } +} + +/// Visits selected in-chunk positions grouped by chunk, passing `(chunk_idx, out_start, positions)` +/// to `on_chunk`. +fn visit_mask_chunks( + mask_values: &MaskValues, + offset: usize, + mut on_chunk: impl FnMut(usize, usize, &[usize]), +) { + let mut positions = [0usize; FL_CHUNK_SIZE]; + if let Some(indices) = mask_values.cached_indices() { + let mut out_start = 0usize; + let mut rest = indices; + while let Some(&first) = rest.first() { + let chunk_idx = (first + offset) / FL_CHUNK_SIZE; + let chunk_start = chunk_idx * FL_CHUNK_SIZE; + let chunk_end = chunk_start + FL_CHUNK_SIZE - offset; + let count = rest.partition_point(|&i| i < chunk_end); + for (dst, &orig_idx) in positions[..count].iter_mut().zip(&rest[..count]) { + *dst = orig_idx + offset - chunk_start; + } + on_chunk(chunk_idx, out_start, &positions[..count]); + out_start += count; + rest = &rest[count..]; + } + return; + } + + let bits = mask_values.bit_buffer(); + let len = bits.len(); + let num_chunks = (offset + len).div_ceil(FL_CHUNK_SIZE); + let mut out_start = 0usize; + for chunk_idx in 0..num_chunks { + let chunk_start = chunk_idx * FL_CHUNK_SIZE; + let start = chunk_start.saturating_sub(offset); + let end = (chunk_start + FL_CHUNK_SIZE - offset).min(len); + let chunk_offset = start + offset - chunk_start; + let mut count = 0usize; + bits.slice(start..end).for_each_set_index(|rel| { + positions[count] = chunk_offset + rel; + count += 1; + }); + if count > 0 { + on_chunk(chunk_idx, out_start, &positions[..count]); + out_start += count; + } + } +} diff --git a/encodings/fastlanes/src/affine/compute/mod.rs b/encodings/fastlanes/src/affine/compute/mod.rs new file mode 100644 index 00000000000..c4cd3debd22 --- /dev/null +++ b/encodings/fastlanes/src/affine/compute/mod.rs @@ -0,0 +1,257 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Chunk-level compute kernels (`filter`, `take`, `compare`) for [`Affine`](crate::Affine). + +mod compare; +mod filter; +mod take; + +use std::mem; +use std::mem::MaybeUninit; + +use fastlanes::BitPacking; +use fastlanes::FoR; +use num_traits::AsPrimitive; +use num_traits::PrimInt; +use num_traits::WrappingAdd; +use num_traits::WrappingMul; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::ExecutionCtx; +use vortex_array::arrays::Slice; +use vortex_array::arrays::slice::SliceArraySlotsExt; +use vortex_array::arrays::slice::SliceKernel; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::PhysicalPType; +use vortex_buffer::filter::ChunkDecoder; +use vortex_buffer::filter::FILTER_CHUNK_LEN; +use vortex_error::VortexResult; + +use crate::Affine; +use crate::BitPacked; +use crate::BitPackedArrayExt; +use crate::FL_CHUNK_SIZE; +use crate::affine::array::AffineArrayExt; +use crate::affine::array::AffineArraySlotsExt; +use crate::affine::array::affine_decompress::Params; +use crate::affine::array::affine_decompress::physical_as_logical; + +const _: () = assert!(FL_CHUNK_SIZE == FILTER_CHUNK_LEN); + +/// Maximum number of indices for which [`AffineBitPackedChunks::decode_indices`] extracts +/// individual values instead of unpacking the whole narrow chunk first. +pub(super) const fn unpack_chunk_threshold() -> usize { + match size_of::() { + 1 => 16, + 2 => 32, + 4 => 64, + 8 => 160, + _ => unreachable!(), + } +} + +/// Maximum sparse index count supported by stack-allocated scratch in `decode_indices`. +const MAX_SPARSE_STACK: usize = unpack_chunk_threshold::(); + +/// Resolves `array.encoded()` to an aligned [`BitPacked`] array when possible. +/// +/// Slicing a patched `BitPacked` child leaves a lazy `Slice` wrapper; resolving it via +/// [`SliceKernel`] keeps the fused chunk-pruned kernels active on sliced arrays. +pub(super) fn resolve_aligned_bitpacked( + array: ArrayView<'_, Affine>, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + let encoded = array.encoded(); + let candidate = if let Some(bp) = encoded.as_opt::() { + Some(bp.array().clone()) + } else if let Some(slice) = encoded.as_opt::() + && let Some(bp) = slice.child().as_opt::() + { + ::slice(bp, slice.slice_range().clone(), ctx)? + } else { + None + }; + Ok(candidate.filter(|arr| { + arr.as_opt::() + .is_some_and(|bp| bp.offset() == array.offset()) + })) +} + +/// Chunk decoder for an [`Affine`] array backed by an aligned [`BitPacked`] child whose physical +/// residual type `U` is narrower than `T`. +pub(super) struct AffineNarrowBitPackedChunks<'a, T, U> { + packed: &'a [U], + bit_width: usize, + packed_chunk_len: usize, + params: &'a Params, +} + +impl<'a, T, U> AffineNarrowBitPackedChunks<'a, T, U> { + pub(super) fn new(packed: &'a [U], bit_width: usize, params: &'a Params) -> Self { + Self { + packed, + bit_width, + packed_chunk_len: FL_CHUNK_SIZE * bit_width / (8 * size_of::()), + params, + } + } + + #[inline] + fn chunk(&self, chunk_idx: usize) -> &[U] { + &self.packed[chunk_idx * self.packed_chunk_len..][..self.packed_chunk_len] + } +} + +// SAFETY: Both `decode_chunk` and `decode_indices` initialize every element of `dst`. +unsafe impl ChunkDecoder for AffineNarrowBitPackedChunks<'_, T, U> +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul + AsPrimitive, + i64: AsPrimitive, + u64: AsPrimitive, + U: PhysicalPType + BitPacking + AsPrimitive, +{ + #[inline] + fn decode_chunk(&self, chunk_idx: usize, dst: &mut [MaybeUninit; FILTER_CHUNK_LEN]) { + let mut scratch = [U::default(); FL_CHUNK_SIZE]; + // SAFETY: `self.chunk(chunk_idx)` holds one chunk packed at `self.bit_width` bits. + unsafe { + BitPacking::unchecked_unpack(self.bit_width, self.chunk(chunk_idx), &mut scratch); + } + self.params.apply_narrow(chunk_idx, 0, &scratch, dst); + } + + #[inline] + fn decode_indices(&self, chunk_idx: usize, indices: &[usize], dst: &mut [MaybeUninit]) { + debug_assert_eq!(indices.len(), dst.len()); + debug_assert!(indices.iter().all(|&index| index < FL_CHUNK_SIZE)); + let count = indices.len(); + if count == 0 { + return; + } + let packed_chunk = self.chunk(chunk_idx); + if count <= unpack_chunk_threshold::() { + let mut unpacked = [const { MaybeUninit::::uninit() }; MAX_SPARSE_STACK]; + // SAFETY: every index is < FL_CHUNK_SIZE and `unpacked[..count]` holds `count` slots. + unsafe { + BitPacking::unchecked_unpack_indices( + self.bit_width, + packed_chunk, + indices, + &mut unpacked[..count], + ); + } + // SAFETY: `unchecked_unpack_indices` initialized the first `count` slots. + let unpacked = unsafe { unpacked[..count].assume_init_ref() }; + self.params + .apply_selected_narrow(chunk_idx, indices, unpacked, dst); + } else { + let mut scratch = [U::default(); FL_CHUNK_SIZE]; + // SAFETY: `packed_chunk` holds one chunk packed at `self.bit_width` bits. + unsafe { + BitPacking::unchecked_unpack(self.bit_width, packed_chunk, &mut scratch); + } + self.params + .apply_gather_narrow(chunk_idx, indices, &scratch, dst); + } + } +} + +/// Chunk decoder for an [`Affine`] array backed by an aligned [`BitPacked`] child of the same +/// width as `T`. +/// +/// Flat chunks (`scale == 1 && slope == 0`) unpack straight into `dst` with FastLanes' fused +/// `FoR::unchecked_unfor_pack`. +pub(super) struct AffineSameWidthBitPackedChunks<'a, T: PhysicalPType> { + packed: &'a [T::Physical], + bit_width: usize, + packed_chunk_len: usize, + params: &'a Params, +} + +impl<'a, T: PhysicalPType> AffineSameWidthBitPackedChunks<'a, T> { + pub(super) fn new(packed: &'a [T::Physical], bit_width: usize, params: &'a Params) -> Self { + Self { + packed, + bit_width, + packed_chunk_len: FL_CHUNK_SIZE * bit_width / (8 * size_of::()), + params, + } + } + + #[inline] + fn chunk(&self, chunk_idx: usize) -> &[T::Physical] { + &self.packed[chunk_idx * self.packed_chunk_len..][..self.packed_chunk_len] + } +} + +// SAFETY: Both `decode_chunk` and `decode_indices` initialize every element of `dst`. +unsafe impl ChunkDecoder for AffineSameWidthBitPackedChunks<'_, T> +where + T: PhysicalPType> + + AsPrimitive + + AsPrimitive + + PrimInt + + WrappingAdd + + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, +{ + #[inline] + fn decode_chunk(&self, chunk_idx: usize, dst: &mut [MaybeUninit; FILTER_CHUNK_LEN]) { + let packed_chunk = self.chunk(chunk_idx); + // SAFETY: `T::Physical` has the same size and alignment as `T`, and the unpack below + // initializes every slot of `dst` before any element is read. + let phys_dst = unsafe { + mem::transmute::< + &mut [MaybeUninit; FILTER_CHUNK_LEN], + &mut [T::Physical; FL_CHUNK_SIZE], + >(dst) + }; + if self.params.is_flat(chunk_idx) { + let reference = self.params.references.get(chunk_idx).as_(); + // SAFETY: `packed_chunk` holds one chunk packed at `self.bit_width` bits. + unsafe { FoR::unchecked_unfor_pack(self.bit_width, packed_chunk, reference, phys_dst) }; + } else { + // SAFETY: `packed_chunk` holds one chunk packed at `self.bit_width` bits. + unsafe { BitPacking::unchecked_unpack(self.bit_width, packed_chunk, phys_dst) }; + self.params + .apply_chunk(chunk_idx, 0, physical_as_logical::(phys_dst)); + } + } + + #[inline] + fn decode_indices(&self, chunk_idx: usize, indices: &[usize], dst: &mut [MaybeUninit]) { + debug_assert_eq!(indices.len(), dst.len()); + debug_assert!(indices.iter().all(|&index| index < FL_CHUNK_SIZE)); + let count = indices.len(); + if count == 0 { + return; + } + let packed_chunk = self.chunk(chunk_idx); + if count <= unpack_chunk_threshold::() { + let mut unpacked = [const { MaybeUninit::::uninit() }; MAX_SPARSE_STACK]; + // SAFETY: every index is < FL_CHUNK_SIZE and `unpacked[..count]` holds `count` slots. + unsafe { + BitPacking::unchecked_unpack_indices( + self.bit_width, + packed_chunk, + indices, + &mut unpacked[..count], + ); + } + // SAFETY: `unchecked_unpack_indices` initialized the first `count` slots. + let unpacked = unsafe { unpacked[..count].assume_init_ref() }; + self.params + .apply_selected_narrow(chunk_idx, indices, unpacked, dst); + } else { + let mut scratch = [T::Physical::default(); FL_CHUNK_SIZE]; + // SAFETY: `packed_chunk` holds one chunk packed at `self.bit_width` bits. + unsafe { + BitPacking::unchecked_unpack(self.bit_width, packed_chunk, &mut scratch); + } + self.params + .apply_gather_narrow(chunk_idx, indices, &scratch, dst); + } + } +} diff --git a/encodings/fastlanes/src/affine/compute/take.rs b/encodings/fastlanes/src/affine/compute/take.rs new file mode 100644 index 00000000000..f429d51c9f4 --- /dev/null +++ b/encodings/fastlanes/src/affine/compute/take.rs @@ -0,0 +1,550 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Chunk-pruned `take` kernel for [`Affine`]. + +use std::mem::MaybeUninit; + +use fastlanes::BitPacking; +use fastlanes::FoR; +use num_traits::AsPrimitive; +use num_traits::PrimInt; +use num_traits::WrappingAdd; +use num_traits::WrappingMul; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::Canonical; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::dict::TakeExecute; +use vortex_array::dtype::IntegerPType; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::PhysicalPType; +use vortex_array::match_each_integer_ptype; +use vortex_array::match_each_unsigned_integer_ptype; +use vortex_array::patches::Patches; +use vortex_array::scalar::Scalar; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_buffer::BufferAllocatorRef; +use vortex_buffer::BufferMut; +use vortex_error::VortexResult; +use vortex_mask::Mask; + +use super::AffineNarrowBitPackedChunks; +use super::AffineSameWidthBitPackedChunks; +use super::resolve_aligned_bitpacked; +use super::unpack_chunk_threshold; +use crate::Affine; +use crate::BitPacked; +use crate::BitPackedArrayExt; +use crate::FL_CHUNK_SIZE; +use crate::affine::array::AffineArrayExt; +use crate::affine::array::AffineArraySlotsExt; +use crate::affine::array::affine_decompress::Params; +use crate::take_chunks::check_indices; +use crate::take_chunks::nullable_positions; +use crate::take_chunks::take_in_order; +use crate::take_chunks::valid_positions; + +/// Above this fraction of the array, fused full-array decode plus primitive gather beats sparse +/// chunked take. +const FULL_ARRAY_DECODE_RATIO: usize = 8; + +/// With dense patches (> 1/256 rows patched), full-array decode + sequential patch application +/// beats per-index patch search once take selectivity exceeds 1/16. +const PATCHED_FULL_DECODE_RATIO: usize = 16; +const DENSE_PATCH_RATIO: usize = 256; + +impl TakeExecute for Affine { + fn take( + array: ArrayView<'_, Self>, + indices: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + if indices.is_empty() { + let dtype = array + .dtype() + .union_nullability(indices.dtype().nullability()); + return Ok(Some(Canonical::empty(&dtype).into_array())); + } + if matches!(indices.validity()?, Validity::AllInvalid) { + return Ok(Some( + ConstantArray::new(Scalar::null(array.dtype().as_nullable()), indices.len()) + .into_array(), + )); + } + if indices.len().saturating_mul(FULL_ARRAY_DECODE_RATIO) > array.len() { + return Ok(None); + } + + if let Some(bp_arr) = resolve_aligned_bitpacked(array, ctx)? { + let bp = bp_arr.as_::(); + let bit_width = bp.bit_width(); + if let Some(patches) = bp.patches() + && indices.len().saturating_mul(PATCHED_FULL_DECODE_RATIO) > array.len() + && patches.num_patches().saturating_mul(DENSE_PATCH_RATIO) > array.len() + { + 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(array.dtype().as_nullable()), + indices_prim.len(), + ) + .into_array(), + )); + } + let taken_validity = array.validity()?.take(&indices_prim.clone().into_array())?; + return match_each_integer_ptype!(array.ptype(), |T| { + take_bitpacked_typed::( + array, + bp, + bit_width, + &indices_prim, + &index_validity, + taken_validity, + ctx, + ) + .map(Some) + }); + } + + 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(array.dtype().as_nullable()), + indices_prim.len(), + ) + .into_array(), + )); + } + let taken_encoded = array + .encoded() + .take(indices_prim.clone().into_array())? + .execute::(ctx)?; + match_each_integer_ptype!(array.ptype(), |T| { + take_residuals_typed::(array, taken_encoded, &indices_prim, &index_validity, ctx) + .map(Some) + }) + } +} + +fn take_bitpacked_typed( + array: ArrayView<'_, Affine>, + bp: ArrayView<'_, BitPacked>, + bit_width: u8, + indices: &PrimitiveArray, + index_validity: &Mask, + taken_validity: Validity, + ctx: &mut ExecutionCtx, +) -> VortexResult +where + T: PhysicalPType> + + AsPrimitive + + AsPrimitive + + PrimInt + + WrappingAdd + + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, +{ + match_each_integer_ptype!(indices.ptype(), |I| { + take_bitpacked_with_index::( + array, + bp, + bit_width, + indices, + index_validity, + taken_validity, + ctx, + ) + }) +} + +fn take_bitpacked_with_index( + array: ArrayView<'_, Affine>, + bp: ArrayView<'_, BitPacked>, + bit_width: u8, + indices: &PrimitiveArray, + index_validity: &Mask, + taken_validity: Validity, + ctx: &mut ExecutionCtx, +) -> VortexResult +where + T: PhysicalPType> + + AsPrimitive + + AsPrimitive + + PrimInt + + WrappingAdd + + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, + I: IntegerPType, +{ + let indices_slice = indices.as_slice::(); + check_indices(indices_slice, index_validity, array.len())?; + + let params = Params::::execute(array, ctx)?; + let encoded_ptype = bp.dtype().as_ptype(); + let bit_width = usize::from(bit_width); + let sparse_limit = unpack_chunk_threshold::(); + let mut output = BufferMut::::with_capacity_in(indices.len(), ctx.allocator().clone()); + let mut scratch = [const { MaybeUninit::::uninit() }; FL_CHUNK_SIZE]; + + if encoded_ptype.byte_width() < T::PTYPE.byte_width() { + match_each_unsigned_integer_ptype!(encoded_ptype, |U| { + take_bitpacked_narrow::( + bp, + bit_width, + ¶ms, + indices_slice, + index_validity, + sparse_limit, + &mut output, + &mut scratch, + ) + }); + } else { + let chunks = AffineSameWidthBitPackedChunks::::new( + bp.packed_slice::(), + bit_width, + ¶ms, + ); + match index_validity { + Mask::AllTrue(_) => take_in_order( + &chunks, + &mut output, + valid_positions(indices_slice, params.offset), + sparse_limit, + &mut scratch, + ), + _ => take_in_order( + &chunks, + &mut output, + nullable_positions(indices_slice, index_validity, params.offset), + sparse_limit, + &mut scratch, + ), + } + } + + if let Some(patches) = bp.patches() { + apply_taken_patches::(&mut output, &patches, indices, indices_slice, ¶ms, ctx)?; + } + + Ok(PrimitiveArray::new(output.freeze(), taken_validity).into_array()) +} + +#[expect( + clippy::too_many_arguments, + reason = "typed bitpacked take dispatch parameters" +)] +fn take_bitpacked_narrow( + bp: ArrayView<'_, BitPacked>, + bit_width: usize, + params: &Params, + indices_slice: &[I], + index_validity: &Mask, + sparse_limit: usize, + output: &mut BufferMut, + scratch: &mut [MaybeUninit; FL_CHUNK_SIZE], +) where + T: NativePType + PrimInt + WrappingAdd + WrappingMul + AsPrimitive, + i64: AsPrimitive, + u64: AsPrimitive, + U: PhysicalPType + BitPacking + AsPrimitive, + I: IntegerPType, +{ + let chunks = + AffineNarrowBitPackedChunks::::new(bp.packed_slice::(), bit_width, params); + match index_validity { + Mask::AllTrue(_) => take_in_order( + &chunks, + output, + valid_positions(indices_slice, params.offset), + sparse_limit, + scratch, + ), + _ => take_in_order( + &chunks, + output, + nullable_positions(indices_slice, index_validity, params.offset), + sparse_limit, + scratch, + ), + } +} + +/// Apply [`BitPacked`] patches to `output` for the taken `indices`, decoding each matched patch +/// residual with the model of its original `(chunk, j)` position. +fn apply_taken_patches( + output: &mut [T], + patches: &Patches, + indices: &PrimitiveArray, + indices_slice: &[I], + params: &Params, + ctx: &mut ExecutionCtx, +) -> VortexResult<()> +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, + I: IntegerPType, +{ + let taken_patches = if patches.chunk_offsets().is_some() || patches.num_patches() > 4096 { + patches.take_search(indices.clone(), false, ctx)? + } else { + patches.take(&indices.clone().into_array(), ctx)? + }; + let Some(taken_patches) = taken_patches else { + return Ok(()); + }; + + let out_indices = taken_patches + .indices() + .clone() + .execute::(ctx)?; + let patch_values = taken_patches + .values() + .clone() + .execute::(ctx)?; + let patch_offset = taken_patches.offset(); + + match_each_unsigned_integer_ptype!(out_indices.ptype(), |P| { + apply_taken_patches_typed::( + output, + out_indices.as_slice::

(), + patch_offset, + &patch_values, + indices_slice, + params, + ) + }); + Ok(()) +} + +fn apply_taken_patches_typed( + output: &mut [T], + out_indices: &[P], + patch_offset: usize, + patch_values: &PrimitiveArray, + indices_slice: &[I], + params: &Params, +) where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, + I: IntegerPType, + P: Copy + AsPrimitive, +{ + match_each_integer_ptype!(patch_values.ptype(), |V| { + apply_taken_patches_values::( + output, + out_indices, + patch_offset, + patch_values.as_slice::(), + indices_slice, + params, + ) + }); +} + +fn apply_taken_patches_values( + output: &mut [T], + out_indices: &[P], + patch_offset: usize, + patch_values: &[V], + indices_slice: &[I], + params: &Params, +) where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, + u64: AsPrimitive, + I: IntegerPType, + P: Copy + AsPrimitive, + V: NativePType + AsPrimitive, +{ + for (&out_idx, &val) in out_indices.iter().zip(patch_values) { + let out_idx = out_idx.as_() - patch_offset; + let orig_idx = AsPrimitive::::as_(indices_slice[out_idx]); + let pos = params.offset + orig_idx; + let residual: T = >::as_(val.as_()); + output[out_idx] = params.decode(pos / FL_CHUNK_SIZE, pos % FL_CHUNK_SIZE, residual); + } +} + +/// Apply the affine model to already-taken residuals from a non-BitPacked child. +fn take_residuals_typed( + array: ArrayView<'_, Affine>, + taken_encoded: PrimitiveArray, + indices: &PrimitiveArray, + index_validity: &Mask, + ctx: &mut ExecutionCtx, +) -> VortexResult +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul + AsPrimitive, + i64: AsPrimitive, + u64: AsPrimitive, +{ + let params = Params::::execute(array, ctx)?; + let validity = taken_encoded.validity()?; + let encoded_ptype = taken_encoded.ptype(); + + let values = if encoded_ptype == T::PTYPE { + let mut values = taken_encoded.into_buffer::().into_mut(); + match_each_integer_ptype!(indices.ptype(), |I| { + apply_taken_in_place::( + &mut values, + indices.as_slice::(), + index_validity, + ¶ms, + ) + }); + values.freeze() + } else { + match_each_unsigned_integer_ptype!(encoded_ptype, |U| { + take_residuals_narrow_index::( + taken_encoded.as_slice::(), + indices, + index_validity, + ¶ms, + ctx.allocator(), + ) + }) + }; + + Ok(PrimitiveArray::new(values, validity).into_array()) +} + +fn take_residuals_narrow_index( + src: &[U], + indices: &PrimitiveArray, + index_validity: &Mask, + params: &Params, + allocator: &BufferAllocatorRef, +) -> Buffer +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul + AsPrimitive, + i64: AsPrimitive, + u64: AsPrimitive, + U: Copy + AsPrimitive, +{ + match_each_integer_ptype!(indices.ptype(), |I| { + apply_taken_narrow::( + src, + indices.as_slice::(), + index_validity, + params, + allocator, + ) + }) +} + +fn apply_taken_in_place( + values: &mut [T], + indices: &[I], + index_validity: &Mask, + params: &Params, +) where + T: NativePType + PrimInt + WrappingAdd + WrappingMul, + i64: AsPrimitive, + I: IntegerPType, +{ + if params.all_constant_flat() { + params.apply_chunk(0, 0, values); + return; + } + + let offset = params.offset; + match index_validity { + Mask::AllTrue(_) => { + for (val, &idx) in values.iter_mut().zip(indices) { + let pos = offset + AsPrimitive::::as_(idx); + *val = params.decode(pos / FL_CHUNK_SIZE, pos % FL_CHUNK_SIZE, *val); + } + } + Mask::AllFalse(_) => values.fill(T::zero()), + Mask::Values(mask_vals) => { + let bits = mask_vals.bit_buffer(); + for (i, (val, &idx)) in values.iter_mut().zip(indices).enumerate() { + if bits.value(i) { + let pos = offset + AsPrimitive::::as_(idx); + *val = params.decode(pos / FL_CHUNK_SIZE, pos % FL_CHUNK_SIZE, *val); + } else { + *val = T::zero(); + } + } + } + } +} + +fn apply_taken_narrow( + src: &[U], + indices: &[I], + index_validity: &Mask, + params: &Params, + allocator: &BufferAllocatorRef, +) -> Buffer +where + T: NativePType + PrimInt + WrappingAdd + WrappingMul + AsPrimitive, + i64: AsPrimitive, + u64: AsPrimitive, + U: Copy + AsPrimitive, + I: IntegerPType, +{ + let len = src.len(); + let mut out = BufferMut::::with_capacity_in(len, allocator.clone()); + let dst = &mut out.spare_capacity_mut()[..len]; + + if params.all_constant_flat() { + params.apply_narrow(0, 0, src, dst); + } else { + let offset = params.offset; + match index_validity { + Mask::AllTrue(_) => { + for ((slot, &e), &idx) in dst.iter_mut().zip(src).zip(indices) { + let pos = offset + AsPrimitive::::as_(idx); + let residual: T = >::as_(e.as_()); + slot.write(params.decode(pos / FL_CHUNK_SIZE, pos % FL_CHUNK_SIZE, residual)); + } + } + Mask::AllFalse(_) => { + for slot in dst.iter_mut() { + slot.write(T::zero()); + } + } + Mask::Values(mask_vals) => { + let bits = mask_vals.bit_buffer(); + for (i, ((slot, &e), &idx)) in dst.iter_mut().zip(src).zip(indices).enumerate() { + if bits.value(i) { + let pos = offset + AsPrimitive::::as_(idx); + let residual: T = >::as_(e.as_()); + slot.write(params.decode( + pos / FL_CHUNK_SIZE, + pos % FL_CHUNK_SIZE, + residual, + )); + } else { + slot.write(T::zero()); + } + } + } + } + } + + // SAFETY: every slot in `0..len` was initialized above. + unsafe { out.set_len(len) }; + out.freeze() +} diff --git a/encodings/fastlanes/src/affine/mod.rs b/encodings/fastlanes/src/affine/mod.rs new file mode 100644 index 00000000000..e902109d177 --- /dev/null +++ b/encodings/fastlanes/src/affine/mod.rs @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +mod array; +pub use array::AffineArrayExt; +pub use array::AffineArraySlotsExt; +pub use array::AffineData; +pub use array::AffineSlots; +pub use array::affine_compress::AffineModeEstimates; +pub use array::affine_compress::AffineOptions; + +mod compute; + +#[cfg(test)] +mod tests; + +mod plugin; +pub use plugin::AffinePlugin; +pub use plugin::affine_id; + +mod vtable; +pub use vtable::Affine; +pub use vtable::AffineArray; +pub(crate) use vtable::initialize; diff --git a/encodings/fastlanes/src/affine/plugin.rs b/encodings/fastlanes/src/affine/plugin.rs new file mode 100644 index 00000000000..eb08e263f8c --- /dev/null +++ b/encodings/fastlanes/src/affine/plugin.rs @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Serde for `fastlanes.affine`, which stores the residuals and the three per-chunk parameter +//! arrays as children. + +use prost::Message as _; +use vortex_array::ArrayDeserialization; +use vortex_array::ArrayId; +use vortex_array::ArrayPlugin; +use vortex_array::ArrayRef; +use vortex_array::ArraySerialization; +use vortex_array::IntoArray; +use vortex_array::VTable; +use vortex_array::dtype::DType; +use vortex_array::dtype::PType; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_err; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +use crate::Affine; +use crate::FL_CHUNK_SIZE; +use crate::affine::array::AffineArrayExt; +use crate::affine::array::AffineArraySlotsExt; +use crate::affine::array::MAX_SLOPE_SHIFT; +use crate::affine::array::num_chunks; + +/// The serialized and in-memory ID of the [`Affine`] array. +pub fn affine_id() -> ArrayId { + static ID: CachedId = CachedId::new("fastlanes.affine"); + *ID +} + +/// Metadata for `fastlanes.affine`. The children are encoded, references, scales and slopes. +#[derive(Clone, prost::Message)] +struct AffineMetadata { + /// The position of the first element within the first chunk. + #[prost(uint32, tag = "1")] + offset: u32, + /// The number of fractional bits in each slope. + #[prost(uint32, tag = "2")] + slope_shift: u32, + /// The byte width of the unsigned residuals, or 0 when they have the array's own type. + #[prost(uint32, tag = "3")] + encoded_bytes: u32, +} + +/// Serde for the [`Affine`] array. +/// +/// Register this plugin, or call [`crate::initialize`], to enable serde. +#[derive(Clone, Debug)] +pub struct AffinePlugin; + +impl ArrayPlugin for AffinePlugin { + fn id(&self) -> ArrayId { + VTable::id(&Affine) + } + + fn serialize( + &self, + array: &ArrayRef, + _session: &VortexSession, + ) -> VortexResult> { + let view = array + .as_opt::() + .ok_or_else(|| vortex_err!("Affine plugin cannot serialize {}", array.encoding_id()))?; + let encoded_dtype = view.encoded().dtype(); + let metadata = AffineMetadata { + offset: u32::from(view.offset()), + slope_shift: u32::from(view.slope_shift()), + encoded_bytes: if encoded_dtype == view.dtype() { + 0 + } else { + u32::try_from(encoded_dtype.as_ptype().byte_width())? + }, + }; + Ok(Some(ArraySerialization::new( + affine_id(), + metadata.encode_to_vec(), + vec![], + vec![ + view.encoded().clone(), + view.references().clone(), + view.scales().clone(), + view.slopes().clone(), + ], + ))) + } + + fn deserialize( + &self, + parts: ArrayDeserialization<'_>, + _session: &VortexSession, + ) -> VortexResult { + vortex_ensure!( + parts.buffers.is_empty(), + "AffineArray expects 0 buffers, got {}", + parts.buffers.len() + ); + vortex_ensure_eq!( + parts.children.len(), + 4, + "Expected 4 children for {}, found {}", + affine_id(), + parts.children.len() + ); + let metadata = AffineMetadata::decode(parts.metadata)?; + vortex_ensure!( + usize::try_from(metadata.offset).is_ok_and(|offset| offset < FL_CHUNK_SIZE), + "Affine offset must be less than {FL_CHUNK_SIZE}, got {}", + metadata.offset + ); + vortex_ensure!( + metadata.slope_shift <= u32::from(MAX_SLOPE_SHIFT), + "Affine slope shift must be at most {MAX_SLOPE_SHIFT}, got {}", + metadata.slope_shift + ); + let offset = u16::try_from(metadata.offset)?; + let chunks = num_chunks(offset, parts.len); + let param_dtype = parts.dtype.as_nonnullable(); + let encoded_dtype = match metadata.encoded_bytes { + 0 => parts.dtype.clone(), + 1 => DType::Primitive(PType::U8, parts.dtype.nullability()), + 2 => DType::Primitive(PType::U16, parts.dtype.nullability()), + 4 => DType::Primitive(PType::U32, parts.dtype.nullability()), + 8 => DType::Primitive(PType::U64, parts.dtype.nullability()), + other => vortex_bail!("Affine residuals cannot be {other} bytes wide"), + }; + let encoded = parts.children.get(0, &encoded_dtype, parts.len)?; + let references = parts.children.get(1, ¶m_dtype, chunks)?; + let scales = parts.children.get(2, ¶m_dtype, chunks)?; + let slopes = parts + .children + .get(3, &DType::Primitive(PType::I64, false.into()), chunks)?; + Ok(Affine::try_new( + encoded, + references, + scales, + slopes, + offset, + u8::try_from(metadata.slope_shift)?, + )? + .into_array()) + } +} diff --git a/encodings/fastlanes/src/affine/tests.rs b/encodings/fastlanes/src/affine/tests.rs new file mode 100644 index 00000000000..7a03b28500b --- /dev/null +++ b/encodings/fastlanes/src/affine/tests.rs @@ -0,0 +1,1048 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::LazyLock; + +use rand::RngExt; +use rand::SeedableRng; +use rand::rngs::StdRng; +use rstest::rstest; +use vortex_array::ArrayContext; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +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::assert_arrays_eq; +use vortex_array::buffer::BufferHandle; +use vortex_array::builders::dict::dict_encode; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::compute::conformance::consistency::test_array_consistency; +use vortex_array::compute::conformance::filter::test_filter_conformance; +use vortex_array::compute::conformance::take::test_take_conformance; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::optimizer::ArrayOptimizer; +use vortex_array::patches::Patches; +use vortex_array::scalar::Scalar; +use vortex_array::scalar_fn::builtin::binary::CompareKernel; +use vortex_array::scalar_fn::builtin::operators::CompareOperator; +use vortex_array::scalar_fn::builtin::operators::Operator; +use vortex_array::serde::SerializeOptions; +use vortex_array::serde::SerializedArray; +use vortex_array::validity::Validity; +use vortex_buffer::BitBuffer; +use vortex_buffer::Buffer; +use vortex_buffer::ByteBuffer; +use vortex_buffer::ByteBufferMut; +use vortex_error::VortexResult; +use vortex_mask::Mask; +use vortex_session::VortexSession; +use vortex_session::registry::ReadContext; + +use crate::Affine; +use crate::AffineArray; +use crate::AffineArrayExt; +use crate::AffineArraySlotsExt; +use crate::AffineOptions; +use crate::BitPacked; +use crate::BitPackedArrayExt; +use crate::BitPackedData; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +const MODES: [AffineOptions; 5] = [ + AffineOptions::FOR, + AffineOptions::SCALE, + AffineOptions::SLOPE, + AffineOptions::ALL, + AffineOptions::LECO, +]; + +const ALL_OPERATORS: [CompareOperator; 6] = [ + CompareOperator::Eq, + CompareOperator::NotEq, + CompareOperator::Lt, + CompareOperator::Lte, + CompareOperator::Gt, + CompareOperator::Gte, +]; + +/// Timestamps in nanoseconds on a one-minute grid, with every seventh sample missing. +fn grid_timestamps() -> PrimitiveArray { + PrimitiveArray::from_iter( + (0..5000i64) + .filter(|i| i % 7 != 3) + .map(|i| 1_700_000_000_000_000_000 + i * 60_000_000_000), + ) +} + +/// Millisecond timestamps in nanoseconds, roughly every 2.6 s with jitter. +fn jittered_timestamps() -> PrimitiveArray { + PrimitiveArray::from_iter( + (0..5000i64) + .map(|i| 1_655_870_000_000_000_000 + i * 2_612_000_000 + (i * 7919 % 41) * 1_000_000), + ) +} + +/// Prices on a 0.01 tick, stored in units of 1e-8. +fn prices() -> PrimitiveArray { + PrimitiveArray::from_iter( + (0..3000i64).map(|i| 6_776_562_000_000 + ((i * 37) % 501 - 250) * 1_000_000), + ) +} + +fn nullable_ids() -> PrimitiveArray { + PrimitiveArray::from_option_iter((0..4000u32).map(|i| (i % 11 != 0).then_some(3 * i + 17))) +} + +fn extremes() -> PrimitiveArray { + PrimitiveArray::from_iter([i64::MIN, i64::MAX, 0, -1, 1, i64::MIN + 1, i64::MAX - 1]) +} + +fn unsigned_extremes() -> PrimitiveArray { + PrimitiveArray::from_iter((0..2100u64).map(|i| u64::MAX - i * i * 1000)) +} + +fn small_signed() -> PrimitiveArray { + PrimitiveArray::from_iter((0..3000i32).map(|i| -128 + (i % 256)).map(|v| v as i8)) +} + +#[rstest] +#[case::grid(grid_timestamps())] +#[case::jitter(jittered_timestamps())] +#[case::prices(prices())] +#[case::nullable(nullable_ids())] +#[case::extremes(extremes())] +#[case::unsigned_extremes(unsigned_extremes())] +#[case::small_signed(small_signed())] +#[case::empty(PrimitiveArray::from_iter(Vec::::new()))] +#[case::all_null(PrimitiveArray::from_option_iter([None::, None, None]))] +fn roundtrip(#[case] values: PrimitiveArray) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + for options in MODES { + let encoded = Affine::encode(&values, options, &mut ctx)?; + assert_arrays_eq!(encoded, values, &mut ctx); + } + Ok(()) +} + +#[rstest] +#[case::start(0..100)] +#[case::within_chunk(1500..1600)] +#[case::across_chunks(1000..3500)] +#[case::to_end(2900..4285)] +fn slice(#[case] range: std::ops::Range) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = grid_timestamps(); + let expected = values.clone().into_array().slice(range.clone())?; + for options in MODES { + let encoded = Affine::encode(&values, options, &mut ctx)?.into_array(); + let sliced = encoded.slice(range.clone())?; + assert_arrays_eq!(sliced, expected, &mut ctx); + // Slicing twice exercises the offset of an already-sliced array. + let inner = 7..range.len() / 2; + assert_arrays_eq!( + sliced.slice(inner.clone())?, + expected.slice(inner)?, + &mut ctx + ); + } + Ok(()) +} + +#[test] +fn scalar_at() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = nullable_ids(); + let expected = values.clone().into_array(); + let encoded = Affine::encode(&values, AffineOptions::ALL, &mut ctx)?.into_array(); + for index in [0, 1, 11, 1023, 1024, 2047, 3999] { + assert_eq!( + encoded.execute_scalar(index, &mut ctx)?, + expected.execute_scalar(index, &mut ctx)? + ); + } + Ok(()) +} + +#[test] +fn scale_finds_the_grid_step() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let encoded = Affine::encode(&prices(), AffineOptions::SCALE, &mut ctx)?; + let scale = encoded + .scales() + .as_constant() + .and_then(|s| s.as_primitive().typed_value::()); + assert_eq!(scale, Some(1_000_000)); + Ok(()) +} + +#[test] +fn slope_fits_a_regular_grid() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = PrimitiveArray::from_iter((0..4096i64).map(|i| 1_000 + 60 * i)); + let encoded = Affine::encode(&values, AffineOptions::SLOPE, &mut ctx)?; + let residuals = encoded + .encoded() + .clone() + .execute::(&mut ctx)?; + // All-zero residuals are stored in the narrowest type. + assert_eq!(residuals.ptype(), PType::U8); + assert!(residuals.as_slice::().iter().all(|&r| r == 0)); + Ok(()) +} + +fn serde_roundtrip(array: &ArrayRef) -> VortexResult { + let array_ctx = ArrayContext::empty(); + let buffers = array.serialize(&array_ctx, &SESSION, &SerializeOptions::default())?; + let mut bytes = ByteBufferMut::empty(); + for buffer in buffers { + bytes.extend_from_slice(&buffer); + } + SerializedArray::try_from(bytes.freeze())?.decode( + array.dtype(), + array.len(), + &ReadContext::new(array_ctx.to_ids()), + &SESSION, + ) +} + +#[rstest] +#[case::grid(grid_timestamps())] +#[case::nullable(nullable_ids())] +fn serde(#[case] values: PrimitiveArray) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + for options in MODES { + let encoded = Affine::encode(&values, options, &mut ctx)?.into_array(); + let read = serde_roundtrip(&encoded)?; + assert_eq!(read.encoding_id(), encoded.encoding_id()); + assert_arrays_eq!(read, values, &mut ctx); + let sliced = encoded.slice(1500..2600)?.optimize_ctx(&SESSION)?; + assert_arrays_eq!(serde_roundtrip(&sliced)?, sliced, &mut ctx); + } + Ok(()) +} + +/// Bit-pack the residuals, narrow enough to need patches, so decoding takes the fused path. +#[rstest] +#[case::grid(grid_timestamps(), 3)] +#[case::grid_wide(grid_timestamps(), 40)] +#[case::jitter(jittered_timestamps(), 2)] +#[case::nullable(nullable_ids(), 1)] +fn fused_bitpacked(#[case] values: PrimitiveArray, #[case] bit_width: u8) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + for options in MODES { + let affine = Affine::encode(&values, options, &mut ctx)?; + // BitPacked needs a width below the residual type's. + let width = bit_width.min(affine.encoded().dtype().as_ptype().bit_width() as u8 - 1); + let packed = BitPackedData::encode(affine.encoded(), width, &mut ctx)?.into_array(); + let fused = Affine::try_new( + packed, + affine.references().clone(), + affine.scales().clone(), + affine.slopes().clone(), + 0, + affine.slope_shift(), + )? + .into_array(); + assert_arrays_eq!(fused, values, &mut ctx); + for range in [1500..2600, 1024..2048, 7..900] { + let expected = values.clone().into_array().slice(range.clone())?; + assert_arrays_eq!(fused.slice(range)?, expected, &mut ctx); + } + } + Ok(()) +} + +/// Dictionary-encoded residuals decode fused with the model, including slices and slopes. +#[rstest] +#[case::grid(grid_timestamps())] +#[case::jitter(jittered_timestamps())] +#[case::prices(prices())] +fn fused_dict(#[case] values: PrimitiveArray) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + for options in MODES { + let affine = Affine::encode(&values, options, &mut ctx)?; + let residuals = affine + .encoded() + .clone() + .execute::(&mut ctx)?; + let dict = dict_encode(&residuals.into_array(), &mut ctx)?; + let fused = Affine::try_new( + dict.into_array(), + affine.references().clone(), + affine.scales().clone(), + affine.slopes().clone(), + 0, + affine.slope_shift(), + )? + .into_array(); + assert_arrays_eq!(fused, values, &mut ctx); + for range in [1500..2600, 1024..2048, 7..900] { + let expected = values.clone().into_array().slice(range.clone())?; + assert_arrays_eq!(fused.slice(range)?, expected, &mut ctx); + } + } + Ok(()) +} + +/// Bit-pack an Affine array's residuals at `bit_width` (clamped below residual type width). +fn bitpack_affine( + affine: &AffineArray, + bit_width: u8, + ctx: &mut ExecutionCtx, +) -> VortexResult { + let max_width = affine.encoded().dtype().as_ptype().bit_width() as u8 - 1; + let width = bit_width.min(max_width); + let packed = BitPackedData::encode(affine.encoded(), width, ctx)?.into_array(); + Affine::try_new( + packed, + affine.references().clone(), + affine.scales().clone(), + affine.slopes().clone(), + affine.offset(), + affine.slope_shift(), + ) +} + +#[rstest] +#[case::grid(grid_timestamps(), 3)] +#[case::jitter(jittered_timestamps(), 2)] +#[case::prices(prices(), 4)] +#[case::nullable(nullable_ids(), 1)] +#[case::extremes(unsigned_extremes(), 8)] +fn filter_bitpacked_and_primitive( + #[case] values: PrimitiveArray, + #[case] bit_width: u8, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let mut rng = StdRng::seed_from_u64(42); + for options in MODES { + let prim_affine = Affine::encode(&values, options, &mut ctx)?; + let bp_affine = bitpack_affine(&prim_affine, bit_width, &mut ctx)?; + for range in [ + 0..values.len(), + 7..values.len().min(3500), + 1023..values.len().min(2050), + ] { + if range.is_empty() { + continue; + } + let expected_slice = values.clone().into_array().slice(range.clone())?; + let sliced_prim = prim_affine + .clone() + .into_array() + .slice(range.clone())? + .optimize_ctx(&SESSION)?; + let sliced_bp = bp_affine + .clone() + .into_array() + .slice(range.clone())? + .optimize_ctx(&SESSION)?; + let slice_len = range.len(); + + for density in [0.005, 0.02, 0.15, 0.5, 0.99] { + let bits = BitBuffer::from_iter((0..slice_len).map(|_| rng.random_bool(density))); + for mask in [ + Mask::from_buffer(bits.clone()), + Mask::from_indices(slice_len, bits.set_indices()), + Mask::from_slices(slice_len, bits.set_slices().collect()), + ] { + let expected = expected_slice.filter(mask.clone())?; + + let got_bp = ::filter( + sliced_bp.as_::(), + &mask, + &mut ctx, + )? + .expect("Affine filter kernel must engage on BitPacked child"); + assert_arrays_eq!(got_bp, expected, &mut ctx); + + let got_prim = ::filter( + sliced_prim.as_::(), + &mask, + &mut ctx, + )? + .expect("Affine filter kernel must engage on Primitive child"); + assert_arrays_eq!(got_prim, expected, &mut ctx); + } + } + } + } + Ok(()) +} + +#[test] +fn filter_and_take_conformance_and_consistency() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + for values in [ + PrimitiveArray::from_iter((0..2500i64).map(|i| 1_000_000 + (i % 73) * 1_000)), + PrimitiveArray::from_option_iter( + (0..2500i32).map(|i| (i % 9 != 0).then_some(-50_000 + i * 17)), + ), + PrimitiveArray::from_iter((0..1500u16).map(|i| 200 + (i % 64) * 5)), + ] { + for options in [ + AffineOptions::SCALE, + AffineOptions::SLOPE, + AffineOptions::ALL, + ] { + let affine = Affine::encode(&values, options, &mut ctx)?; + let bp = bitpack_affine(&affine, 3, &mut ctx)?; + test_filter_conformance(&bp.clone().into_array(), &mut ctx); + test_take_conformance(&bp.clone().into_array(), &mut ctx); + test_array_consistency(&bp.into_array(), &mut ctx); + } + } + Ok(()) +} + +#[rstest] +#[case::grid(grid_timestamps(), 3)] +#[case::jitter(jittered_timestamps(), 2)] +#[case::prices(prices(), 4)] +#[case::nullable(nullable_ids(), 1)] +fn take_sparse_sliced_and_nullable_indices( + #[case] values: PrimitiveArray, + #[case] bit_width: u8, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let mut rng = StdRng::seed_from_u64(99); + for options in MODES { + let prim_affine = Affine::encode(&values, options, &mut ctx)?; + let bp_affine = bitpack_affine(&prim_affine, bit_width, &mut ctx)?; + for range in [ + 0..values.len(), + 13..values.len().min(3200), + 1023..values.len().min(2050), + ] { + let expected_slice = values.clone().into_array().slice(range.clone())?; + let sliced_prim = prim_affine + .clone() + .into_array() + .slice(range.clone())? + .optimize_ctx(&SESSION)?; + let sliced_bp = bp_affine + .clone() + .into_array() + .slice(range.clone())? + .optimize_ctx(&SESSION)?; + let slice_len = range.len(); + let k = (slice_len / 20).max(5); + + // Unsorted with duplicates (u32). + let raw_indices: Vec = (0..k) + .map(|_| rng.random_range(0..slice_len) as u32) + .collect(); + let indices_u32 = PrimitiveArray::from_iter(raw_indices.clone()).into_array(); + let expected = expected_slice.take(indices_u32.clone())?; + let got_bp = + ::take(sliced_bp.as_::(), &indices_u32, &mut ctx)? + .expect("sparse take must engage on BitPacked child"); + assert_arrays_eq!(got_bp, expected, &mut ctx); + let got_prim = + ::take(sliced_prim.as_::(), &indices_u32, &mut ctx)? + .expect("sparse take must engage on Primitive child"); + assert_arrays_eq!(got_prim, expected, &mut ctx); + + // Nullable signed indices with out-of-bounds garbage at null slots. + let mut vals = Vec::with_capacity(k); + let mut valid_bits = Vec::with_capacity(k); + for (pos, &idx) in raw_indices.iter().enumerate() { + if pos % 5 == 0 { + vals.push(-999_999i64); + valid_bits.push(false); + } else { + vals.push(i64::from(idx)); + valid_bits.push(true); + } + } + let nullable_idx = + PrimitiveArray::new(Buffer::from_iter(vals), Validity::from_iter(valid_bits)) + .into_array(); + let expected_null = expected_slice.take(nullable_idx.clone())?; + let got_null_bp = + ::take(sliced_bp.as_::(), &nullable_idx, &mut ctx)? + .expect("nullable sparse take must engage"); + assert_arrays_eq!(got_null_bp, expected_null, &mut ctx); + let got_null_prim = ::take( + sliced_prim.as_::(), + &nullable_idx, + &mut ctx, + )? + .expect("nullable sparse take must engage on Primitive child"); + assert_arrays_eq!(got_null_prim, expected_null, &mut ctx); + + // All-null indices. + let all_null = + PrimitiveArray::new(Buffer::from_iter(vec![999_999u32; 8]), Validity::AllInvalid) + .into_array(); + assert_arrays_eq!( + sliced_bp.take(all_null.clone())?, + expected_slice.take(all_null)?, + &mut ctx + ); + } + } + Ok(()) +} + +#[rstest] +#[case::grid(grid_timestamps(), 3)] +#[case::jitter(jittered_timestamps(), 2)] +#[case::prices(prices(), 4)] +#[case::nullable(nullable_ids(), 1)] +#[case::unsigned_extremes(unsigned_extremes(), 8)] +#[case::small_signed(small_signed(), 4)] +fn compare_matches_primitive_across_modes_and_slices( + #[case] values: PrimitiveArray, + #[case] bit_width: u8, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let sample_positions = [0, 1, values.len() / 3, values.len() / 2, values.len() - 1]; + let mut constants: Vec = Vec::new(); + for pos in sample_positions { + let s = values.execute_scalar(pos, &mut ctx)?; + if !s.is_null() { + constants.push(s); + } + } + match values.ptype() { + PType::I64 => { + constants.extend([ + Scalar::from(i64::MIN), + Scalar::from(i64::MAX), + Scalar::from(0i64), + Scalar::from(6_776_562_000_001i64), + Scalar::from(1_700_000_000_000_000_001i64), + ]); + } + PType::U32 => { + constants.extend([ + Scalar::from(0u32), + Scalar::from(18u32), + Scalar::from(u32::MAX), + ]); + } + PType::U64 => { + constants.extend([Scalar::from(0u64), Scalar::from(u64::MAX)]); + } + PType::I8 => { + constants.extend([ + Scalar::from(i8::MIN), + Scalar::from(-1i8), + Scalar::from(i8::MAX), + ]); + } + _ => {} + } + + for options in MODES { + let prim_affine = Affine::encode(&values, options, &mut ctx)?; + let bp_affine = bitpack_affine(&prim_affine, bit_width, &mut ctx).ok(); + for range in [ + 0..values.len(), + 7..values.len().min(3200), + 1023..values.len().min(2050), + ] { + let expected_slice = values.clone().into_array().slice(range.clone())?; + let sliced_prim = prim_affine + .clone() + .into_array() + .slice(range.clone())? + .optimize_ctx(&SESSION)?; + let sliced_bp = bp_affine + .as_ref() + .map(|bp| { + bp.clone() + .into_array() + .slice(range.clone())? + .optimize_ctx(&SESSION) + }) + .transpose()?; + let slice_len = range.len(); + + for scalar in &constants { + for rhs_nullability in [Nullability::NonNullable, Nullability::Nullable] { + let rhs = ConstantArray::new( + scalar.cast(&scalar.dtype().with_nullability(rhs_nullability))?, + slice_len, + ) + .into_array(); + for op in ALL_OPERATORS { + let expected = expected_slice.binary(rhs.clone(), Operator::from(op))?; + if let Some(sliced_bp) = &sliced_bp { + let got_bp = ::compare( + sliced_bp.as_::(), + &rhs, + op, + &mut ctx, + )? + .expect("compare kernel must engage on BitPacked child"); + assert_arrays_eq!(got_bp, expected, &mut ctx); + } + + let got_prim = ::compare( + sliced_prim.as_::(), + &rhs, + op, + &mut ctx, + )? + .expect("compare kernel must engage on Primitive child"); + assert_arrays_eq!(got_prim, expected, &mut ctx); + } + } + } + + let target = sliced_bp.as_ref().unwrap_or(&sliced_prim); + if let Some(first_scalar) = constants.first() { + let rhs = ConstantArray::new(first_scalar.clone(), slice_len).into_array(); + let actual_rev = rhs.binary(target.clone(), Operator::Lt)?; + let expected_rev = rhs.binary(expected_slice.clone(), Operator::Lt)?; + assert_arrays_eq!(actual_rev, expected_rev, &mut ctx); + } + let null_rhs = + ConstantArray::new(Scalar::null(values.dtype().as_nullable()), slice_len) + .into_array(); + let actual_null = target.binary(null_rhs.clone(), Operator::Eq)?; + let expected_null = expected_slice.binary(null_rhs, Operator::Eq)?; + assert_arrays_eq!(actual_null, expected_null, &mut ctx); + } + } + Ok(()) +} + +/// Negative scales, zero scales, wrapping arithmetic, and negative slopes constructed directly via +/// `Affine::try_new` must compare bit-identically to canonical execution across all 6 operators. +#[test] +fn compare_negative_scales_slopes_and_wrapping() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let len = 3072usize; + let residuals = PrimitiveArray::from_iter((0..len).map(|i| (i % 100) as u8)); + let packed = BitPackedData::encode(&residuals.clone().into_array(), 7, &mut ctx)?.into_array(); + + // Chunk 0: negative scale (no wrap) + // Chunk 1: zero scale (constant chunk) + // Chunk 2: positive scale that wraps i16::MAX -> i16::MIN + let references = PrimitiveArray::from_iter([500i16, -42, 32_000]).into_array(); + let scales = PrimitiveArray::from_iter([-5i16, 0, 20]).into_array(); + let slopes = ConstantArray::new(0i64, 3).into_array(); + + for encoded in [packed, residuals.into_array()] { + let affine = Affine::try_new( + encoded, + references.clone(), + scales.clone(), + slopes.clone(), + 0, + 0, + )? + .into_array(); + let canonical = affine + .clone() + .execute::(&mut ctx)? + .into_array(); + + for rhs_val in [ + i16::MIN, + -32_000, + -43, + -42, + -41, + 0, + 5, + 6, + 250, + 251, + 499, + 500, + 501, + 32_000, + 32_760, + i16::MAX, + ] { + let rhs = ConstantArray::new(rhs_val, len).into_array(); + for op in ALL_OPERATORS { + let got = + ::compare(affine.as_::(), &rhs, op, &mut ctx)? + .expect("compare kernel must engage"); + let want = canonical.binary(rhs.clone(), Operator::from(op))?; + assert_arrays_eq!(got, want, &mut ctx); + } + } + } + + // Extreme slope that wraps `i64` in `slope_term` must fall back per chunk cleanly. + let wrap_residuals = PrimitiveArray::from_iter((0..2048).map(|i| (i % 16) as u8)); + let wrap_packed = + BitPackedData::encode(&wrap_residuals.into_array(), 4, &mut ctx)?.into_array(); + let wrap_affine = Affine::try_new( + wrap_packed, + PrimitiveArray::from_iter([0i64, i64::MAX - 10]).into_array(), + PrimitiveArray::from_iter([3i64, -7]).into_array(), + PrimitiveArray::from_iter([i64::MAX / 2, -(1i64 << 40)]).into_array(), + 0, + 4, + )? + .into_array(); + let wrap_canonical = wrap_affine + .clone() + .execute::(&mut ctx)? + .into_array(); + for rhs_val in [i64::MIN, -100, 0, 100, i64::MAX - 10, i64::MAX] { + let rhs = ConstantArray::new(rhs_val, 2048).into_array(); + for op in ALL_OPERATORS { + let got = ::compare( + wrap_affine.as_::(), + &rhs, + op, + &mut ctx, + )? + .expect("compare kernel must engage"); + let want = wrap_canonical.binary(rhs.clone(), Operator::from(op))?; + assert_arrays_eq!(got, want, &mut ctx); + } + } + Ok(()) +} + +/// Non-divisible `Eq`/`NotEq` and out-of-range constants on unpatched non-nullable `SCALE` +/// arrays must short-circuit to a `ConstantArray`, while patches in short-circuited chunks must +/// still be evaluated accurately. +#[test] +fn compare_constant_short_circuit_and_patched_override() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let unpatched_vals = PrimitiveArray::from_iter((0..3072i64).map(|i| 1_000 + 10 * (i % 16))); + let affine = Affine::encode(&unpatched_vals, AffineOptions::SCALE, &mut ctx)?; + let bp = bitpack_affine(&affine, 4, &mut ctx)?; + assert!(bp.encoded().as_::().patches().is_none()); + + let rhs_off_grid = ConstantArray::new(1_005i64, 3072).into_array(); + let eq_res = ::compare( + bp.as_view(), + &rhs_off_grid, + CompareOperator::Eq, + &mut ctx, + )? + .expect("compare must engage"); + assert!( + eq_res.as_constant().is_some(), + "off-grid Eq should short-circuit to Constant" + ); + assert_arrays_eq!( + eq_res, + ConstantArray::new(false, 3072).into_array(), + &mut ctx + ); + + let rhs_high = ConstantArray::new(5_000i64, 3072).into_array(); + let lt_res = + ::compare(bp.as_view(), &rhs_high, CompareOperator::Lt, &mut ctx)? + .expect("compare must engage"); + assert!( + lt_res.as_constant().is_some(), + "out-of-range Lt should short-circuit to Constant" + ); + assert_arrays_eq!( + lt_res, + ConstantArray::new(true, 3072).into_array(), + &mut ctx + ); + + // Patched override inside a chunk whose packed bounds [1000, 1150] are all < 5000. + let patched_vals = PrimitiveArray::from_iter((0..3072i64).map(|i| { + if i == 1500 { + 5_000 + } else { + 1_000 + 10 * (i % 16) + } + })); + let affine_p = Affine::encode(&patched_vals, AffineOptions::SCALE, &mut ctx)?; + let bp_p = bitpack_affine(&affine_p, 4, &mut ctx)?; + assert!(bp_p.encoded().as_::().patches().is_some()); + for op in ALL_OPERATORS { + let got = ::compare(bp_p.as_view(), &rhs_high, op, &mut ctx)? + .expect("compare must engage"); + let want = patched_vals + .clone() + .into_array() + .binary(rhs_high.clone(), Operator::from(op))?; + assert_arrays_eq!(got, want, &mut ctx); + } + Ok(()) +} + +/// Bit-width 0 residuals (e.g. exact linear sequence) must support filter, take, and compare. +#[test] +fn zero_bit_width_filter_take_compare() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = PrimitiveArray::from_iter((0..3072i64).map(|i| 1_000 + 60 * i)); + let affine = Affine::encode(&values, AffineOptions::SLOPE, &mut ctx)?; + let bp = bitpack_affine(&affine, 0, &mut ctx)?.into_array(); + + let mask = Mask::from_indices(3072, [0, 5, 1023, 1024, 2500, 3071]); + assert_arrays_eq!(bp.filter(mask.clone())?, values.filter(mask)?, &mut ctx); + + let indices = PrimitiveArray::from_iter([3071u32, 0, 1024, 5]).into_array(); + assert_arrays_eq!(bp.take(indices.clone())?, values.take(indices)?, &mut ctx); + + for rhs_val in [999i64, 1_000, 1_000 + 60 * 1024, 1_000 + 60 * 3071, 999_999] { + let rhs = ConstantArray::new(rhs_val, 3072).into_array(); + for op in ALL_OPERATORS { + assert_arrays_eq!( + bp.binary(rhs.clone(), Operator::from(op))?, + values + .clone() + .into_array() + .binary(rhs.clone(), Operator::from(op))?, + &mut ctx + ); + } + } + Ok(()) +} + +#[test] +fn estimate_modes_ranks_candidates_accurately() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let price_est = Affine::estimate_modes(&prices(), 16, &mut ctx)?; + assert!( + price_est.for_bits - price_est.scale_bits >= 0.5, + "prices should strongly prefer SCALE over FOR: {price_est:?}" + ); + + let grid_est = Affine::estimate_modes(&grid_timestamps(), 16, &mut ctx)?; + assert!( + grid_est.all_bits < grid_est.scale_bits && grid_est.for_bits - grid_est.all_bits >= 0.5, + "grid timestamps should prefer ALL over SCALE/FOR: {grid_est:?}" + ); + + let mut rng = StdRng::seed_from_u64(123); + let random = PrimitiveArray::from_iter((0..16_384u32).map(|_| rng.random_range(0..10_000))); + let rand_est = Affine::estimate_modes(&random, 16, &mut ctx)?; + assert!( + rand_est.for_bits - rand_est.scale_bits < 0.5 + && rand_est.for_bits - rand_est.slope_bits < 0.5 + && rand_est.for_bits - rand_est.all_bits < 0.5, + "random data should not beat FOR by >= 0.5 bits/val: {rand_est:?}" + ); + Ok(()) +} + +/// Filter, take, and compare must work identically when `encoded` is a `Dict` child or when +/// `references`/`scales`/`slopes` and `BitPacked` patch values are themselves compressed. +#[test] +fn compute_kernels_with_dict_child_and_compressed_patches() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = PrimitiveArray::from_iter((0..4096i64).map(|i| { + if i % 37 == 0 { + 1_000_000 + 100 * (200 + (i % 50)) + } else { + 1_000_000 + (i / 1024) * 50_000 + 100 * (i % 15) + } + })); + let affine = Affine::encode(&values, AffineOptions::SCALE, &mut ctx)?; + + // 1. Dict child with compressed references. + let residuals = affine + .encoded() + .clone() + .execute::(&mut ctx)?; + let dict_encoded = dict_encode(&residuals.into_array(), &mut ctx)?.into_array(); + let dict_refs = dict_encode(affine.references(), &mut ctx)?.into_array(); + let dict_affine = Affine::try_new( + dict_encoded, + dict_refs, + affine.scales().clone(), + affine.slopes().clone(), + 0, + affine.slope_shift(), + )? + .into_array() + .slice(5..3900)? + .optimize_ctx(&SESSION)?; + let expected_slice = values.clone().into_array().slice(5..3900)?; + + let sparse_mask = Mask::from_indices(3895, [0, 32, 1020, 1021, 2500, 3894]); + assert_arrays_eq!( + dict_affine.filter(sparse_mask.clone())?, + expected_slice.filter(sparse_mask)?, + &mut ctx + ); + let take_idx = PrimitiveArray::from_iter([3894u32, 0, 1021, 32, 32]).into_array(); + assert_arrays_eq!( + dict_affine.take(take_idx.clone())?, + expected_slice.take(take_idx)?, + &mut ctx + ); + let rhs = ConstantArray::new(1_050_500i64, 3895).into_array(); + for op in ALL_OPERATORS { + assert_arrays_eq!( + dict_affine.binary(rhs.clone(), Operator::from(op))?, + expected_slice.binary(rhs.clone(), Operator::from(op))?, + &mut ctx + ); + } + + // 2. BitPacked child whose patch values are themselves BitPacked (exercising both sparse and + // dense patch-value paths in `apply_filtered_patches`). + let bp = BitPackedData::encode(affine.encoded(), 4, &mut ctx)?; + let orig_patches = bp.patches().expect("outliers must create patches"); + let compressed_patch_vals = + BitPackedData::encode(orig_patches.values(), 9, &mut ctx)?.into_array(); + let compressed_patches = orig_patches.map_values(|_| Ok(compressed_patch_vals))?; + let bp_parts = BitPacked::into_parts(bp); + let bp_with_compressed_patches = BitPacked::try_new( + bp_parts.packed, + affine.encoded().dtype().as_ptype(), + bp_parts.validity, + Some(compressed_patches), + 4, + bp_parts.len, + bp_parts.offset, + )? + .into_array(); + let bp_affine = Affine::try_new( + bp_with_compressed_patches, + affine.references().clone(), + affine.scales().clone(), + affine.slopes().clone(), + 0, + affine.slope_shift(), + )? + .into_array(); + + // Very sparse filter (hits < patches / 8) and dense filter (hits >= patches / 8). + let very_sparse = Mask::from_indices(4096, [0, 37, 74, 1500]); + assert_arrays_eq!( + bp_affine.filter(very_sparse.clone())?, + values.filter(very_sparse)?, + &mut ctx + ); + let dense = Mask::from_iter((0..4096).map(|i| i % 2 == 0)); + assert_arrays_eq!( + bp_affine.filter(dense.clone())?, + values.filter(dense)?, + &mut ctx + ); + Ok(()) +} + +/// Direct kernel calls must handle empty sliced arrays (`len == 0, offset > 0`), null constants, +/// constant-null patches, and empty / all-null take indices without panicking. +#[test] +fn compute_kernels_edge_cases() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let base = bitpack_affine( + &Affine::encode(&prices(), AffineOptions::SCALE, &mut ctx)?, + 10, + &mut ctx, + )?; + // Empty slice with non-zero offset. + let empty_sliced = Affine::try_new( + base.encoded().slice(5..5)?.optimize_ctx(&SESSION)?, + base.references().slice(0..1)?.optimize_ctx(&SESSION)?, + base.scales().slice(0..1)?.optimize_ctx(&SESSION)?, + base.slopes().slice(0..1)?.optimize_ctx(&SESSION)?, + 5, + base.slope_shift(), + )?; + let empty_rhs = ConstantArray::new(0i64, 0).into_array(); + let cmp_empty = ::compare( + empty_sliced.as_view(), + &empty_rhs, + CompareOperator::Lt, + &mut ctx, + )? + .expect("compare should handle empty sliced Affine"); + assert_eq!(cmp_empty.len(), 0); + assert_eq!(cmp_empty.dtype(), &DType::Bool(Nullability::NonNullable)); + + // Direct compare against a null constant. + let null_rhs = ConstantArray::new( + Scalar::null(DType::Primitive(PType::I64, Nullability::Nullable)), + base.len(), + ) + .into_array(); + let cmp_null = ::compare( + base.as_view(), + &null_rhs, + CompareOperator::Eq, + &mut ctx, + )? + .expect("compare should handle null constant RHS"); + assert_eq!(cmp_null.len(), base.len()); + assert!(cmp_null.all_invalid(&mut ctx)?); + + // Empty and all-null take indices (both BitPacked and non-BitPacked children). + let empty_idx = PrimitiveArray::from_iter(std::iter::empty::()).into_array(); + let all_null_idx = PrimitiveArray::new( + Buffer::from_iter([0u32, 1, 2]), + Validity::Array(BoolArray::from(BitBuffer::new_unset(3)).into_array()), + ) + .into_array(); + let prim_affine = Affine::encode(&prices(), AffineOptions::SCALE, &mut ctx)?; + for aff in [base.as_view(), prim_affine.as_view()] { + let taken_empty = ::take(aff, &empty_idx, &mut ctx)? + .expect("empty take should be handled"); + assert_eq!(taken_empty.len(), 0); + let taken_null = ::take(aff, &all_null_idx, &mut ctx)? + .expect("all-null take should be handled"); + assert_eq!(taken_null.len(), 3); + assert!(taken_null.all_invalid(&mut ctx)?); + } + + // Nullable BitPacked child whose patch values are `ConstantArray(null)`. + let len = 2048usize; + let validity = Validity::from_iter((0..len).map(|i| i != 17 && i != 1500)); + let packed_zeros = ByteBuffer::zeroed(2 * 128 * 4); + let null_patches = Patches::new( + len, + 0, + PrimitiveArray::from_iter([17u32, 1500]).into_array(), + ConstantArray::new( + Scalar::null(DType::Primitive(PType::U16, Nullability::Nullable)), + 2, + ) + .into_array(), + None, + &mut ctx, + )?; + let bp_null_patches = BitPacked::try_new( + BufferHandle::new_host(packed_zeros), + PType::U16, + validity, + Some(null_patches), + 4, + len, + 0, + )? + .into_array(); + let aff_null_patches = Affine::try_new( + bp_null_patches, + ConstantArray::new(100i64, 2).into_array(), + ConstantArray::new(5i64, 2).into_array(), + ConstantArray::new(0i64, 2).into_array(), + 0, + 16, + )?; + let mask = Mask::from_indices(len, [0, 17, 500, 1500, 2047]); + let filtered = ::filter(aff_null_patches.as_view(), &mask, &mut ctx)? + .expect("filter should handle constant-null patches"); + let expected = PrimitiveArray::new( + Buffer::from_iter([100i64; 5]), + Validity::from_iter([true, false, true, false, true]), + ); + assert_arrays_eq!(filtered, expected, &mut ctx); + Ok(()) +} diff --git a/encodings/fastlanes/src/affine/vtable/kernels.rs b/encodings/fastlanes/src/affine/vtable/kernels.rs new file mode 100644 index 00000000000..5d8a51c63f6 --- /dev/null +++ b/encodings/fastlanes/src/affine/vtable/kernels.rs @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_array::ArrayVTable; +use vortex_array::arrays::Dict; +use vortex_array::arrays::Filter; +use vortex_array::arrays::dict::TakeExecuteAdaptor; +use vortex_array::arrays::filter::FilterExecuteAdaptor; +use vortex_array::optimizer::kernels::ArrayKernelsExt; +use vortex_array::scalar_fn::ScalarFnVTable; +use vortex_array::scalar_fn::builtin::binary::Binary; +use vortex_array::scalar_fn::builtin::binary::CompareExecuteAdaptor; +use vortex_session::VortexSession; + +use crate::Affine; + +pub(crate) fn initialize(session: &VortexSession) { + let kernels = session.kernels(); + kernels.register_execute_parent_kernel(Binary.id(), Affine, CompareExecuteAdaptor(Affine)); + kernels.register_execute_parent_kernel(Filter.id(), Affine, FilterExecuteAdaptor(Affine)); + kernels.register_execute_parent_kernel(Dict.id(), Affine, TakeExecuteAdaptor(Affine)); +} diff --git a/encodings/fastlanes/src/affine/vtable/mod.rs b/encodings/fastlanes/src/affine/vtable/mod.rs new file mode 100644 index 00000000000..8e32a688e93 --- /dev/null +++ b/encodings/fastlanes/src/affine/vtable/mod.rs @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::fmt::Debug; +use std::hash::Hash; +use std::hash::Hasher; + +use vortex_array::Array; +use vortex_array::ArrayEq; +use vortex_array::ArrayHash; +use vortex_array::ArrayId; +use vortex_array::ArrayParts; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::EqMode; +use vortex_array::ExecutionCtx; +use vortex_array::ExecutionResult; +use vortex_array::IntoArray; +use vortex_array::arrays::Constant; +use vortex_array::arrays::Dict; +use vortex_array::arrays::Primitive; +use vortex_array::arrays::Slice; +use vortex_array::arrays::slice::SliceArraySlotsExt; +use vortex_array::buffer::BufferHandle; +use vortex_array::dtype::DType; +use vortex_array::dtype::PType; +use vortex_array::require_child; +use vortex_array::smallvec::smallvec; +use vortex_array::vtable::VTable; +use vortex_array::vtable::ValidityVTableFromChild; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_panic; +use vortex_session::VortexSession; + +use crate::AffineData; +use crate::BitPacked; +use crate::BitPackedArrayExt; +use crate::affine::array::AffineArrayExt; +use crate::affine::array::AffineArraySlotsExt; +use crate::affine::array::AffineSlots; +use crate::affine::array::AffineSlotsView; +use crate::affine::array::affine_decompress::decompress; +use crate::affine::array::num_chunks; +use crate::affine::plugin::affine_id; + +mod kernels; +mod operations; +mod rules; +mod slice; +mod validity; + +/// An [`Affine`]-encoded Vortex array. +pub type AffineArray = Array; + +pub(crate) fn initialize(session: &VortexSession) { + kernels::initialize(session); + rules::register_parent_rules(session); +} + +impl ArrayHash for AffineData { + fn array_hash(&self, state: &mut H, _accuracy: EqMode) { + self.offset.hash(state); + self.slope_shift.hash(state); + } +} + +impl ArrayEq for AffineData { + fn array_eq(&self, other: &Self, _accuracy: EqMode) -> bool { + self.offset == other.offset && self.slope_shift == other.slope_shift + } +} + +impl VTable for Affine { + type TypedArrayData = AffineData; + + type OperationsVTable = Self; + type ValidityVTable = ValidityVTableFromChild; + + fn id(&self) -> ArrayId { + affine_id() + } + + fn validate( + &self, + data: &Self::TypedArrayData, + dtype: &DType, + len: usize, + slots: &[Option], + ) -> VortexResult<()> { + let slots = AffineSlotsView::from_slots(slots); + validate_parts(&slots, data.offset, dtype, len) + } + + fn nbuffers(_array: ArrayView<'_, Self>) -> usize { + 0 + } + + fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle { + vortex_panic!("AffineArray buffer index {idx} out of bounds") + } + + fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option { + None + } + + fn with_buffers( + &self, + array: ArrayView<'_, Self>, + buffers: &[BufferHandle], + ) -> VortexResult> { + vortex_array::vtable::with_empty_buffers(self, array, buffers) + } + + fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String { + AffineSlots::NAMES[idx].to_string() + } + + fn execute(array: Array, ctx: &mut ExecutionCtx) -> VortexResult { + let array = if array.references().is::() { + array + } else { + require_child!(array, array.references(), AffineSlots::REFERENCES => Primitive) + }; + let array = if array.scales().is::() { + array + } else { + require_child!(array, array.scales(), AffineSlots::SCALES => Primitive) + }; + let array = if array.slopes().is::() { + array + } else { + require_child!(array, array.slopes(), AffineSlots::SLOPES => Primitive) + }; + // Dictionary-encoded residuals decode fused with the model, reading the dictionary's own + // children, so the dictionary itself is left unexecuted. + if array.encoded().is::() { + return Ok(ExecutionResult::done(decompress(&array, ctx)?.into_array())); + } + // A slice of a bit-packed child with patches stays lazy until executed. Step it to the + // sliced bit-packed array, so the fused unpack below still applies. + let slice_of_bitpacked = array + .encoded() + .as_opt::() + .is_some_and(|slice| slice.child().is::()); + let array = if slice_of_bitpacked { + require_child!(array, array.encoded(), AffineSlots::ENCODED => BitPacked) + } else { + array + }; + // The fused unpack reads a bit-packed child's buffers directly when its chunks line up. + let fused = array + .encoded() + .as_opt::() + .is_some_and(|bp| bp.offset() == array.offset()); + let array = if fused { + array + } else { + require_child!(array, array.encoded(), AffineSlots::ENCODED => Primitive) + }; + Ok(ExecutionResult::done(decompress(&array, ctx)?.into_array())) + } +} + +#[derive(Clone, Debug)] +pub struct Affine; + +impl Affine { + /// Construct an Affine array from its residuals and per-chunk parameters. + /// + /// `encoded` holds the residuals, either of the array's integer type or of a narrower unsigned + /// type. `references` and `scales` must be non-nullable arrays of the array's integer type, + /// and `slopes` a non-nullable `i64` array, each with one entry for every chunk spanned by + /// `offset + encoded.len()` elements. `offset` is the position of the first element within the + /// first chunk. + pub fn try_new( + encoded: ArrayRef, + references: ArrayRef, + scales: ArrayRef, + slopes: ArrayRef, + offset: u16, + slope_shift: u8, + ) -> VortexResult { + let dtype = references + .dtype() + .with_nullability(encoded.dtype().nullability()); + let len = encoded.len(); + let data = AffineData::try_new(offset, slope_shift)?; + let slots = smallvec![Some(encoded), Some(references), Some(scales), Some(slopes)]; + Array::try_from_parts(ArrayParts::new(Affine, dtype, len, data, slots)) + } +} + +fn validate_parts( + slots: &AffineSlotsView<'_>, + offset: u16, + dtype: &DType, + len: usize, +) -> VortexResult<()> { + vortex_ensure!( + dtype.is_int(), + "Affine requires an integer dtype, got {dtype}" + ); + let encoded_dtype = slots.encoded.dtype(); + vortex_ensure!( + encoded_dtype == dtype + || (encoded_dtype.is_unsigned_int() + && encoded_dtype.nullability() == dtype.nullability() + && encoded_dtype.as_ptype().byte_width() <= dtype.as_ptype().byte_width()), + "Affine encoded dtype must be {dtype} or a no wider unsigned integer, got {encoded_dtype}" + ); + vortex_ensure_eq!(slots.encoded.len(), len, "Affine encoded length mismatch"); + let num_chunks = num_chunks(offset, len); + let param_dtype = dtype.as_nonnullable(); + let slope_dtype = DType::Primitive(PType::I64, false.into()); + for (name, child, expected) in [ + ("references", slots.references, ¶m_dtype), + ("scales", slots.scales, ¶m_dtype), + ("slopes", slots.slopes, &slope_dtype), + ] { + vortex_ensure_eq!(child.dtype(), expected, "Affine {name} dtype mismatch"); + vortex_ensure_eq!(child.len(), num_chunks, "Affine {name} length mismatch"); + } + Ok(()) +} diff --git a/encodings/fastlanes/src/affine/vtable/operations.rs b/encodings/fastlanes/src/affine/vtable/operations.rs new file mode 100644 index 00000000000..f53ecd3ffa0 --- /dev/null +++ b/encodings/fastlanes/src/affine/vtable/operations.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use num_traits::AsPrimitive; +use vortex_array::ArrayView; +use vortex_array::ExecutionCtx; +use vortex_array::dtype::NativePType; +use vortex_array::match_each_integer_ptype; +use vortex_array::scalar::Scalar; +use vortex_array::vtable::OperationsVTable; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; + +use super::Affine; +use crate::FL_CHUNK_SIZE; +use crate::affine::array::AffineArrayExt; +use crate::affine::array::AffineArraySlotsExt; +use crate::affine::array::affine_decompress::decode_one; + +impl OperationsVTable for Affine { + type ProbeState = (); + + fn scalar_at( + array: ArrayView<'_, Affine>, + index: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let encoded = array.encoded().execute_scalar(index, ctx)?; + let position = usize::from(array.offset()) + index; + let (chunk, j) = (position / FL_CHUNK_SIZE, position % FL_CHUNK_SIZE); + let reference = array.references().execute_scalar(chunk, ctx)?; + let scale = array.scales().execute_scalar(chunk, ctx)?; + let slope = array + .slopes() + .execute_scalar(chunk, ctx)? + .as_primitive() + .typed_value::() + .vortex_expect("Affine slopes are non-nullable"); + let shift = array.slope_shift(); + + Ok(match_each_integer_ptype!(array.ptype(), |P| { + let encoded = encoded.as_primitive(); + // Narrow residuals are unsigned and fit in `P`'s bits, so they convert by truncation. + let residual = if encoded.ptype() == P::PTYPE { + encoded.typed_value::

() + } else { + encoded.as_::().map(>::as_) + }; + residual + .map(|e| { + let reference = reference + .as_primitive() + .typed_value::

() + .vortex_expect("Affine references are non-nullable"); + let scale = scale + .as_primitive() + .typed_value::

() + .vortex_expect("Affine scales are non-nullable"); + decode_one(e, reference, scale, slope, j, shift) + }) + .map(|v| Scalar::primitive::

(v, array.dtype().nullability())) + .unwrap_or_else(|| Scalar::null(array.dtype().clone())) + })) + } +} diff --git a/encodings/fastlanes/src/affine/vtable/rules.rs b/encodings/fastlanes/src/affine/vtable/rules.rs new file mode 100644 index 00000000000..35dc258c046 --- /dev/null +++ b/encodings/fastlanes/src/affine/vtable/rules.rs @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_array::arrays::Slice; +use vortex_array::arrays::slice::SliceReduceAdaptor; +use vortex_array::optimizer::kernels::ArrayKernelsExt; +use vortex_session::VortexSession; + +use crate::Affine; + +pub(crate) fn register_parent_rules(session: &VortexSession) { + session.kernels().register_reduce_parent_rule( + Slice, + Affine, + const { &SliceReduceAdaptor(Affine) }, + ); +} diff --git a/encodings/fastlanes/src/affine/vtable/slice.rs b/encodings/fastlanes/src/affine/vtable/slice.rs new file mode 100644 index 00000000000..84896db6f21 --- /dev/null +++ b/encodings/fastlanes/src/affine/vtable/slice.rs @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; + +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::IntoArray; +use vortex_array::arrays::slice::SliceReduce; +use vortex_error::VortexResult; + +use crate::Affine; +use crate::FL_CHUNK_SIZE; +use crate::affine::array::AffineArrayExt; +use crate::affine::array::AffineArraySlotsExt; + +impl SliceReduce for Affine { + fn slice(array: ArrayView<'_, Self>, range: Range) -> VortexResult> { + // Keep the parameters of the chunks the slice overlaps, and record how far into the first + // of them the slice starts, as FoR does. + let start = usize::from(array.offset()) + range.start; + let end = usize::from(array.offset()) + range.end; + let chunks = start / FL_CHUNK_SIZE..end.div_ceil(FL_CHUNK_SIZE); + Ok(Some( + Affine::try_new( + array.encoded().slice(range)?, + array.references().slice(chunks.clone())?, + array.scales().slice(chunks.clone())?, + array.slopes().slice(chunks)?, + u16::try_from(start % FL_CHUNK_SIZE)?, + array.slope_shift(), + )? + .into_array(), + )) + } +} diff --git a/encodings/fastlanes/src/affine/vtable/validity.rs b/encodings/fastlanes/src/affine/vtable/validity.rs new file mode 100644 index 00000000000..60c857865c6 --- /dev/null +++ b/encodings/fastlanes/src/affine/vtable/validity.rs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::vtable::ValidityChild; + +use super::Affine; +use crate::affine::array::AffineArraySlotsExt; + +impl ValidityChild for Affine { + fn validity_child(array: ArrayView<'_, Affine>) -> ArrayRef { + array.encoded().clone() + } +} diff --git a/encodings/fastlanes/src/lib.rs b/encodings/fastlanes/src/lib.rs index bb57be92000..5aa06759606 100644 --- a/encodings/fastlanes/src/lib.rs +++ b/encodings/fastlanes/src/lib.rs @@ -10,6 +10,7 @@ //! - [`BitPacked`] stores fixed-width integer values using the minimum bit width plus optional //! patches. //! - [`FoR`] stores frame-of-reference deltas from a base value. +//! - [`Affine`] extends per-chunk FoR with a common divisor and a linear trend per chunk. //! - [`Delta`] stores adjacent deltas in chunked form. //! - [`RLE`] stores repeated runs. //! @@ -27,6 +28,7 @@ //! The original encodings are described in the paper [The FastLanes Compression Layout](https://15721.courses.cs.cmu.edu/spring2024/papers/03-data2/p2132-afroozeh.pdf), //! but are not fully binary compatible. See the underlying [fastlanes](https://github.com/spiraldb/fastlanes) crate for more details. +pub use affine::*; pub use bitpacking::*; pub use delta::*; pub use for_::*; @@ -40,6 +42,7 @@ use vortex_buffer::Buffer; use vortex_buffer::BufferMut; use vortex_error::VortexResult; +mod affine; mod bitpacking; mod delta; mod for_; @@ -72,10 +75,12 @@ pub fn initialize(session: &VortexSession) { } session.arrays().register(Delta); session.arrays().register(FoRPlugin); + session.arrays().register(AffinePlugin); session.arrays().register(RLE); bitpacking::initialize(session); delta::initialize(session); for_::initialize(session); + affine::initialize(session); rle::initialize(session); // Register the encoding-specific aggregate kernels. diff --git a/scripts/codspeed_bench_counts.json b/scripts/codspeed_bench_counts.json index 8d8aa130eae..deed8d61d7b 100644 --- a/scripts/codspeed_bench_counts.json +++ b/scripts/codspeed_bench_counts.json @@ -109,6 +109,7 @@ "unary": 20 }, "vortex-fastlanes": { + "affine_decode": 0, "bitpack_compare": 2, "bitpack_compare_sweep": 56, "bitpacking_filter": 0, diff --git a/vortex-btrblocks/src/builder.rs b/vortex-btrblocks/src/builder.rs index 80023d98df3..3cc7b007d86 100644 --- a/vortex-btrblocks/src/builder.rs +++ b/vortex-btrblocks/src/builder.rs @@ -5,6 +5,7 @@ use vortex_array::ArrayId; use vortex_decimal_byte_parts::decimal_byte_parts_v2_id; +use vortex_fastlanes::affine_id; use vortex_fastlanes::for_v2_id; use vortex_session::VortexSession; use vortex_utils::aliases::hash_set::HashSet; @@ -72,6 +73,7 @@ impl CompressionMode { excluded.extend([ boolean::BoolRunEndScheme.id(), boolean::BoolSparseScheme.id(), + integer::AffineScheme.id(), integer::DeltaScheme::default().id(), integer::SparseScheme.id(), integer::IntRLEScheme.id(), @@ -99,9 +101,9 @@ impl CompressionMode { fn excluded_encodings(self) -> Vec { match self { Self::All | Self::Default | Self::Compact => Vec::new(), - // Multi-part DecimalByteParts arrays and FoR arrays with per-chunk references have no - // CUDA decode kernel. - Self::Cuda => vec![decimal_byte_parts_v2_id(), for_v2_id()], + // Affine, multi-part DecimalByteParts, and FoR arrays with per-chunk references have + // no CUDA decode kernel. + Self::Cuda => vec![affine_id(), decimal_byte_parts_v2_id(), for_v2_id()], } } } diff --git a/vortex-btrblocks/src/schemes/integer/affine.rs b/vortex-btrblocks/src/schemes/integer/affine.rs new file mode 100644 index 00000000000..70dbb525a09 --- /dev/null +++ b/vortex-btrblocks/src/schemes/integer/affine.rs @@ -0,0 +1,738 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Affine integer encoding: per-chunk reference, common divisor and linear trend. + +use vortex_array::ArrayId; +use vortex_array::ArrayRef; +use vortex_array::Canonical; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VTable; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::Constant; +use vortex_array::arrays::PrimitiveArray; +use vortex_compressor::builtins::BinaryDictScheme; +use vortex_compressor::builtins::DecimalDictScheme; +use vortex_compressor::builtins::FloatDictScheme; +use vortex_compressor::builtins::IntDictScheme; +use vortex_compressor::builtins::StringDictScheme; +use vortex_compressor::scheme::AncestorExclusion; +use vortex_compressor::scheme::ChildSelection; +use vortex_compressor::scheme::CompressionEstimate; +use vortex_compressor::scheme::DeferredEstimate; +use vortex_compressor::scheme::EstimateScore; +use vortex_compressor::scheme::EstimateVerdict; +use vortex_error::VortexResult; +use vortex_fastlanes::Affine; +use vortex_fastlanes::AffineArray; +use vortex_fastlanes::AffineArrayExt; +use vortex_fastlanes::AffineArraySlotsExt; +use vortex_fastlanes::AffineModeEstimates; +use vortex_fastlanes::AffineOptions; +use vortex_fastlanes::FL_CHUNK_SIZE; +use vortex_fastlanes::affine_id; + +use super::DeltaScheme; +use super::RunEndScheme; +use crate::ArrayAndStats; +use crate::CascadingCompressor; +use crate::CompressorContext; +use crate::Scheme; +use crate::SchemeExt; +use crate::SchemeId; +use crate::schemes::boolean::BoolRunEndScheme; + +/// The number of whole chunks the estimate fits the model to. +const SAMPLE_CHUNKS: usize = 16; + +/// The bits per value a mode must save over per-chunk FoR before Affine is worth its extra +/// decode work, the threshold Pco uses for its common-divisor mode. +const MIN_BITS_SAVED_PER_VALUE: f64 = 0.5; + +/// Affine encoding: `value = encoded * scale + reference + ((slope * j) >> shift)` per +/// 1024-element chunk. +/// +/// The scheme pre-estimates all candidate modes (`FOR`, `SCALE`, `SLOPE`, `ALL`) directly in +/// memory from sampled residual bit-width histograms + outlier patch costs, rejecting early if no +/// non-`FOR` mode saves at least [`MIN_BITS_SAVED_PER_VALUE`] bits per value over per-chunk FoR. +/// Only the winning mode is cascaded through the compressor on the sample to measure its final +/// compression ratio. +/// +/// Affine applies to every integer array the compressor reaches, including the integers that the +/// decimal scheme narrows decimals to and that ALP encodes floats as. +#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)] +pub struct AffineScheme; + +impl Scheme for AffineScheme { + fn scheme_name(&self) -> &'static str { + "vortex.int.affine" + } + + fn matches(&self, canonical: &Canonical) -> bool { + canonical.dtype().is_int() + } + + fn produced_encodings(&self) -> Vec { + // `Affine::encode` stores uniform per-chunk parameters as `ConstantArray`. + vec![affine_id(), Constant.id()] + } + + /// Children: encoded=0, references=1, scales=2, slopes=3. + fn num_children(&self) -> usize { + 4 + } + + /// Exclude dictionary codes (which start at 0 with no trend) and `RunEnd.ends` / + /// `BoolRunEnd.ends` (which are binary-searched via `scalar_at`, matching `FoR.v2`). + fn ancestor_exclusions(&self) -> Vec { + let mut exclusions: Vec<_> = [ + IntDictScheme.id(), + FloatDictScheme.id(), + StringDictScheme.id(), + BinaryDictScheme.id(), + DecimalDictScheme.id(), + RunEndScheme.id(), + ] + .into_iter() + .map(|ancestor| AncestorExclusion { + ancestor, + children: ChildSelection::One(1), + }) + .collect(); + exclusions.push(AncestorExclusion { + ancestor: BoolRunEndScheme.id(), + children: ChildSelection::One(0), + }); + exclusions + } + + fn expected_compression_ratio( + &self, + data: &ArrayAndStats, + compress_ctx: CompressorContext, + _exec_ctx: &mut ExecutionCtx, + ) -> CompressionEstimate { + // The residuals only shrink once a later layer packs them. Samples splice together short + // runs from across the array, so per-chunk models fitted to them mean nothing. + if compress_ctx.finished_cascading() + || compress_ctx.is_sample() + || data.array_len() < FL_CHUNK_SIZE + { + return CompressionEstimate::Verdict(EstimateVerdict::Skip); + } + let scheme = *self; + CompressionEstimate::Deferred(DeferredEstimate::Callback(Box::new( + move |compressor, data, best_so_far, compress_ctx, exec_ctx| { + if matches!(best_so_far, Some(EstimateScore::ZeroBytes)) { + return Ok(EstimateVerdict::Skip); + } + let primitive = data.array().clone().execute::(exec_ctx)?; + let Some(choice) = + choose_mode(&scheme, &primitive, compressor, &compress_ctx, exec_ctx)? + else { + return Ok(EstimateVerdict::Skip); + }; + if !choice.is_worthwhile() { + return Ok(EstimateVerdict::Skip); + } + let full_width = primitive.ptype().bit_width() as f64; + Ok(EstimateVerdict::Ratio(full_width / choice.bits.max(1e-3))) + }, + ))) + } + + fn compress( + &self, + compressor: &CascadingCompressor, + data: &ArrayAndStats, + compress_ctx: CompressorContext, + exec_ctx: &mut ExecutionCtx, + ) -> VortexResult { + let primitive = data.array().clone().execute::(exec_ctx)?; + let options = + choose_mode_for_compress(self, &primitive, compressor, &compress_ctx, exec_ctx)?; + let affine = Affine::encode(&primitive, options, exec_ctx)?; + compress_children(self, &affine, compressor, &compress_ctx, exec_ctx) + } +} + +/// Cascade every non-constant child of `affine`. +fn compress_children( + scheme: &AffineScheme, + affine: &AffineArray, + compressor: &CascadingCompressor, + compress_ctx: &CompressorContext, + exec_ctx: &mut ExecutionCtx, +) -> VortexResult { + let mut children = [ + affine.encoded().clone(), + affine.references().clone(), + affine.scales().clone(), + affine.slopes().clone(), + ]; + for (idx, child) in children.iter_mut().enumerate() { + if child.as_constant().is_none() { + *child = compressor.compress_child(child, compress_ctx, scheme.id(), idx, exec_ctx)?; + } + } + let [encoded, references, scales, slopes] = children; + Ok(Affine::try_new( + encoded, + references, + scales, + slopes, + affine.offset(), + affine.slope_shift(), + )? + .into_array()) +} + +/// The chosen non-`FOR` mode and its sampled bits per value alongside the per-chunk `FOR` +/// baseline. +#[derive(Debug, Clone, Copy)] +struct ModeChoice { + /// The chosen mode (never [`AffineOptions::FOR`]). + options: AffineOptions, + /// Sampled cascaded bits per value of the chosen mode. + bits: f64, + /// Estimated bits per value of per-chunk FoR on the same sample. + for_bits: f64, +} + +impl ModeChoice { + /// Whether the chosen mode is worth its decode work over per-chunk FoR. + fn is_worthwhile(&self) -> bool { + self.options != AffineOptions::FOR && self.for_bits - self.bits >= MIN_BITS_SAVED_PER_VALUE + } +} + +/// Pre-screened candidate modes from the fast in-memory residual estimator. +#[derive(Debug, Clone, Copy)] +struct PreEstimatePlan { + est: AffineModeEstimates, + scale_worthwhile: bool, + best_sloped: Option<(AffineOptions, f64)>, +} + +fn pre_estimate( + array: &PrimitiveArray, + exec_ctx: &mut ExecutionCtx, +) -> VortexResult { + let est = Affine::estimate_modes(array, SAMPLE_CHUNKS, exec_ctx)?; + let scale_worthwhile = est.for_bits - est.scale_bits >= MIN_BITS_SAVED_PER_VALUE; + let (sloped_opts, sloped_bits) = if est.all_bits < est.slope_bits { + (AffineOptions::ALL, est.all_bits) + } else { + (AffineOptions::SLOPE, est.slope_bits) + }; + let best_sloped = (est.for_bits - sloped_bits >= MIN_BITS_SAVED_PER_VALUE) + .then_some((sloped_opts, sloped_bits)); + Ok(PreEstimatePlan { + est, + scale_worthwhile, + best_sloped, + }) +} + +fn delta_allowed( + compressor: &CascadingCompressor, + compress_ctx: &CompressorContext, +) -> Option { + let delta_id = DeltaScheme::default().id(); + let active = compressor.has_scheme(delta_id) + && !compress_ctx + .cascade_history() + .iter() + .any(|&(id, _)| id == delta_id); + active.then_some(delta_id) +} + +fn measure_affine_bits( + scheme: &AffineScheme, + sample: &PrimitiveArray, + options: AffineOptions, + compressor: &CascadingCompressor, + compress_ctx: &CompressorContext, + exec_ctx: &mut ExecutionCtx, +) -> VortexResult { + let affine = Affine::encode(sample, options, exec_ctx)?; + let compressed = compress_children(scheme, &affine, compressor, compress_ctx, exec_ctx)?; + // Floor at 4 scalars (one per child) so Affine never beats a pure 2-scalar `Sequence` when + // all children collapse to `Constant`/`Sequence` with near-zero buffer bytes. + let min_bytes = (4 * sample.ptype().byte_width()) as u64; + Ok(compressed.nbytes().max(min_bytes) as f64 * 8.0 / sample.len() as f64) +} + +fn measure_delta_bits( + sample: &PrimitiveArray, + compressor: &CascadingCompressor, + compress_ctx: &CompressorContext, + delta_id: SchemeId, + exec_ctx: &mut ExecutionCtx, +) -> VortexResult { + let (bases, deltas) = vortex_fastlanes::delta_compress(sample, exec_ctx)?; + let mut bytes = 0u64; + for (idx, child) in [bases, deltas].into_iter().enumerate() { + bytes += compressor + .compress_child(&child.into_array(), compress_ctx, delta_id, idx, exec_ctx)? + .nbytes(); + } + Ok(bytes as f64 * 8.0 / sample.len() as f64) +} + +/// Pre-estimate all modes in memory, reject early if estimated savings over per-chunk FoR are +/// below [`MIN_BITS_SAVED_PER_VALUE`], and cascade only the winning non-`FOR` mode on the sample. +/// +/// A slope serves the same sorted and trending data as Delta, so when Delta is allowed, a sloped +/// mode is only kept if its cascaded sample size is no larger than Delta's on the same sample. +/// Otherwise `SCALE` is used if it independently saves at least [`MIN_BITS_SAVED_PER_VALUE`] bits +/// per value over per-chunk FoR. +fn choose_mode( + scheme: &AffineScheme, + array: &PrimitiveArray, + compressor: &CascadingCompressor, + compress_ctx: &CompressorContext, + exec_ctx: &mut ExecutionCtx, +) -> VortexResult> { + let plan = pre_estimate(array, exec_ctx)?; + if !plan.scale_worthwhile && plan.best_sloped.is_none() { + return Ok(None); + } + + let sample = sample_chunks(array, exec_ctx)?; + let flat_bits = if plan.scale_worthwhile { + plan.est.scale_bits + } else { + plan.est.for_bits + }; + + if let Some((sloped_opts, sloped_est)) = plan.best_sloped + && sloped_est < flat_bits + { + let sloped_bits = measure_affine_bits( + scheme, + &sample, + sloped_opts, + compressor, + compress_ctx, + exec_ctx, + )?; + let slope_wins = match delta_allowed(compressor, compress_ctx) { + None => true, + Some(delta_id) => { + sloped_bits + <= measure_delta_bits(&sample, compressor, compress_ctx, delta_id, exec_ctx)? + } + }; + if slope_wins { + return Ok(Some(ModeChoice { + options: sloped_opts, + bits: sloped_bits, + for_bits: plan.est.for_bits, + })); + } + } + + if !plan.scale_worthwhile { + return Ok(None); + } + + let scale_bits = measure_affine_bits( + scheme, + &sample, + AffineOptions::SCALE, + compressor, + compress_ctx, + exec_ctx, + )?; + Ok(Some(ModeChoice { + options: AffineOptions::SCALE, + bits: scale_bits, + for_bits: plan.est.for_bits, + })) +} + +/// Select the [`AffineOptions`] to encode with during [`AffineScheme::compress`], matching +/// [`choose_mode`] while avoiding redundant sample cascades whenever Delta arbitration is not +/// needed. +fn choose_mode_for_compress( + scheme: &AffineScheme, + array: &PrimitiveArray, + compressor: &CascadingCompressor, + compress_ctx: &CompressorContext, + exec_ctx: &mut ExecutionCtx, +) -> VortexResult { + let plan = pre_estimate(array, exec_ctx)?; + let flat_bits = if plan.scale_worthwhile { + plan.est.scale_bits + } else { + plan.est.for_bits + }; + + if let Some((sloped_opts, sloped_est)) = plan.best_sloped + && sloped_est < flat_bits + { + let Some(delta_id) = delta_allowed(compressor, compress_ctx) else { + return Ok(sloped_opts); + }; + // Only arbitrate against Delta when both SCALE and a sloped mode are viable; if SCALE is + // not viable, `choose_mode` already confirmed the sloped mode beat Delta. + if !plan.scale_worthwhile { + return Ok(sloped_opts); + } + let sample = sample_chunks(array, exec_ctx)?; + let sloped_bits = measure_affine_bits( + scheme, + &sample, + sloped_opts, + compressor, + compress_ctx, + exec_ctx, + )?; + let delta_bits = measure_delta_bits(&sample, compressor, compress_ctx, delta_id, exec_ctx)?; + if sloped_bits <= delta_bits { + return Ok(sloped_opts); + } + } + + if plan.scale_worthwhile { + Ok(AffineOptions::SCALE) + } else if let Some((sloped_opts, _)) = plan.best_sloped { + Ok(sloped_opts) + } else { + Ok(AffineOptions::SCALE) + } +} + +/// Up to [`SAMPLE_CHUNKS`] evenly spaced chunks, kept aligned to chunk boundaries so that each +/// sampled chunk is fitted exactly as in the full array. +fn sample_chunks(array: &PrimitiveArray, ctx: &mut ExecutionCtx) -> VortexResult { + let num_chunks = array.len().div_ceil(FL_CHUNK_SIZE); + if num_chunks <= SAMPLE_CHUNKS { + return Ok(array.clone()); + } + let array = array.clone().into_array(); + let chunks = (0..SAMPLE_CHUNKS) + .map(|i| { + let chunk = i * num_chunks / SAMPLE_CHUNKS; + let start = chunk * FL_CHUNK_SIZE; + array.slice(start..(start + FL_CHUNK_SIZE).min(array.len())) + }) + .collect::>>()?; + ChunkedArray::try_new(chunks, array.dtype().clone())? + .into_array() + .execute::(ctx) +} + +#[cfg(test)] +mod tests { + use rand::RngExt; + use rand::SeedableRng; + use rand::rngs::StdRng; + use rstest::rstest; + use vortex_array::ArrayRef; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::BoolArray; + use vortex_array::arrays::DecimalArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::RunEnd; + use vortex_array::arrays::runend::RunEndArraySlotsExt; + use vortex_array::assert_arrays_eq; + use vortex_array::dtype::DecimalDType; + use vortex_array::validity::Validity; + use vortex_buffer::BitBuffer; + use vortex_buffer::Buffer; + use vortex_edition::EDITION_DECLARATIONS; + use vortex_edition::EDITION_FAMILIES; + use vortex_edition::EditionSession; + use vortex_edition::EditionSessionExt; + use vortex_edition::declarations::core::CORE_2026_08_3; + use vortex_edition::declarations::unstable::UNSTABLE; + use vortex_error::VortexResult; + use vortex_fastlanes::Affine; + use vortex_fastlanes::AffineArraySlotsExt; + use vortex_sequence::Sequence; + use vortex_session::VortexSession; + + use crate::BtrBlocksCompressorBuilder; + use crate::CompressionSession; + use crate::SESSION; + use crate::SchemeExt; + use crate::schemes::integer::DeltaScheme; + + /// Compress with the default schemes (including Affine) and check the round trip. + fn compress(values: impl IntoArray) -> VortexResult { + let mut ctx = SESSION.create_execution_ctx(); + let compressor = BtrBlocksCompressorBuilder::from_session(&SESSION) + .unrestricted() + .build(); + let input = values.into_array(); + let compressed = compressor.compress(&input, &mut ctx)?; + assert_arrays_eq!(compressed, input, &mut ctx); + Ok(compressed) + } + + /// The first Affine array anywhere in the compressed tree. + fn find_affine(compressed: &ArrayRef) -> Option { + compressed + .depth_first_traversal() + .find(|array| array.is::()) + } + + /// Prices on a 0.05 tick around a level, in cents, so every value is a multiple of 5 and has + /// no trend for Delta to exploit. + fn nickel_cents() -> impl Iterator { + let mut rng = StdRng::seed_from_u64(11); + (0..20_000).map(move |_| 10_000 + 5 * rng.random_range(0..1000i64)) + } + + /// Decimals narrow to integers in the decimal scheme, which then cascade into Affine. + #[test] + fn divisor_under_decimal() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let decimals = DecimalArray::new( + nickel_cents().collect::>(), + DecimalDType::new(12, 2), + Validity::NonNullable, + &mut ctx, + ); + let compressed = compress(decimals)?; + let affine = find_affine(&compressed).unwrap_or_else(|| { + panic!( + "Affine should encode the decimal's integers: {}", + compressed.display_tree() + ) + }); + let affine = affine.as_::(); + assert!(!is_unit(affine.scales(), 1)); + Ok(()) + } + + /// ALP turns floats on a decimal grid into integers, which then cascade into Affine. + #[test] + fn divisor_under_alp() -> VortexResult<()> { + let floats = PrimitiveArray::from_iter(nickel_cents().map(|cents| cents as f64 / 100.0)); + let compressed = compress(floats)?; + let affine = find_affine(&compressed).unwrap_or_else(|| { + panic!( + "Affine should encode ALP's integers: {}", + compressed.display_tree() + ) + }); + let affine = affine.as_::(); + assert!(!is_unit(affine.scales(), 1)); + Ok(()) + } + + fn is_unit(param: &ArrayRef, unit: i64) -> bool { + param + .as_constant() + .and_then(|s| s.as_primitive().as_::()) + .is_some_and(|v| v == unit) + } + + /// Prices on a 0.01 tick in units of 1e-8, which only a common divisor narrows. + fn tick_prices() -> PrimitiveArray { + let mut rng = StdRng::seed_from_u64(7); + let mut price = 6_776_562i64; + PrimitiveArray::from_iter((0..20_000).map(|_| { + price += rng.random_range(-40..=40); + price * 1_000_000 + })) + } + + /// Nanosecond timestamps on a one-minute grid with gaps, which a slope and a divisor fit. + fn gappy_grid() -> PrimitiveArray { + PrimitiveArray::from_iter( + (0..30_000i64) + .filter(|i| i % 97 != 5) + .map(|i| 1_700_000_000_000_000_000 + i * 60_000_000_000), + ) + } + + #[test] + fn divisor_on_tick_prices() -> VortexResult<()> { + let compressed = compress(tick_prices())?; + let affine = compressed + .as_opt::() + .expect("Affine should win on tick prices"); + assert!(!is_unit(affine.scales(), 1)); + assert!(is_unit(affine.slopes(), 0)); + Ok(()) + } + + #[test] + fn slope_and_divisor_on_gappy_grid() -> VortexResult<()> { + let compressed = compress(gappy_grid())?; + let affine = compressed + .as_opt::() + .expect("Affine should win on a gappy grid"); + assert!(!is_unit(affine.slopes(), 0)); + assert!(compressed.nbytes() * 8 < 30_000); + Ok(()) + } + + /// Random values and heavy-tailed sorted keys have no divisor or trend to exploit, and the + /// latter suit Delta better than a slope. + #[rstest] + #[case::random(PrimitiveArray::from_iter( + (0..20_000u64).map(|i| i.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 20) + ))] + #[case::heavy_tailed_keys({ + let mut rng = StdRng::seed_from_u64(3); + let mut key = 0u64; + PrimitiveArray::from_iter((0..20_000).map(|_| { + key += if rng.random_ratio(1, 50) { rng.random_range(1..400_000) } else { rng.random_range(1..60) }; + key + })) + })] + fn not_chosen(#[case] values: PrimitiveArray) -> VortexResult<()> { + let compressed = compress(values)?; + assert!( + compressed.as_opt::().is_none(), + "{}", + compressed.display_tree() + ); + Ok(()) + } + + /// Affine must never wrap `RunEnd.ends`, even with Delta disabled, so binary-search + /// `scalar_at` on run-end encoded columns stays fast. + #[test] + fn excluded_on_runend_ends() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let mut rng = StdRng::seed_from_u64(19); + let mut values = Vec::with_capacity(40_000); + for run in 0..2_500i32 { + let run_len = rng.random_range(12..=20); + values.extend(std::iter::repeat_n(run * 7, run_len)); + } + let input = PrimitiveArray::from_iter(values).into_array(); + let compressor = BtrBlocksCompressorBuilder::from_session(&SESSION) + .unrestricted() + .exclude_schemes([DeltaScheme::default().id()]) + .build(); + let compressed = compressor.compress(&input, &mut ctx)?; + assert_arrays_eq!(compressed, input, &mut ctx); + let runend = compressed + .as_opt::() + .expect("repeated runs should compress with RunEnd"); + assert!( + find_affine(runend.ends()).is_none(), + "Affine must not encode RunEnd.ends: {}", + runend.ends().display_tree() + ); + Ok(()) + } + + /// Affine must also stay off `BoolRunEnd.ends` (`child 0`) and never wrap a pure `Sequence`. + #[test] + fn excluded_on_bool_runend_ends_and_pure_sequence() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let mut rng = StdRng::seed_from_u64(23); + let mut bits = Vec::with_capacity(400_000); + let mut current = false; + for _ in 0..2_500 { + let run_len = rng.random_range(120..=200); + bits.extend(std::iter::repeat_n(current, run_len)); + current = !current; + } + let bool_input = BoolArray::from(BitBuffer::from_iter(bits)).into_array(); + let compressor = BtrBlocksCompressorBuilder::from_session(&SESSION) + .unrestricted() + .exclude_schemes([DeltaScheme::default().id()]) + .build(); + let compressed_bool = compressor.compress(&bool_input, &mut ctx)?; + assert_arrays_eq!(compressed_bool, bool_input, &mut ctx); + let runend = compressed_bool + .as_opt::() + .expect("long bool runs should compress with RunEnd"); + assert!( + find_affine(runend.ends()).is_none(), + "Affine must not encode BoolRunEnd.ends: {}", + runend.ends().display_tree() + ); + + let seq_input = PrimitiveArray::from_iter(1..=10_000i64).into_array(); + let compressed_seq = compressor.compress(&seq_input, &mut ctx)?; + assert_arrays_eq!(compressed_seq, seq_input, &mut ctx); + assert!( + compressed_seq.is::(), + "pure sequence should stay Sequence, got {}", + compressed_seq.display_tree() + ); + Ok(()) + } + + fn session_with_editions(enable_unstable: bool) -> VortexSession { + let session = VortexSession::empty() + .with::() + .with::(); + for family in EDITION_FAMILIES { + session + .editions() + .declare_family(family) + .expect("first-party edition family"); + } + for declaration in EDITION_DECLARATIONS { + session + .register_edition(declaration) + .expect("first-party edition"); + } + session + .enable_edition(CORE_2026_08_3) + .expect("core edition is registered"); + if enable_unstable { + session + .enable_edition(UNSTABLE) + .expect("unstable edition is registered"); + } + vortex_fastlanes::initialize(&session); + session + } + + /// `CORE` excludes `fastlanes.affine`, `UNSTABLE` enables it by default, and CUDA mode + /// excludes it even when `UNSTABLE` is enabled. + #[test] + fn edition_gating_and_cuda_exclusion() -> VortexResult<()> { + let input = tick_prices().into_array(); + + let core_session = session_with_editions(false); + let mut core_ctx = core_session.create_execution_ctx(); + let core_compressed = BtrBlocksCompressorBuilder::from_session(&core_session) + .build() + .compress(&input, &mut core_ctx)?; + assert_arrays_eq!(core_compressed, input, &mut core_ctx); + assert!( + find_affine(&core_compressed).is_none(), + "CORE edition must not emit fastlanes.affine: {}", + core_compressed.display_tree() + ); + + let unstable_session = session_with_editions(true); + let mut unstable_ctx = unstable_session.create_execution_ctx(); + let unstable_compressed = BtrBlocksCompressorBuilder::from_session(&unstable_session) + .build() + .compress(&input, &mut unstable_ctx)?; + assert_arrays_eq!(unstable_compressed, input, &mut unstable_ctx); + assert!( + unstable_compressed.is::(), + "UNSTABLE edition should emit fastlanes.affine by default: {}", + unstable_compressed.display_tree() + ); + + let cuda_compressed = BtrBlocksCompressorBuilder::from_session(&unstable_session) + .only_cuda_compatible() + .build() + .compress(&input, &mut unstable_ctx)?; + assert_arrays_eq!(cuda_compressed, input, &mut unstable_ctx); + assert!( + find_affine(&cuda_compressed).is_none(), + "CUDA mode must exclude AffineScheme even under UNSTABLE: {}", + cuda_compressed.display_tree() + ); + Ok(()) + } +} diff --git a/vortex-btrblocks/src/schemes/integer/mod.rs b/vortex-btrblocks/src/schemes/integer/mod.rs index 4216bc6e2f4..dff32b7f651 100644 --- a/vortex-btrblocks/src/schemes/integer/mod.rs +++ b/vortex-btrblocks/src/schemes/integer/mod.rs @@ -3,6 +3,7 @@ //! Integer compression schemes. +mod affine; mod bitpacking; mod delta; mod for_; @@ -15,6 +16,7 @@ mod zigzag; #[cfg(feature = "pco")] mod pco; +pub use affine::AffineScheme; pub use bitpacking::BitPackingScheme; pub use delta::DeltaScheme; #[cfg(test)] diff --git a/vortex-btrblocks/src/session.rs b/vortex-btrblocks/src/session.rs index d3bd3780b3f..649d562e952 100644 --- a/vortex-btrblocks/src/session.rs +++ b/vortex-btrblocks/src/session.rs @@ -64,6 +64,8 @@ impl Default for CompressionSession { &integer::SequenceScheme, &integer::IntRLEScheme, &DELTA_SCHEME, + // Affine requires `fastlanes.affine` (`UNSTABLE`); excluded in CUDA mode. + &integer::AffineScheme, #[cfg(feature = "pco")] &integer::PcoScheme, //////////////////////////////////////////////////////////////////////////////////// diff --git a/vortex-btrblocks/src/tests.rs b/vortex-btrblocks/src/tests.rs index 504b7a14d0d..927796c47e0 100644 --- a/vortex-btrblocks/src/tests.rs +++ b/vortex-btrblocks/src/tests.rs @@ -60,8 +60,10 @@ use vortex_sparse::Sparse; use crate::BtrBlocksCompressor; use crate::BtrBlocksCompressorBuilder; use crate::SESSION; +use crate::SchemeExt; use crate::schemes::binary::VarBinScheme; use crate::schemes::boolean::BoolRunEndScheme; +use crate::schemes::integer::AffineScheme; use crate::schemes::integer::BitPackingScheme; #[track_caller] @@ -272,8 +274,10 @@ fn test_extreme_timestamps_roundtrip(#[case] unit: TimeUnit) -> VortexResult<()> )] fn test_delta_unaligned_roundtrip(#[case] input: PrimitiveArray) -> VortexResult<()> { // Zero-padding the final chunk used to inflate the delta span and reject this scheme. + // Exclude Affine so the linear ramp case exercises Delta specifically. let compressor = BtrBlocksCompressorBuilder::from_session(&SESSION) .unrestricted() + .exclude_schemes([AffineScheme.id()]) .build(); let input = input.into_array(); let compressed = assert_roundtrip(&compressor, &input)?; @@ -306,8 +310,10 @@ fn test_delta_chosen_for_restarting_series() -> VortexResult<()> { })) .into_array(); + // Exclude Affine so this 30,000-step grid exercises Delta's outlier-patched estimator. let compressor = BtrBlocksCompressorBuilder::from_session(&SESSION) .unrestricted() + .exclude_schemes([AffineScheme.id()]) .build(); let compressed = assert_roundtrip(&compressor, &input)?; assert!(compressed.is::()); diff --git a/vortex-btrblocks/tests/for_config.rs b/vortex-btrblocks/tests/for_config.rs index f7a71db3dce..4b302bc7fbf 100644 --- a/vortex-btrblocks/tests/for_config.rs +++ b/vortex-btrblocks/tests/for_config.rs @@ -99,7 +99,7 @@ static UNSTABLE_SESSION: LazyLock = LazyLock::new(|| { /// plain BitPacking 30, so FoR is estimated to pay off, and per-chunk references then pack to 7. fn drifting() -> ArrayRef { PrimitiveArray::from_iter( - (0..8192u32).map(|i| 1_000_000_000 + (i / 1024) * 1_000_000 + i % 100), + (0..8192u32).map(|i| 1_000_000_000 + (i / 1024) * 1_000_000 + i.wrapping_mul(37) % 100), ) .into_array() } diff --git a/vortex-compressor/src/compressor/mod.rs b/vortex-compressor/src/compressor/mod.rs index 19199d77365..0afd91aa9fd 100644 --- a/vortex-compressor/src/compressor/mod.rs +++ b/vortex-compressor/src/compressor/mod.rs @@ -71,6 +71,14 @@ impl CascadingCompressor { root_exclusions, } } + + /// Whether the compressor has the scheme with this ID enabled. + /// + /// A scheme can use this to compare itself against an alternative only when the compressor + /// could actually pick that alternative. + pub fn has_scheme(&self, id: SchemeId) -> bool { + self.schemes.iter().any(|s| s.id() == id) + } } // NB: Cascading compression logic is located in `vortex-compressor/src/compressor/cascade.rs`. diff --git a/vortex-edition/src/declarations/unstable/mod.rs b/vortex-edition/src/declarations/unstable/mod.rs index 5916f4c164c..bc313931840 100644 --- a/vortex-edition/src/declarations/unstable/mod.rs +++ b/vortex-edition/src/declarations/unstable/mod.rs @@ -31,5 +31,8 @@ pub static DECLARATION: EditionDeclaration = EditionDeclaration { immutable: false, min_library_version: None, }, - added: &[EditionMember::array(&"fastlanes.for.v2")], + added: &[ + EditionMember::array(&"fastlanes.affine"), + EditionMember::array(&"fastlanes.for.v2"), + ], }; diff --git a/vortex-file/src/open.rs b/vortex-file/src/open.rs index 7c32851674a..12a9425a2bd 100644 --- a/vortex-file/src/open.rs +++ b/vortex-file/src/open.rs @@ -866,8 +866,13 @@ mod tests { let session = test_session(); let mut file_bytes = ByteBufferMut::empty(); - let values = (0i32..65_536) - .map(|value| value.wrapping_mul(1_664_525).wrapping_add(1_013_904_223)) + let values = (0u32..65_536) + .map(|value| { + let mut x = value.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + x ^= x >> 16; + x = x.wrapping_mul(0x85EB_CA6B); + (x ^ (x >> 13)) as i32 + }) .collect::>(); let array = Buffer::from(values).into_array(); session diff --git a/vortex-file/src/strategy.rs b/vortex-file/src/strategy.rs index b35cf6e118b..ac8c5fb2c2d 100644 --- a/vortex-file/src/strategy.rs +++ b/vortex-file/src/strategy.rs @@ -9,6 +9,7 @@ use std::sync::Arc; use vortex_array::dtype::FieldPath; use vortex_btrblocks::BtrBlocksCompressorBuilder; use vortex_btrblocks::SchemeExt; +use vortex_btrblocks::schemes::integer::AffineScheme; use vortex_btrblocks::schemes::integer::IntDictScheme; use vortex_edition::ComponentKind; use vortex_edition::EditionSessionExt; @@ -59,18 +60,18 @@ struct Compressors { impl CompressorConfig { /// Splits the configured compressor into the codes and full compressors. /// - /// The codes compressor excludes `IntDictScheme` because `DictStrategy` already - /// dictionary-encoded the column, and dictionary-encoding its integer codes again would be - /// redundant. The full compressor keeps every scheme, so chunks that `DictStrategy` rejects can - /// still use integer dictionaries, e.g. for a decimal's most significant part. An opaque - /// compressor is used as-is for both. + /// The codes compressor excludes `IntDictScheme` (preventing recursive dictionary encoding) + /// and `AffineScheme` (matching `AffineScheme::ancestor_exclusions` on dictionary codes so + /// layout codes compress consistently with the dictionary probe). The full compressor keeps + /// every scheme, so chunks that `DictStrategy` rejects can still use integer dictionaries, + /// e.g. for a decimal's most significant part. An opaque compressor is used as-is for both. fn into_compressors(self) -> Compressors { match self { CompressorConfig::BtrBlocks(builder) => Compressors { codes: Arc::new( builder .clone() - .exclude_schemes([IntDictScheme.id()]) + .exclude_schemes([IntDictScheme.id(), AffineScheme.id()]) .build(), ), full: Arc::new(builder.build()), diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests.rs index 9aae6a3a6d5..ab0fa0adf5b 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -184,13 +184,13 @@ async fn test_eof_values() { #[rstest] #[case::default( BtrBlocksCompressorBuilder::from_session(&SESSION), - if cfg!(feature = "zstd") { 68_932 } else { 68_868 } + if cfg!(feature = "zstd") { 53_212 } else { 53_148 } )] #[cfg_attr( feature = "zstd", case::compact( BtrBlocksCompressorBuilder::from_session(&SESSION).with_compact(), - 55_088 + 52_960 ) )] #[tokio::test] @@ -2025,11 +2025,12 @@ async fn test_into_tokio_array_stream() -> VortexResult<()> { #[tokio::test] async fn test_array_stream_no_double_dict_encode() -> VortexResult<()> { let num_vals = 2048; - // Alternating and far apart, so neither runs nor bit widths pack them tighter than a - // dictionary. - let array = - PrimitiveArray::from_iter((0..num_vals).map(|i| [1_000_000_000i64, 2_000_000_000][i % 2])) - .into_array(); + // Alternating, far apart, and coprime, so neither runs, bit widths, nor affine scaling pack + // them tighter than a dictionary. + let array = PrimitiveArray::from_iter( + (0..num_vals).map(|i| [1_000_000_000i64, 1_000_000_001, 2_000_000_003][i % 3]), + ) + .into_array(); let mut buf = Vec::new(); SESSION .write_options() diff --git a/vortex/editions/unstable/unstable2026.10.0.toml b/vortex/editions/unstable/unstable2026.10.0.toml index d051325f2ad..769c2e472df 100644 --- a/vortex/editions/unstable/unstable2026.10.0.toml +++ b/vortex/editions/unstable/unstable2026.10.0.toml @@ -13,6 +13,7 @@ immutable = false # Components added by this edition. [added] arrays = [ + "fastlanes.affine", "fastlanes.for.v2", ] layouts = [] @@ -23,6 +24,7 @@ aggregates = [] # editions of the family. [components] arrays = [ + "fastlanes.affine", "fastlanes.for.v2", ] layouts = []