diff --git a/encodings/pivco-bytes/src/lib.rs b/encodings/pivco-bytes/src/lib.rs index 0b39629953e..c11ead35b0d 100644 --- a/encodings/pivco-bytes/src/lib.rs +++ b/encodings/pivco-bytes/src/lib.rs @@ -28,7 +28,12 @@ //! sparse filters and takes decode only the blocks their rows span, `==` and `!=` against a //! constant decode only the rows of its length, and byte length reads the offsets alone. //! -//! Both encodings are members of the `unstable` edition: their wire formats may change. Register +//! [`PivcoTokens`] codes `u16` columns with more than 256 distinct values, such as substring +//! dictionary token codes: the high bytes are one [`PivcoBytesArray`] child, and the low bytes are +//! grouped by their high byte into one [`PivcoBytesArray`] child each, so that every group gets a +//! tree of its own. +//! +//! All three encodings are members of the `unstable` edition: their wire formats may change. Register //! them with [`initialize`]: //! //! ```rust @@ -49,6 +54,7 @@ mod array; mod compute; mod plugin; mod string; +mod tokens; pub use array::DEFAULT_BLOCK_SIZE; pub use array::PivcoBytes; @@ -69,6 +75,14 @@ pub use string::PivcoStringData; pub use string::PivcoStringMetadata; pub use string::PivcoStringSlots; pub use string::pivco_string_id; +pub use tokens::MIN_CODED_GROUP_LEN; +pub use tokens::PivcoTokens; +pub use tokens::PivcoTokensArray; +pub use tokens::PivcoTokensArrayExt; +pub use tokens::PivcoTokensData; +pub use tokens::PivcoTokensMetadata; +pub use tokens::PivcoTokensParts; +pub use tokens::pivco_tokens_id; use vortex_array::ArrayVTable; use vortex_array::arrays::Dict; use vortex_array::arrays::Filter; @@ -87,7 +101,7 @@ use vortex_functions::byte_length::ByteLength; use vortex_functions::byte_length::ByteLengthExecuteAdaptor; use vortex_session::VortexSession; -/// Registers the `vortex.pivco_bytes` and `vortex.pivco_string` encodings, their slice and cast +/// Registers the `vortex.pivco_bytes`, `vortex.pivco_string` and `vortex.pivco_tokens` encodings, their slice and cast /// rules and their filter, take, compare and byte length kernels with the session. pub fn initialize(session: &VortexSession) { session.register_array(PivcoBytes, PivcoBytes); @@ -136,6 +150,8 @@ pub fn initialize(session: &VortexSession) { PivcoString, ByteLengthExecuteAdaptor(PivcoString), ); + + session.register_array(PivcoTokens, PivcoTokens); } #[cfg(test)] diff --git a/encodings/pivco-bytes/src/tokens/mod.rs b/encodings/pivco-bytes/src/tokens/mod.rs new file mode 100644 index 00000000000..abff46262c0 --- /dev/null +++ b/encodings/pivco-bytes/src/tokens/mod.rs @@ -0,0 +1,466 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! [`PivcoTokens`]: `u16` arrays coded as a high byte and a low byte conditioned on it. +//! +//! A `u16` column with a large alphabet, such as the token codes of a substring dictionary, has +//! more distinct values than the 256-symbol PIVCO byte codec can code directly. [`PivcoTokens`] +//! splits every value into its high and low byte, codes the high bytes as one [`PivcoBytes`] +//! child, and groups the low bytes by their high byte, coding each group as a [`PivcoBytes`] child +//! with a tree of its own. Since `H(value) = H(high) + H(low | high)`, the result approaches the +//! order-0 entropy of the values, which coding the two bytes independently does not. + +use std::fmt::Display; +use std::fmt::Formatter; +use std::hash::Hash; +use std::hash::Hasher; +use std::sync::Arc; + +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::Primitive; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::buffer::BufferHandle; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::scalar::Scalar; +use vortex_array::validity::Validity; +use vortex_array::vtable::OperationsVTable; +use vortex_array::vtable::VTable; +use vortex_array::vtable::ValidityVTable; +use vortex_array::vtable::child_to_validity; +use vortex_array::vtable::validity_to_child; +use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; +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_error::vortex_panic; +use vortex_session::registry::CachedId; + +use crate::ByteOptions; +use crate::PivcoBytes; + +mod plugin; +#[cfg(test)] +mod tests; + +/// The serialized and in-memory [`ArrayId`] of [`PivcoTokens`] (`"vortex.pivco_tokens"`). +pub fn pivco_tokens_id() -> ArrayId { + static ID: CachedId = CachedId::new("vortex.pivco_tokens"); + *ID +} + +/// Index of the high-byte slot. +const HI_SLOT: usize = 0; +/// Index of the optional validity slot. +const VALIDITY_SLOT: usize = 1; +/// Index of the first low-byte group slot. +const GROUPS_OFFSET: usize = 2; + +/// Groups shorter than this keep their low bytes uncompressed, since a tree would cost more than +/// it saves. +pub const MIN_CODED_GROUP_LEN: usize = 64; + +/// Serialized protobuf metadata for a [`PivcoTokensArray`]. +/// +/// Children are, in order, the `u8` high bytes, the validity when `has_validity` is set, and one +/// `u8` child of low bytes for each high byte in `group_his`. +#[derive(Clone, PartialEq, Eq, prost::Message)] +pub struct PivcoTokensMetadata { + /// Whether a validity child follows the high bytes. + #[prost(bool, tag = "1")] + pub has_validity: bool, + /// The high byte of each low-byte group, strictly increasing. + #[prost(bytes = "vec", tag = "2")] + pub group_his: Vec, + /// The length of each low-byte group. + #[prost(uint64, repeated, tag = "3")] + pub group_lens: Vec, +} + +/// A [`PivcoTokens`]-encoded Vortex array. +pub type PivcoTokensArray = Array; + +/// Marker struct for the `vortex.pivco_tokens` encoding. +#[derive(Clone, Debug)] +pub struct PivcoTokens; + +/// The high byte of each low-byte group; everything else is in the children. +#[derive(Clone, Debug, Default)] +pub struct PivcoTokensData { + group_his: Arc<[u8]>, +} + +impl PivcoTokensData { + /// The high byte of each low-byte group, strictly increasing. + pub fn group_his(&self) -> &[u8] { + &self.group_his + } +} + +impl Display for PivcoTokensData { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "groups: {}", self.group_his.len()) + } +} + +impl ArrayHash for PivcoTokensData { + fn array_hash(&self, state: &mut H, _accuracy: EqMode) { + self.group_his.hash(state); + } +} + +impl ArrayEq for PivcoTokensData { + fn array_eq(&self, other: &Self, _accuracy: EqMode) -> bool { + self.group_his == other.group_his + } +} + +/// Typed accessors for [`PivcoTokensArray`] and `ArrayView<'_, PivcoTokens>`. +pub trait PivcoTokensArrayExt { + /// The `u8` high bytes. + fn hi(&self) -> &ArrayRef; + /// The validity child, if any. + fn validity_child(&self) -> Option<&ArrayRef>; + /// The `u8` low-byte groups, one per entry of [`PivcoTokensData::group_his`]. + fn groups(&self) -> impl Iterator; +} + +impl PivcoTokensArrayExt for ArrayView<'_, PivcoTokens> { + fn hi(&self) -> &ArrayRef { + self.slots()[HI_SLOT] + .as_ref() + .unwrap_or_else(|| vortex_panic!("PivcoTokensArray hi slot is empty")) + } + + fn validity_child(&self) -> Option<&ArrayRef> { + self.slots()[VALIDITY_SLOT].as_ref() + } + + fn groups(&self) -> impl Iterator { + self.slots()[GROUPS_OFFSET..].iter().map(|slot| { + slot.as_ref() + .unwrap_or_else(|| vortex_panic!("PivcoTokensArray group slot is empty")) + }) + } +} + +impl PivcoTokens { + /// Constructs a validated [`PivcoTokensArray`] from its children. + pub fn try_new( + nullability: Nullability, + hi: ArrayRef, + validity: Validity, + group_his: Vec, + groups: Vec, + ) -> VortexResult { + let len = hi.len(); + let mut slots = Vec::with_capacity(GROUPS_OFFSET + groups.len()); + slots.push(Some(hi)); + slots.push(validity_to_child(&validity, len)); + slots.extend(groups.into_iter().map(Some)); + Array::try_from_parts(ArrayParts::new( + PivcoTokens, + DType::Primitive(PType::U16, nullability), + len, + PivcoTokensData { + group_his: group_his.into(), + }, + slots.into(), + )) + } + + /// Splits a `u16` array into its high bytes and its low bytes grouped by high byte, returning + /// the high bytes, the array's validity, the high byte of each group, and the groups. Null + /// values are split as zero. + pub fn split( + array: ArrayView<'_, Primitive>, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let dtype = array.dtype(); + vortex_ensure!( + matches!(dtype, DType::Primitive(PType::U16, _)), + "PivcoTokens can only encode u16 arrays, got {dtype}" + ); + let validity = array.validity()?; + let mask = validity.execute_mask(array.len(), ctx)?; + let values = array.as_slice::(); + + let mut his = BufferMut::::with_capacity(values.len()); + let mut groups: Vec> = (0..256).map(|_| BufferMut::empty()).collect(); + for (i, &value) in values.iter().enumerate() { + let value = if mask.value(i) { value } else { 0 }; + let [lo, hi] = value.to_le_bytes(); + his.push(hi); + groups[usize::from(hi)].push(lo); + } + let mut group_his = Vec::new(); + let mut los = Vec::new(); + for (hi, group) in groups.into_iter().enumerate() { + if !group.is_empty() { + group_his.push(u8::try_from(hi)?); + los.push(PrimitiveArray::new(group.freeze(), Validity::NonNullable)); + } + } + Ok(PivcoTokensParts { + nullability: dtype.nullability(), + hi: PrimitiveArray::new(his.freeze(), Validity::NonNullable), + validity, + group_his, + groups: los, + }) + } + + /// Encodes a `u16` array, coding its high bytes and each group of low bytes with + /// [`PivcoBytes`]. Null values are coded as zero. + pub fn encode( + array: ArrayView<'_, Primitive>, + opts: ByteOptions, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let parts = Self::split(array, ctx)?; + let hi = PivcoBytes::encode_with_options(parts.hi.as_view(), opts, ctx)?.into_array(); + let groups = parts + .groups + .into_iter() + .map(|group| { + Ok(if group.len() < MIN_CODED_GROUP_LEN { + group.into_array() + } else { + PivcoBytes::encode_with_options(group.as_view(), opts, ctx)?.into_array() + }) + }) + .collect::>>()?; + Self::try_new( + parts.nullability, + hi, + parts.validity, + parts.group_his, + groups, + ) + } +} + +/// A `u16` array split by [`PivcoTokens::split`], before its children are coded. +#[derive(Debug)] +pub struct PivcoTokensParts { + /// The nullability of the array. + pub nullability: Nullability, + /// The high byte of every value. + pub hi: PrimitiveArray, + /// The validity of the array. + pub validity: Validity, + /// The high byte of each group, strictly increasing. + pub group_his: Vec, + /// The low bytes of the values with each high byte, in order. + pub groups: Vec, +} + +impl VTable for PivcoTokens { + type TypedArrayData = PivcoTokensData; + type OperationsVTable = Self; + type ValidityVTable = Self; + + fn id(&self) -> ArrayId { + pivco_tokens_id() + } + + fn validate( + &self, + data: &Self::TypedArrayData, + dtype: &DType, + len: usize, + slots: &[Option], + ) -> VortexResult<()> { + vortex_ensure!( + matches!(dtype, DType::Primitive(PType::U16, _)), + "PivcoTokensArray requires a u16 dtype, got {dtype}" + ); + vortex_ensure_eq!( + slots.len(), + GROUPS_OFFSET + data.group_his.len(), + "PivcoTokensArray slot count" + ); + vortex_ensure!( + data.group_his.is_sorted_by(|a, b| a < b), + "PivcoTokensArray group high bytes must be strictly increasing" + ); + let u8_dtype = DType::Primitive(PType::U8, Nullability::NonNullable); + let hi = slots[HI_SLOT] + .as_ref() + .ok_or_else(|| vortex_err!("PivcoTokensArray is missing its hi child"))?; + vortex_ensure_eq!( + hi.dtype(), + &u8_dtype, + "PivcoTokensArray hi must be non-nullable u8" + ); + vortex_ensure_eq!(hi.len(), len, "PivcoTokensArray hi length"); + let mut total = 0usize; + for slot in &slots[GROUPS_OFFSET..] { + let group = slot + .as_ref() + .ok_or_else(|| vortex_err!("PivcoTokensArray is missing a group child"))?; + vortex_ensure_eq!( + group.dtype(), + &u8_dtype, + "PivcoTokensArray groups must be non-nullable u8" + ); + total += group.len(); + } + vortex_ensure_eq!(total, len, "PivcoTokensArray group lengths must sum to len"); + let validity = child_to_validity(slots[VALIDITY_SLOT].as_ref(), dtype.nullability()); + if let Some(validity_len) = validity.maybe_len() { + vortex_ensure_eq!(validity_len, len, "PivcoTokensArray validity length"); + } + Ok(()) + } + + fn nbuffers(_array: ArrayView<'_, Self>) -> usize { + 0 + } + + fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle { + vortex_panic!("PivcoTokensArray 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_ensure!(buffers.is_empty(), "PivcoTokensArray has no buffers"); + Ok(ArrayParts::new( + self.clone(), + array.dtype().clone(), + array.len(), + array.data().clone(), + array.slots().iter().cloned().collect(), + )) + } + + fn slot_name(array: ArrayView<'_, Self>, idx: usize) -> String { + match idx { + HI_SLOT => "hi".to_string(), + VALIDITY_SLOT => "validity".to_string(), + _ => format!("lo[{}]", array.data().group_his[idx - GROUPS_OFFSET]), + } + } + + fn execute(array: Array, ctx: &mut ExecutionCtx) -> VortexResult { + let view = array.as_view(); + let his = view.hi().clone().execute::(ctx)?; + let his = his.as_slice::(); + + // `cursors[hi]` walks the low bytes of the group with that high byte. + let mut groups: Vec>> = vec![None; 256]; + for (&hi, group) in view.data().group_his.iter().zip(view.groups()) { + groups[usize::from(hi)] = Some( + group + .clone() + .execute::(ctx)? + .into_buffer::(), + ); + } + let mut cursors = [0usize; 256]; + let mut values = BufferMut::::with_capacity(his.len()); + for &hi in his { + let h = usize::from(hi); + let lo = groups[h] + .as_ref() + .and_then(|group| group.get(cursors[h])) + .ok_or_else(|| { + vortex_err!("PivcoTokensArray group {hi} has fewer values than its high bytes") + })?; + cursors[h] += 1; + values.push(u16::from_le_bytes([*lo, hi])); + } + Ok(ExecutionResult::done( + PrimitiveArray::new(values.freeze(), view.pivco_tokens_validity()).into_array(), + )) + } +} + +/// The array's [`Validity`], read from its validity slot. +trait PivcoTokensValidity { + fn pivco_tokens_validity(&self) -> Validity; +} + +impl PivcoTokensValidity for ArrayView<'_, PivcoTokens> { + fn pivco_tokens_validity(&self) -> Validity { + child_to_validity(self.validity_child(), self.dtype().nullability()) + } +} + +impl ValidityVTable for PivcoTokens { + fn validity(array: ArrayView<'_, PivcoTokens>) -> VortexResult { + Ok(array.pivco_tokens_validity()) + } +} + +impl OperationsVTable for PivcoTokens { + type ProbeState = (); + + /// Reads the high byte, counts its earlier occurrences, and reads that entry of its group. + fn scalar_at( + array: ArrayView<'_, PivcoTokens>, + index: usize, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + if index >= array.len() { + vortex_bail!( + "PivcoTokensArray index {index} out of bounds for len {}", + array.len() + ); + } + let nullability = array.dtype().nullability(); + if !array.array().is_valid(index, ctx)? { + return Ok(Scalar::null(array.dtype().clone())); + } + let hi = array + .hi() + .execute_scalar(index, ctx)? + .as_primitive() + .as_opt::() + .flatten() + .ok_or_else(|| vortex_err!("PivcoTokensArray hi[{index}] is null"))?; + let earlier = array.hi().slice(0..index)?.execute::(ctx)?; + let rank = earlier + .as_slice::() + .iter() + .filter(|&&h| h == hi) + .count(); + let group_idx = array + .data() + .group_his + .binary_search(&hi) + .map_err(|_| vortex_err!("PivcoTokensArray has no group for high byte {hi}"))?; + let group = array + .groups() + .nth(group_idx) + .ok_or_else(|| vortex_err!("PivcoTokensArray group {group_idx} is missing"))?; + let lo = group + .execute_scalar(rank, ctx)? + .as_primitive() + .as_opt::() + .flatten() + .ok_or_else(|| vortex_err!("PivcoTokensArray group {hi}[{rank}] is null"))?; + Ok(Scalar::primitive(u16::from_le_bytes([lo, hi]), nullability)) + } +} diff --git a/encodings/pivco-bytes/src/tokens/plugin.rs b/encodings/pivco-bytes/src/tokens/plugin.rs new file mode 100644 index 00000000000..7d40620e641 --- /dev/null +++ b/encodings/pivco-bytes/src/tokens/plugin.rs @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! [`ArrayPlugin`] implementation for [`PivcoTokens`]. + +use prost::Message; +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::Nullability; +use vortex_array::dtype::PType; +use vortex_array::validity::Validity; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_err; +use vortex_session::VortexSession; + +use super::PivcoTokens; +use super::PivcoTokensArrayExt; +use super::PivcoTokensMetadata; +use super::pivco_tokens_id; + +impl ArrayPlugin for PivcoTokens { + fn id(&self) -> ArrayId { + VTable::id(self) + } + + fn serialize( + &self, + array: &ArrayRef, + _session: &VortexSession, + ) -> VortexResult> { + let view = array.as_opt::().ok_or_else(|| { + vortex_err!( + "PivcoTokens plugin cannot serialize {}", + array.encoding_id() + ) + })?; + let metadata = PivcoTokensMetadata { + has_validity: view.validity_child().is_some(), + group_his: view.data().group_his().to_vec(), + group_lens: view.groups().map(|g| g.len() as u64).collect(), + }; + Ok(Some(ArraySerialization::from_array( + pivco_tokens_id(), + view.array(), + metadata.encode_to_vec(), + ))) + } + + fn deserialize( + &self, + parts: ArrayDeserialization<'_>, + _session: &VortexSession, + ) -> VortexResult { + vortex_ensure_eq!( + parts.serialized_id, + pivco_tokens_id(), + "PivcoTokens plugin does not recognize serialized ID {}", + parts.serialized_id + ); + let ArrayDeserialization { + dtype, + len, + metadata, + buffers, + children, + .. + } = parts; + vortex_ensure!( + matches!(dtype, DType::Primitive(PType::U16, _)), + "PivcoTokensArray requires a u16 dtype, got {dtype}" + ); + vortex_ensure!(buffers.is_empty(), "PivcoTokensArray has no buffers"); + let metadata = PivcoTokensMetadata::decode(metadata)?; + vortex_ensure!( + !metadata.has_validity || dtype.is_nullable(), + "Non-nullable PivcoTokensArray cannot have a validity child" + ); + vortex_ensure_eq!( + metadata.group_his.len(), + metadata.group_lens.len(), + "PivcoTokens group_his and group_lens lengths" + ); + let first_group = 1 + usize::from(metadata.has_validity); + let required = first_group + metadata.group_his.len(); + vortex_ensure!( + children.len() >= required, + "PivcoTokensArray expects {required} children, got {}", + children.len() + ); + let u8_dtype = DType::Primitive(PType::U8, Nullability::NonNullable); + let hi = children.get(0, &u8_dtype, len)?; + let validity = if metadata.has_validity { + Validity::Array(children.get(1, &Validity::DTYPE, len)?) + } else { + Validity::from(dtype.nullability()) + }; + let groups = metadata + .group_lens + .iter() + .enumerate() + .map(|(i, &group_len)| { + let group_len = usize::try_from(group_len) + .map_err(|_| vortex_err!("PivcoTokens group length {group_len} overflows"))?; + children.get(first_group + i, &u8_dtype, group_len) + }) + .collect::>>()?; + Ok(PivcoTokens::try_new( + dtype.nullability(), + hi, + validity, + metadata.group_his, + groups, + )? + .into_array()) + } +} diff --git a/encodings/pivco-bytes/src/tokens/tests.rs b/encodings/pivco-bytes/src/tokens/tests.rs new file mode 100644 index 00000000000..d7fa34f9424 --- /dev/null +++ b/encodings/pivco-bytes/src/tokens/tests.rs @@ -0,0 +1,110 @@ +// 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::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::assert_arrays_eq; +use vortex_array::optimizer::ArrayOptimizer; +use vortex_array::serde::SerializeOptions; +use vortex_array::serde::SerializedArray; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_buffer::ByteBufferMut; +use vortex_error::VortexResult; +use vortex_session::VortexSession; +use vortex_session::registry::ReadContext; + +use super::PivcoTokens; +use crate::ByteOptions; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +/// Zipf-like token ids over a 4096-symbol alphabet, as a substring dictionary produces. +fn tokens(len: usize, nullable: bool) -> PrimitiveArray { + let mut rng = StdRng::seed_from_u64(7); + let values: Buffer = (0..len) + .map(|_| { + // The square of a uniform value skews the ids towards zero. + let r: u32 = rng.random_range(0..4096); + u16::try_from(r * r / 4096).unwrap_or(u16::MAX) + }) + .collect(); + let validity = if nullable { + Validity::from_iter((0..len).map(|i| i % 7 != 3)) + } else { + Validity::NonNullable + }; + PrimitiveArray::new(values, validity) +} + +#[rstest] +#[case::non_nullable(false)] +#[case::nullable(true)] +fn round_trips_and_shrinks(#[case] nullable: bool) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let input = tokens(50_000, nullable); + let encoded = PivcoTokens::encode(input.as_view(), ByteOptions::pha(), &mut ctx)?; + assert!( + encoded.nbytes() * 10 < input.nbytes() * 9, + "{} >= 90% of {}", + encoded.nbytes(), + input.nbytes() + ); + assert_arrays_eq!( + encoded.clone().into_array(), + input.clone().into_array(), + &mut ctx + ); + for index in [0, 1, 4_095, 33_333, 49_999] { + assert_eq!( + encoded.as_view().array().execute_scalar(index, &mut ctx)?, + input.as_view().array().execute_scalar(index, &mut ctx)?, + "scalar_at({index})" + ); + } + Ok(()) +} + +#[test] +fn serde_round_trips() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let input = tokens(20_000, true); + let encoded = PivcoTokens::encode(input.as_view(), ByteOptions::pha(), &mut ctx)?.into_array(); + let encoded = encoded.optimize_ctx(&*SESSION)?; + let array_ctx = ArrayContext::empty(); + let buffers = encoded.serialize(&array_ctx, &SESSION, &SerializeOptions::default())?; + let mut concat = ByteBufferMut::empty(); + for buffer in buffers { + concat.extend_from_slice(buffer.as_ref()); + } + let decoded = SerializedArray::try_from(concat.freeze())?.decode( + encoded.dtype(), + encoded.len(), + &ReadContext::new(array_ctx.to_ids()), + &SESSION, + )?; + assert_arrays_eq!(decoded, input.into_array(), &mut ctx); + Ok(()) +} + +#[test] +fn empty_array() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let input = PrimitiveArray::new(Buffer::::empty(), Validity::NonNullable); + let encoded = PivcoTokens::encode(input.as_view(), ByteOptions::pha(), &mut ctx)?; + assert_eq!(encoded.len(), 0); + assert_arrays_eq!(encoded.into_array(), input.into_array(), &mut ctx); + Ok(()) +} diff --git a/vortex-btrblocks/src/builder.rs b/vortex-btrblocks/src/builder.rs index eaa31b5152d..6840847eaaa 100644 --- a/vortex-btrblocks/src/builder.rs +++ b/vortex-btrblocks/src/builder.rs @@ -92,6 +92,7 @@ impl CompressionMode { binary::VarBinScheme.id(), // No CUDA decoder for PIVCO wavelet trees yet. integer::PivcoBytesScheme.id(), + integer::PivcoTokensScheme.id(), string::PivcoStringScheme.id(), ]); // Both binary Zstd schemes are kept. Buffer-level compression preserves binary @@ -674,7 +675,7 @@ mod tests { Ok(()) } - /// `vortex.pivco_bytes` and `vortex.pivco_string` are members of the `unstable` edition only, + /// `vortex.pivco_bytes`, `vortex.pivco_string` and `vortex.pivco_tokens` are members of the `unstable` edition only, /// so their schemes are used only when that edition is enabled, and never by the CUDA preset, /// which cannot decode them. #[rstest] @@ -699,6 +700,7 @@ mod tests { let builder = BtrBlocksCompressorBuilder::from_session(&session); for pivco in [ integer::PivcoBytesScheme.id(), + integer::PivcoTokensScheme.id(), string::PivcoStringScheme.id(), ] { let has = |preset: &BtrBlocksCompressorBuilder| { diff --git a/vortex-btrblocks/src/schemes/integer/mod.rs b/vortex-btrblocks/src/schemes/integer/mod.rs index 095969eda20..5297f8b5e1b 100644 --- a/vortex-btrblocks/src/schemes/integer/mod.rs +++ b/vortex-btrblocks/src/schemes/integer/mod.rs @@ -8,6 +8,7 @@ mod delta; mod elias_fano; mod for_; mod pivco_bytes; +mod pivco_tokens; mod rle; mod runend; mod sequence; @@ -26,6 +27,7 @@ pub use for_::FoRScheme; #[cfg(feature = "pco")] pub use pco::PcoScheme; pub use pivco_bytes::PivcoBytesScheme; +pub use pivco_tokens::PivcoTokensScheme; pub use rle::IntRLEScheme; pub(crate) use rle::rle_encode; pub use runend::RunEndScheme; diff --git a/vortex-btrblocks/src/schemes/integer/pivco_tokens.rs b/vortex-btrblocks/src/schemes/integer/pivco_tokens.rs new file mode 100644 index 00000000000..8210846e266 --- /dev/null +++ b/vortex-btrblocks/src/schemes/integer/pivco_tokens.rs @@ -0,0 +1,270 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! PIVCO-Huffman coding of `u16` columns with large alphabets (`vortex.pivco_tokens`). + +use vortex_array::ArrayId; +use vortex_array::ArrayView; +use vortex_array::Canonical; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::arrays::Primitive; +use vortex_array::dtype::DType; +use vortex_array::dtype::PType; +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_pivco_bytes::ByteOptions; +use vortex_pivco_bytes::MIN_CODED_GROUP_LEN; +use vortex_pivco_bytes::PivcoBytes; +use vortex_pivco_bytes::PivcoTokens; +use vortex_pivco_bytes::pivco_bytes_id; +use vortex_pivco_bytes::pivco_tokens_id; + +use crate::ArrayAndStats; +use crate::Child; +use crate::CompressorContext; +use crate::Encoded; +use crate::Scheme; + +/// Arrays shorter than this stay with the lighter-weight schemes. +const MIN_LEN: usize = 1024; +/// Evenly spaced runs of [`SAMPLE_RUN_LEN`] values the estimate histograms. The groups split the +/// sample 256 ways, so it is larger than the compressor's own samples. +const SAMPLE_RUNS: usize = 4; +const SAMPLE_RUN_LEN: usize = 16_384; +/// PIVCO's Huffman trees and block headers cost a few percent more than the order-0 entropy. +const ENTROPY_OVERHEAD: f64 = 1.04; +/// Estimated bytes of one group's tree and block header, per distinct low byte in the group. +const TREE_BYTES_PER_SYMBOL: usize = 2; +const TREE_BYTES_PER_GROUP: usize = 24; +/// PIVCO decodes slower than bit-packing, so it must save at least this fraction of the bits. +const MIN_SAVING: f64 = 0.05; + +/// PIVCO-Huffman coding of `u16` columns (`vortex.pivco_tokens`). +/// +/// The high byte of every value is coded with one tree, and the low bytes with one tree per high +/// byte, which approaches the order-0 entropy of the values. It is meant for the token codes of +/// substring dictionaries such as OnPair, whose skewed 12- and 16-bit codes bit-pack to their full +/// width. +/// +/// Splitting a small sample 256 ways would leave every group too short to code, so the estimate +/// histograms a larger sample instead and compares its entropy, plus the trees, with +/// bit-packing. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct PivcoTokensScheme; + +impl Scheme for PivcoTokensScheme { + fn scheme_name(&self) -> &'static str { + "vortex.int.pivco_tokens" + } + + fn matches(&self, canonical: &Canonical) -> bool { + matches!(canonical.dtype(), DType::Primitive(PType::U16, _)) + } + + fn produced_encodings(&self) -> Vec { + vec![pivco_tokens_id(), pivco_bytes_id()] + } + + /// Children: short low-byte groups=0, which are compressed further. + fn num_children(&self) -> usize { + 1 + } + + fn expected_compression_ratio( + &self, + data: &ArrayAndStats, + _compress_ctx: CompressorContext, + _exec_ctx: &mut ExecutionCtx, + ) -> CompressionEstimate { + if data.array_len() < MIN_LEN { + return CompressionEstimate::Verdict(EstimateVerdict::Skip); + } + CompressionEstimate::Deferred(DeferredEstimate::Callback(Box::new( + |_compressor, data, best_so_far, _compress_ctx, exec_ctx| { + if matches!(best_so_far, Some(EstimateScore::ZeroBytes)) { + return Ok(EstimateVerdict::Skip); + } + let Some(bpv) = estimate_bpv(data.array_as_primitive(), exec_ctx)? else { + return Ok(EstimateVerdict::Skip); + }; + let ratio = 16.0 / bpv; + if best_so_far + .and_then(EstimateScore::finite_ratio) + .is_some_and(|best| ratio * (1.0 - MIN_SAVING) <= best) + { + return Ok(EstimateVerdict::Skip); + } + Ok(EstimateVerdict::Ratio(ratio)) + }, + ))) + } + + /// The high bytes and the longer groups are coded here; the short groups are compressed + /// further. The input's validity is registered. + fn encode( + &self, + data: &ArrayAndStats, + _compress_ctx: &CompressorContext, + exec_ctx: &mut ExecutionCtx, + ) -> VortexResult { + let parts = PivcoTokens::split(data.array_as_primitive(), exec_ctx)?; + let opts = ByteOptions::pha(); + let mut keep = vec![Child::new( + self, + 0, + PivcoBytes::encode_with_options(parts.hi.as_view(), opts, exec_ctx)?.into_array(), + )]; + let mut compress = Vec::new(); + let mut coded = Vec::with_capacity(parts.groups.len()); + for group in parts.groups { + if group.len() < MIN_CODED_GROUP_LEN { + compress.push(Child::new(self, 0, group.into_array())); + coded.push(false); + } else { + let group = PivcoBytes::encode_with_options(group.as_view(), opts, exec_ctx)?; + keep.push(Child::new(self, 0, group.into_array())); + coded.push(true); + } + } + let nullability = parts.nullability; + let group_his = parts.group_his; + Ok(Encoded::new(compress, keep, move |children, _exec_ctx| { + let [hi] = children.kept()?; + let groups = coded + .iter() + .map(|&coded| { + let [group] = if coded { + children.kept()? + } else { + children.compressed()? + }; + Ok(group) + }) + .collect::>>()?; + Ok( + PivcoTokens::try_new(nullability, hi, children.validity()?, group_his, groups)? + .into_array(), + ) + }) + .with_validity(parts.validity)) + } +} + +/// Estimated bits per value of [`PivcoTokens`] over up to [`SAMPLE_RUNS`] evenly spaced runs of +/// the column's valid values, or `None` when the sample holds none. +#[expect( + clippy::cast_precision_loss, + reason = "value and byte counts are far below 2^52" +)] +fn estimate_bpv( + primitive: ArrayView<'_, Primitive>, + exec_ctx: &mut ExecutionCtx, +) -> VortexResult> { + let len = primitive.len(); + let values = primitive.as_slice::(); + let mask = primitive.validity()?.execute_mask(len, exec_ctx)?; + let num_runs = len.div_ceil(SAMPLE_RUN_LEN); + let sampled_runs = num_runs.min(SAMPLE_RUNS); + let mut counts = vec![0u32; 1 << 16]; + let mut sample_len = 0usize; + for i in 0..sampled_runs { + let start = (i * num_runs / sampled_runs) * SAMPLE_RUN_LEN; + let end = (start + SAMPLE_RUN_LEN).min(len); + for (offset, &value) in values[start..end].iter().enumerate() { + if mask.value(start + offset) { + counts[usize::from(value)] += 1; + sample_len += 1; + } + } + } + if sample_len == 0 { + return Ok(None); + } + let n = sample_len as f64; + let entropy_bits: f64 = counts + .iter() + .filter(|&&c| c > 0) + .map(|&c| -f64::from(c) * (f64::from(c) / n).log2()) + .sum(); + let distinct = counts.iter().filter(|&&c| c > 0).count(); + let groups = counts + .chunks(256) + .filter(|group| group.iter().any(|&c| c > 0)) + .count(); + let tree_bytes = distinct * TREE_BYTES_PER_SYMBOL + (groups + 1) * TREE_BYTES_PER_GROUP; + Ok(Some( + entropy_bits / n * ENTROPY_OVERHEAD + (tree_bytes * 8) as f64 / len as f64, + )) +} + +#[cfg(test)] +mod tests { + use std::sync::LazyLock; + + use rand::RngExt; + use rand::SeedableRng; + use rand::rngs::StdRng; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::assert_arrays_eq; + use vortex_array::validity::Validity; + use vortex_buffer::Buffer; + use vortex_error::VortexResult; + use vortex_pivco_bytes::PivcoTokens; + use vortex_session::VortexSession; + + use super::PivcoTokensScheme; + use crate::CascadingCompressor; + use crate::schemes::integer::BitPackingScheme; + use crate::schemes::integer::FOR_V1; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + vortex_fastlanes::initialize(&session); + vortex_pivco_bytes::initialize(&session); + session + }); + + static BITPACKING: BitPackingScheme = BitPackingScheme::v1(); + + /// Skewed 12-bit token ids, as a substring dictionary produces. + fn tokens(len: usize) -> PrimitiveArray { + let mut rng = StdRng::seed_from_u64(3); + let values: Buffer = (0..len) + .map(|_| { + let r: u64 = rng.random_range(0..4096); + u16::try_from(r * r * r * r / (4096 * 4096 * 4096)).unwrap_or(u16::MAX) + }) + .collect(); + PrimitiveArray::new(values, Validity::NonNullable) + } + + #[test] + fn beats_bitpacking_on_skewed_tokens() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let compressor = CascadingCompressor::new(vec![&PivcoTokensScheme, &FOR_V1, &BITPACKING]); + let input = tokens(65_536).into_array(); + let compressed = compressor.compress(&input, &mut ctx)?; + assert!( + compressed.is::(), + "expected vortex.pivco_tokens, got {}", + compressed.display_tree() + ); + assert_arrays_eq!(compressed, input, &mut ctx); + Ok(()) + } + + #[test] + fn skips_short_columns() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let compressor = CascadingCompressor::new(vec![&PivcoTokensScheme]); + let short = tokens(100).into_array(); + assert!(!compressor.compress(&short, &mut ctx)?.is::()); + Ok(()) + } +} diff --git a/vortex-btrblocks/src/session.rs b/vortex-btrblocks/src/session.rs index 34e1b29100e..1894f767e86 100644 --- a/vortex-btrblocks/src/session.rs +++ b/vortex-btrblocks/src/session.rs @@ -73,6 +73,9 @@ impl Default for CompressionSession { &DELTA_SCHEME, // `u8` only, and only where the `unstable` edition permits `vortex.pivco_bytes`. &integer::PivcoBytesScheme, + // `u16` only, such as OnPair token codes, where the `unstable` edition permits + // `vortex.pivco_tokens`. + &integer::PivcoTokensScheme, #[cfg(feature = "pco")] &integer::PcoScheme, //////////////////////////////////////////////////////////////////////////////////// diff --git a/vortex-edition/src/declarations/unstable/mod.rs b/vortex-edition/src/declarations/unstable/mod.rs index c537e109e0c..e67d8f2265d 100644 --- a/vortex-edition/src/declarations/unstable/mod.rs +++ b/vortex-edition/src/declarations/unstable/mod.rs @@ -40,6 +40,7 @@ pub static DECLARATION: EditionDeclaration = EditionDeclaration { EditionMember::array(&"vortex.patched.integer"), EditionMember::array(&"vortex.pivco_bytes"), EditionMember::array(&"vortex.pivco_string"), + EditionMember::array(&"vortex.pivco_tokens"), EditionMember::dtype(&"vortex.duration"), ], }; diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests.rs index b5648f98522..737441ec42b 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -203,13 +203,13 @@ async fn test_eof_values() { #[rstest] #[case::default( BtrBlocksCompressorBuilder::from_session(&SESSION), - if cfg!(feature = "zstd") { 70_180 } else { 70_116 } + if cfg!(feature = "zstd") { 70_220 } else { 70_156 } )] #[cfg_attr( feature = "zstd", case::compact( BtrBlocksCompressorBuilder::from_session(&SESSION).with_compact(), - 55_276 + 55_316 ) )] #[tokio::test] diff --git a/vortex/editions/unstable/unstable2026.10.0.toml b/vortex/editions/unstable/unstable2026.10.0.toml index 0a5ed234bc8..0901e8dbb52 100644 --- a/vortex/editions/unstable/unstable2026.10.0.toml +++ b/vortex/editions/unstable/unstable2026.10.0.toml @@ -19,6 +19,7 @@ arrays = [ "vortex.patched.integer", "vortex.pivco_bytes", "vortex.pivco_string", + "vortex.pivco_tokens", ] layouts = [] dtypes = [ @@ -36,6 +37,7 @@ arrays = [ "vortex.patched.integer", "vortex.pivco_bytes", "vortex.pivco_string", + "vortex.pivco_tokens", ] layouts = [] dtypes = [