From 43916f001bbbc80f55b7ad4550935f3402a8b2b7 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Wed, 25 Nov 2026 22:46:57 -0500 Subject: [PATCH 1/6] Support lossless float narrowing in Widen and BtrBlocks Extend WidenArray and its existing preview vortex.widen wire format to narrow floating-point arrays bit-exactly (f64 to f32/f16, f32 to f16) using tag 1 (ChildType::Primitive) without introducing a new array ID or protobuf tag, and add FloatWidenScheme to BtrBlocks (excluded in CUDA writer preset, with CUDA WidenExecutor staging float Widen on host). Signed-off-by: Will Manning --- vortex-array/src/arrays/widen/array.rs | 25 +- .../src/arrays/widen/compute/aggregate.rs | 22 +- vortex-array/src/arrays/widen/compute/cast.rs | 11 + .../src/arrays/widen/compute/compare.rs | 52 ++ vortex-array/src/arrays/widen/compute/mod.rs | 46 +- .../src/arrays/widen/compute/numeric.rs | 3 + vortex-array/src/arrays/widen/compute/take.rs | 7 + vortex-array/src/arrays/widen/encode/float.rs | 250 +++++ vortex-array/src/arrays/widen/encode/mod.rs | 13 +- vortex-array/src/arrays/widen/mod.rs | 16 +- .../src/arrays/widen/tests/compute.rs | 25 + .../src/arrays/widen/tests/decimal.rs | 4 +- .../src/arrays/widen/tests/encoding.rs | 4 +- vortex-array/src/arrays/widen/tests/float.rs | 851 ++++++++++++++++++ vortex-array/src/arrays/widen/tests/mod.rs | 7 +- vortex-array/src/arrays/widen/tests/serde.rs | 116 ++- vortex-array/src/arrays/widen/vtable/mod.rs | 8 +- .../src/arrays/widen/vtable/plugin.rs | 29 +- vortex-btrblocks/src/builder.rs | 31 +- vortex-btrblocks/src/schemes/float/mod.rs | 2 + vortex-btrblocks/src/schemes/float/widen.rs | 687 ++++++++++++++ vortex-btrblocks/src/session.rs | 1 + vortex-compressor/src/scheme/ctx.rs | 6 +- vortex-cuda/src/kernel/encodings/widen/mod.rs | 14 +- .../src/kernel/encodings/widen/tests.rs | 29 + vortex-functions/src/zip/widen.rs | 90 ++ 26 files changed, 2293 insertions(+), 56 deletions(-) create mode 100644 vortex-array/src/arrays/widen/encode/float.rs create mode 100644 vortex-array/src/arrays/widen/tests/float.rs create mode 100644 vortex-btrblocks/src/schemes/float/widen.rs diff --git a/vortex-array/src/arrays/widen/array.rs b/vortex-array/src/arrays/widen/array.rs index c59446d0210..404e20ff54f 100644 --- a/vortex-array/src/arrays/widen/array.rs +++ b/vortex-array/src/arrays/widen/array.rs @@ -25,13 +25,16 @@ impl WidenArray { /// Creates a `Widen` that presents `values` with the wider logical `dtype`, without reading /// any values. /// - /// `values` and `dtype` **must** both be integers with the same signedness, or decimals with - /// the same scale. They **must** have the same nullability, and the canonical width of `values` - /// **must** be strictly narrower. When `values` is itself a `Widen`, the new array stores its - /// values instead, so that `Widen` arrays do not nest. + /// `values` and `dtype` **must** both be integers with the same signedness, both be + /// floating-point types, or both be decimals with the same scale. They **must** have the same + /// nullability, and the canonical width of `values` **must** be strictly narrower. When + /// `values` is itself a `Widen`, the new array stores its values instead, so that `Widen` + /// arrays do not nest. /// - /// A decimal child **must** be a valid decimal array for its declared dtype. Comparisons, - /// bounds checks and fills rely on this requirement. A violation gives incorrect results, + /// A decimal child **must** be a valid decimal array for its declared dtype, and a + /// floating-point child **must not** contain signaling NaNs (whose widening quiets them and + /// does not preserve IEEE-754 total order relative to quiet NaNs). Comparisons, aggregates, + /// bounds checks, and fills rely on these requirements. A violation gives incorrect results, /// but no undefined behavior. pub fn try_new(mut values: ArrayRef, dtype: DType) -> VortexResult { // NB: Check `values` before the flatten. The values of a `Widen` child are narrower than @@ -70,6 +73,14 @@ pub(super) fn validate_dtypes(values: &DType, logical: &DType) -> VortexResult<( "Widen requires values narrower than {logical}, got {values}" ); } + (DType::Primitive(values_ptype, _), DType::Primitive(logical_ptype, _)) + if values_ptype.is_float() && logical_ptype.is_float() => + { + vortex_ensure!( + values_ptype.byte_width() < logical_ptype.byte_width(), + "Widen requires values narrower than {logical}, got {values}" + ); + } (DType::Decimal(values_decimal, _), DType::Decimal(logical_decimal, _)) => { vortex_ensure!( values_decimal.scale() == logical_decimal.scale(), @@ -81,7 +92,7 @@ pub(super) fn validate_dtypes(values: &DType, logical: &DType) -> VortexResult<( ); } _ => vortex_bail!( - "Widen requires integer dtypes or decimal dtypes for {logical}, got {values}" + "Widen requires integer, float, or decimal dtypes for {logical}, got {values}" ), } diff --git a/vortex-array/src/arrays/widen/compute/aggregate.rs b/vortex-array/src/arrays/widen/compute/aggregate.rs index 6aa15593430..f022355da0a 100644 --- a/vortex-array/src/arrays/widen/compute/aggregate.rs +++ b/vortex-array/src/arrays/widen/compute/aggregate.rs @@ -53,6 +53,10 @@ impl DynAggregateKernel for WidenArrayAggregate { return aggregate_decimal(aggregate_fn, values, logical_dtype, ctx); } + if logical_dtype.is_float() { + return aggregate_order(aggregate_fn, values, logical_dtype, ctx); + } + if !logical_dtype.is_int() { return Ok(None); } @@ -86,9 +90,21 @@ fn aggregate_decimal( return Ok(Some(partial)); } - // Kernel registrations apply to the whole encoding. Keep this decimal allowlist so adding an - // integer aggregate cannot enable it here without checking its partials against canonical decimal - // execution. Every other decimal aggregate uses the default path. + aggregate_order(aggregate_fn, values, logical_dtype, ctx) +} + +/// Computes order and equality aggregates (`MinMax`, `Min`, `Max`, `IsConstant`, `IsSorted`) +/// directly on the narrow child. +/// +/// Kernel registrations apply to the whole encoding. Keeping this explicit allowlist ensures +/// adding a new aggregate cannot enable it for decimal or float `Widen` without checking its +/// partials against canonical execution. +fn aggregate_order( + aggregate_fn: &AggregateFnRef, + values: &ArrayRef, + logical_dtype: &DType, + ctx: &mut ExecutionCtx, +) -> VortexResult> { if !(aggregate_fn.is::() || aggregate_fn.is::() || aggregate_fn.is::() diff --git a/vortex-array/src/arrays/widen/compute/cast.rs b/vortex-array/src/arrays/widen/compute/cast.rs index d0ce1cb9f2b..bd1ec583f79 100644 --- a/vortex-array/src/arrays/widen/compute/cast.rs +++ b/vortex-array/src/arrays/widen/compute/cast.rs @@ -65,6 +65,17 @@ fn cast_primitive( return Ok(None); }; + if values_ptype.is_float() { + // Widening a float child to the logical float dtype is exact, so casting the child + // directly matches casting the widened values. Retain a `Widen` only for strictly wider + // float targets. + if target_ptype.is_float() && target_ptype.byte_width() > values_ptype.byte_width() { + let values = values.cast(DType::Primitive(values_ptype, *nullability))?; + return wrap_values(values, dtype.clone()).map(Some); + } + return values.cast(dtype.clone()).map(Some); + } + let cast_ptype = match values_ptype_for_cast(values_ptype, *target_ptype) { Some(cast_ptype) if target_ptype.byte_width() > cast_ptype.byte_width() => cast_ptype, // A float needs value conversion, and an integer target no wider than the converted child diff --git a/vortex-array/src/arrays/widen/compute/compare.rs b/vortex-array/src/arrays/widen/compute/compare.rs index bb9665a9c5a..6a4391e8ca1 100644 --- a/vortex-array/src/arrays/widen/compute/compare.rs +++ b/vortex-array/src/arrays/widen/compute/compare.rs @@ -16,9 +16,15 @@ use crate::arrays::widen::WidenArraySlotsExt; use crate::arrays::widen::compute::constant_fits_values; use crate::arrays::widen::compute::constant_in_values_dtype; use crate::arrays::widen::compute::ptype_holding_both_values; +use crate::arrays::widen::encode::f32_fits_in_f16; +use crate::arrays::widen::encode::f64_fits_in_f16; +use crate::arrays::widen::encode::f64_fits_in_f32; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::DecimalDType; +use crate::dtype::PType; +use crate::dtype::half::f16; +use crate::scalar::PValue; use crate::scalar::Scalar; use crate::scalar_fn::builtin::compare::CompareKernel; use crate::scalar_fn::builtin::operators::CompareOperator; @@ -43,6 +49,9 @@ impl CompareKernel for Widen { return Ok(None); }; let values = lhs.values(); + if values.dtype().is_float() { + return compare_float_constant(lhs, constant, operator); + } let Some(fits) = constant_fits_values(constant, values.dtype()) else { return Ok(None); }; @@ -95,6 +104,49 @@ fn compare_narrow_values( lhs_values.compare(rhs_values, operator).map(Some) } +/// Compares a floating-point `Widen` against a non-null floating-point constant. +/// +/// Pushes the comparison down to the narrow child when the non-NaN constant is represented +/// bit-for-bit in the child type. In-between constants and NaNs decline to canonical execution. +fn compare_float_constant( + lhs: ArrayView<'_, Widen>, + constant: &Scalar, + operator: CompareOperator, +) -> VortexResult> { + let values = lhs.values(); + let DType::Primitive(values_ptype, _) = values.dtype() else { + return Ok(None); + }; + let Some(pvalue) = constant.as_primitive().pvalue() else { + return Ok(None); + }; + if pvalue.is_nan() { + return Ok(None); + } + + let nullability = constant.dtype().nullability(); + let narrow_scalar = match (pvalue, *values_ptype) { + (PValue::F64(c), PType::F32) if f64_fits_in_f32(c) => + { + #[expect( + clippy::cast_possible_truncation, + reason = "f64_fits_in_f32 verified bit-exact representation" + )] + Scalar::primitive(c as f32, nullability) + } + (PValue::F64(c), PType::F16) if f64_fits_in_f16(c) => { + Scalar::primitive(f16::from_f64(c), nullability) + } + (PValue::F32(c), PType::F16) if f32_fits_in_f16(c) => { + Scalar::primitive(f16::from_f32(c), nullability) + } + _ => return Ok(None), + }; + + let constant = ConstantArray::new(narrow_scalar, lhs.len()).into_array(); + values.compare(constant, operator).map(Some) +} + /// Answers a compare of `lhs` with a valid `constant` outside the range of its values. /// /// Every value is on the same side of the constant, so every valid row has the same answer, and the diff --git a/vortex-array/src/arrays/widen/compute/mod.rs b/vortex-array/src/arrays/widen/compute/mod.rs index f06b9e4623f..d7b86235262 100644 --- a/vortex-array/src/arrays/widen/compute/mod.rs +++ b/vortex-array/src/arrays/widen/compute/mod.rs @@ -39,6 +39,7 @@ use crate::arrays::ConstantArray; use crate::arrays::Widen; use crate::arrays::WidenArray; use crate::arrays::widen::WidenArraySlotsExt; +use crate::arrays::widen::encode::smallest_float_ptype_for_value; use crate::arrays::widen::encode::smallest_integer_ptype; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; @@ -60,10 +61,11 @@ pub fn wrap_values(values: ArrayRef, dtype: DType) -> VortexResult { } /// Returns the type that the values of `array` widen to so that they also hold `scalar`: the type -/// of the values, or the smallest wider type of the logical signedness that holds `scalar`. +/// of the values, or the smallest wider primitive type of the logical kind that holds `scalar` +/// losslessly. /// /// A null `scalar` keeps the type of the values. Returns `None` when `scalar` does not have the -/// logical dtype, or when the values or the logical dtype is not an integer (a decimal `Widen`). +/// logical dtype, or when the values or the logical dtype is not primitive (a decimal `Widen`). pub fn ptype_holding_values_and_scalar( array: ArrayView<'_, Widen>, scalar: &Scalar, @@ -80,12 +82,18 @@ pub fn ptype_holding_values_and_scalar( return Some(*values_ptype); } - let value = scalar + let pvalue = scalar .as_primitive() .pvalue() - .and_then(PValue::as_i128) - .vortex_expect("the non-null scalar has the Widen's integer dtype"); - let scalar_ptype = smallest_integer_ptype(value..=value, logical_ptype.is_signed_int())?; + .vortex_expect("non-null primitive scalar has a value"); + let scalar_ptype = if logical_ptype.is_float() { + smallest_float_ptype_for_value(pvalue)? + } else { + let value = pvalue + .as_i128() + .vortex_expect("the non-null scalar has the Widen's integer dtype"); + smallest_integer_ptype(value..=value, logical_ptype.is_signed_int())? + }; if scalar_ptype.byte_width() > values_ptype.byte_width() { Some(scalar_ptype) @@ -94,15 +102,15 @@ pub fn ptype_holding_values_and_scalar( } } -/// Casts the integer array `array` to `ptype`, keeping its nullability. +/// Casts the primitive array `array` to `ptype`, keeping its nullability. pub fn cast_keeping_nullability(array: &ArrayRef, ptype: PType) -> VortexResult { array.cast(DType::Primitive(ptype, array.dtype().nullability())) } -/// Returns whether the dtype range of `values` holds `constant`. +/// Returns whether the dtype of `values` holds `constant` losslessly. /// -/// Integers must have the same signedness, and decimals must have the same scale. Returns `None` -/// for null constants, unsupported dtypes, or incompatible constants. +/// Integers must have the same signedness and decimals must have the same scale. Returns `None` +/// for null constants, floats, unsupported dtypes, or incompatible constants. pub fn constant_fits_values(constant: &Scalar, values: &DType) -> Option { match (values, constant.dtype()) { (DType::Decimal(values_dtype, _), DType::Decimal(constant_dtype, _)) @@ -130,10 +138,10 @@ pub fn constant_fits_values(constant: &Scalar, values: &DType) -> Option { } /// Returns the wider of the value types of two [`Widen`] arrays, or `None` when a value type is -/// not primitive. +/// not a compatible primitive type. /// -/// The logical dtypes **must** have the same signedness. The value types then have that signedness -/// too, so the wider one holds every value of the narrower one. +/// Both arrays must share the same primitive kind (both signed integers, both unsigned integers, +/// or both floats), so the wider value type holds every value of the narrower one. pub fn ptype_holding_both_values( lhs: ArrayView<'_, Widen>, rhs: ArrayView<'_, Widen>, @@ -144,10 +152,18 @@ pub fn ptype_holding_both_values( return None; }; - if lhs_ptype.is_signed_int() { + if lhs_ptype.is_float() && rhs_ptype.is_float() { + if lhs_ptype.byte_width() >= rhs_ptype.byte_width() { + Some(*lhs_ptype) + } else { + Some(*rhs_ptype) + } + } else if lhs_ptype.is_signed_int() && rhs_ptype.is_signed_int() { Some(lhs_ptype.max_signed_ptype(*rhs_ptype)) - } else { + } else if lhs_ptype.is_unsigned_int() && rhs_ptype.is_unsigned_int() { Some(lhs_ptype.max_unsigned_ptype(*rhs_ptype)) + } else { + None } } diff --git a/vortex-array/src/arrays/widen/compute/numeric.rs b/vortex-array/src/arrays/widen/compute/numeric.rs index 3762e9a489e..2c7778553da 100644 --- a/vortex-array/src/arrays/widen/compute/numeric.rs +++ b/vortex-array/src/arrays/widen/compute/numeric.rs @@ -67,6 +67,9 @@ impl ExecuteParentKernel for WidenNumericKernel { let DType::Primitive(logical_ptype, _) = array.dtype() else { return Ok(None); }; + if !logical_ptype.is_int() { + return Ok(None); + } let binary = parent .as_opt::() diff --git a/vortex-array/src/arrays/widen/compute/take.rs b/vortex-array/src/arrays/widen/compute/take.rs index dee12306237..a29b03d6bcf 100644 --- a/vortex-array/src/arrays/widen/compute/take.rs +++ b/vortex-array/src/arrays/widen/compute/take.rs @@ -19,6 +19,13 @@ impl TakeExecute for Widen { indices: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { + // When gathering more rows than the values array holds (for example `Dict(codes, Widen)`), + // let `Dict` widen the small values table once instead of gathering narrow values and + // widening every output row. + if indices.len() > array.len() { + return Ok(None); + } + // Execute the gather, so that no lazy `Dict` sits under the `Widen` (see the `widen` // module docs). `Columnar` keeps a constant gather constant. let values = array diff --git a/vortex-array/src/arrays/widen/encode/float.rs b/vortex-array/src/arrays/widen/encode/float.rs new file mode 100644 index 00000000000..e702e8f85f8 --- /dev/null +++ b/vortex-array/src/arrays/widen/encode/float.rs @@ -0,0 +1,250 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Bit-exact floating-point narrowing for [`WidenArray`]. +//! +//! A floating-point value fits in a narrower IEEE-754 type iff narrowing and widening back +//! reproduces the original bit pattern, and any NaN is the positive canonical quiet NaN. +//! Comparing bit patterns preserves `-0.0` vs `+0.0`, while restricting NaNs to the canonical +//! quiet NaN keeps narrowing portable across architectures whose float conversions do not +//! preserve NaN sign or payload bits. + +use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_mask::Mask; + +use crate::ArrayRef; +use crate::ExecutionCtx; +use crate::IntoArray; +use crate::arrays::PrimitiveArray; +use crate::arrays::WidenArray; +use crate::arrays::widen::compute::wrap_values; +use crate::dtype::PType; +use crate::dtype::half::f16; +use crate::scalar::PValue; + +/// Number of lanes checked per branchless chunk so LLVM autovectorizes the scan while still +/// exiting early on non-narrowable columns. +const FIT_CHECK_CHUNK_LEN: usize = 64; + +/// Returns whether `value` round-trips bit-for-bit through `f32`, accepting only the positive +/// canonical quiet NaN (`f64::NAN`) among NaN bit patterns. +#[inline] +pub(in crate::arrays::widen) fn f64_fits_in_f32(value: f64) -> bool { + #[expect( + clippy::cast_possible_truncation, + reason = "round-trip bit comparison immediately verifies that narrowing to f32 was lossless" + )] + let narrowed = value as f32; + f64::from(narrowed).to_bits() == value.to_bits() + && (!value.is_nan() || value.to_bits() == f64::NAN.to_bits()) +} + +/// Returns whether `value` round-trips bit-for-bit through `f16`, accepting only the positive +/// canonical quiet NaN (`f32::NAN`) among NaN bit patterns. +#[inline] +pub(in crate::arrays::widen) fn f32_fits_in_f16(value: f32) -> bool { + let narrowed = f16::from_f32(value); + narrowed.to_f32().to_bits() == value.to_bits() + && (!value.is_nan() || value.to_bits() == f32::NAN.to_bits()) +} + +/// Returns whether `value` round-trips bit-for-bit through `f16`, accepting only the positive +/// canonical quiet NaN (`f64::NAN`) among NaN bit patterns. +#[inline] +pub(in crate::arrays::widen) fn f64_fits_in_f16(value: f64) -> bool { + let narrowed = f16::from_f64(value); + narrowed.to_f64().to_bits() == value.to_bits() + && (!value.is_nan() || value.to_bits() == f64::NAN.to_bits()) +} + +fn f64_slice_fits_in_f32(values: &[f64]) -> bool { + slice_fits_chunked(values, f64_fits_in_f32) +} + +fn f32_slice_fits_in_f16(values: &[f32]) -> bool { + slice_fits_chunked(values, f32_fits_in_f16) +} + +fn f64_slice_fits_in_f16(values: &[f64]) -> bool { + slice_fits_chunked(values, f64_fits_in_f16) +} + +#[inline] +fn slice_fits_chunked(values: &[T], fits: impl Fn(T) -> bool) -> bool { + for chunk in values.chunks(FIT_CHECK_CHUNK_LEN) { + let mut all_fit = true; + for &value in chunk { + all_fit &= fits(value); + } + if !all_fit { + return false; + } + } + true +} + +fn all_valid_slices_match(slice: &[T], mask: &Mask, check: impl Fn(&[T]) -> bool) -> bool { + match mask { + Mask::AllTrue(_) => check(slice), + Mask::AllFalse(_) => true, + Mask::Values(values) => values + .bit_buffer() + .set_slices() + .all(|(start, end)| check(&slice[start..end])), + } +} + +/// Returns the narrowest floating-point [`PType`] strictly narrower than `array`'s type that +/// reproduces every valid element bit-for-bit on widening back, or `None` when no narrower float +/// type fits (including when `array` is already `f16`, not a float, or not host-resident). +/// +/// `mask` **must** be the validity mask of `array`. +pub fn narrowest_float_ptype(array: &PrimitiveArray, mask: &Mask) -> Option { + if !array.buffer_handle().is_on_host() { + return None; + } + match array.ptype() { + PType::F64 => { + let slice = array.as_slice::(); + // Every `f16` value is exact in `f32`, so a fast `f32` scan rejects general `f64` + // columns before attempting the narrower `f16` check. + if !all_valid_slices_match(slice, mask, f64_slice_fits_in_f32) { + return None; + } + if all_valid_slices_match(slice, mask, f64_slice_fits_in_f16) { + Some(PType::F16) + } else { + Some(PType::F32) + } + } + PType::F32 => all_valid_slices_match(array.as_slice::(), mask, f32_slice_fits_in_f16) + .then_some(PType::F16), + _ => None, + } +} + +/// Narrows floating-point `array` to the strictly narrower floating-point type `target`, +/// preserving its validity and writing zero into null slots. +/// +/// Callers **must** verify that every valid element in `array` fits losslessly in `target` +/// (for example via [`narrowest_float_ptype`]); otherwise values are rounded silently. Use +/// [`WidenArray::encode_float`] for checked encoding. +/// +/// Null slots are zeroed so arbitrary null payloads cannot introduce signaling NaNs into the +/// narrowed child. `mask` **must** be the validity mask of `array`. +pub fn narrow_float_values( + array: &PrimitiveArray, + target: PType, + mask: &Mask, +) -> VortexResult { + vortex_ensure!( + array.buffer_handle().is_on_host(), + "Widen float narrowing requires host-resident values" + ); + let validity = array.validity()?; + match (array.ptype(), target) { + (PType::F64, PType::F32) => { + #[expect( + clippy::cast_possible_truncation, + reason = "caller verified bit-exact f32 representation on valid lanes; null lanes are zeroed" + )] + let buffer = narrow_slice_with_mask(array.as_slice::(), mask, |v| v as f32); + Ok(PrimitiveArray::new(buffer, validity)) + } + (PType::F64, PType::F16) => { + let buffer = narrow_slice_with_mask(array.as_slice::(), mask, f16::from_f64); + Ok(PrimitiveArray::new(buffer, validity)) + } + (PType::F32, PType::F16) => { + let buffer = narrow_slice_with_mask(array.as_slice::(), mask, f16::from_f32); + Ok(PrimitiveArray::new(buffer, validity)) + } + (src, dst) => { + vortex_bail!("expected a strictly narrower float target than {src}, got {dst}") + } + } +} + +fn narrow_slice_with_mask( + slice: &[W], + mask: &Mask, + narrow: impl Fn(W) -> N, +) -> Buffer { + let len = slice.len(); + match mask { + Mask::AllTrue(_) => { + let mut out = BufferMut::::with_capacity(len); + for &value in slice { + out.push(narrow(value)); + } + out.freeze() + } + Mask::AllFalse(_) => Buffer::::zeroed(len), + Mask::Values(values) => { + let mut out = BufferMut::::zeroed(len); + for (start, end) in values.bit_buffer().set_slices() { + for (dst, &src) in out[start..end].iter_mut().zip(&slice[start..end]) { + *dst = narrow(src); + } + } + out.freeze() + } + } +} + +/// Returns the smallest floating-point type that holds `value` bit-exactly, accepting only the +/// positive canonical quiet NaN among NaN bit patterns. +pub(in crate::arrays::widen) fn smallest_float_ptype_for_value(value: PValue) -> Option { + match value { + PValue::F16(_) => Some(PType::F16), + PValue::F32(v) => { + if f32_fits_in_f16(v) { + Some(PType::F16) + } else { + Some(PType::F32) + } + } + PValue::F64(v) => { + if f64_fits_in_f16(v) { + Some(PType::F16) + } else if f64_fits_in_f32(v) { + Some(PType::F32) + } else { + Some(PType::F64) + } + } + _ => None, + } +} + +impl WidenArray { + /// Stores `array` as a `Widen` over the narrowest floating-point type (`f16` or `f32`) that + /// reproduces every valid value bit-for-bit on widening back, or returns `array` unchanged + /// when no narrower floating-point type holds them. + /// + /// Bit-exact checking preserves `-0.0` vs `+0.0` and the positive canonical quiet NaN while + /// rejecting signaling NaNs, negative NaNs, and non-canonical NaN payloads. Null rows do not + /// count, so their payloads may hold arbitrary values and are zeroed in the narrowed child. + /// An empty or all-null `f32` or `f64` array narrows to `f16`. Fails when `array` is not a + /// floating-point array. + pub fn encode_float(array: PrimitiveArray, ctx: &mut ExecutionCtx) -> VortexResult { + let ptype = array.ptype(); + vortex_ensure!( + ptype.is_float(), + "Widen float encoding requires floating-point values, got {ptype}" + ); + + let mask = array.validity()?.execute_mask(array.len(), ctx)?; + let Some(target) = narrowest_float_ptype(&array, &mask) else { + return Ok(array.into_array()); + }; + + let dtype = array.dtype().clone(); + let narrowed = narrow_float_values(&array, target, &mask)?; + wrap_values(narrowed.into_array(), dtype) + } +} diff --git a/vortex-array/src/arrays/widen/encode/mod.rs b/vortex-array/src/arrays/widen/encode/mod.rs index da2219d8044..f604c8b09cd 100644 --- a/vortex-array/src/arrays/widen/encode/mod.rs +++ b/vortex-array/src/arrays/widen/encode/mod.rs @@ -3,13 +3,22 @@ //! Selection of narrower `Widen` children from valid values. //! -//! Integer narrowing and decimal conversion use separate implementations. Decimal encoding and -//! stored-value reads share one child-selection path so they cannot disagree about its precision. +//! Integer narrowing, floating-point narrowing, and decimal conversion use separate +//! implementations. Decimal encoding and stored-value reads share one child-selection path so they +//! cannot disagree about its precision. mod decimal; #[cfg(test)] pub(crate) use decimal::smallest_decimal_dtype; +mod float; +pub(super) use float::f32_fits_in_f16; +pub(super) use float::f64_fits_in_f16; +pub(super) use float::f64_fits_in_f32; +pub use float::narrow_float_values; +pub use float::narrowest_float_ptype; +pub(super) use float::smallest_float_ptype_for_value; + mod integer; pub(super) use integer::integer_extrema; pub(super) use integer::smallest_integer_ptype; diff --git a/vortex-array/src/arrays/widen/mod.rs b/vortex-array/src/arrays/widen/mod.rs index f4af53947fa..9b3e3e131b0 100644 --- a/vortex-array/src/arrays/widen/mod.rs +++ b/vortex-array/src/arrays/widen/mod.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Stores integer and decimal values in a narrower child array. +//! Stores integer, floating-point, and decimal values in a narrower child array. //! //! A [`WidenArray`] exposes the original dtype. Its child stores the same values at a strictly //! narrower canonical width and supplies their validity. The wrapper and child have the same @@ -13,6 +13,11 @@ //! fixes the dtype of an integer child and stores it narrower uses //! [`WidenArray::from_stored_integer`] on read and [`WidenArray::to_stored_integer`] on write. //! +//! A floating-point child has a strictly narrower IEEE-754 type (`f16 < f32 < f64`) and **must +//! not** contain signaling NaNs. [`WidenArray::encode_float`] selects the narrowest type that +//! reproduces every valid value bit-for-bit on widening back, preserving `-0.0` vs `+0.0` and +//! canonical quiet NaNs. +//! //! A decimal child has the logical scale and a lower precision, and **must** be valid for its dtype. //! Comparisons, bounds checks, and fills use the child dtype to bound its valid values. //! [`WidenArray::encode_decimal`] and [`WidenArray::from_stored_decimal`] choose child precision @@ -21,7 +26,7 @@ //! canonical width, since yielding a cast would produce another `Widen` instead of canonical values. //! //! Narrowing is a physical choice, so it **must not** change a result. Execution casts the values -//! to the logical dtype for integers, and an operation runs on the values only where it gives the +//! to the logical dtype for primitives, and an operation runs on the values only where it gives the //! canonical result. A `Widen` never wraps another `Widen`. //! //! Take executes its gather instead of leaving a lazy [`Dict`] under a `Widen`, because code such @@ -31,8 +36,9 @@ //! child, the plugin writes a legacy `vortex.decimal` node so older readers can read it. The node //! stores the child's buffer width, and the enclosing format supplies the parent's logical dtype. //! [`WidenArray::from_stored_decimal`] handles these nodes in both old and newly written files. -//! Integer children and decimals stored in another encoding use `vortex.widen`. When edition checks -//! are enabled, the target edition must allow the chosen wire ID. +//! Integer children, floating-point children, and decimals stored in another encoding use +//! `vortex.widen`. When edition checks are enabled, the target edition must allow the chosen wire +//! ID. //! //! [`ArraySession`]: crate::session::ArraySession //! [`Dict`]: crate::arrays::Dict @@ -46,7 +52,7 @@ pub use array::WidenSlots; pub use array::WidenSlotsView; pub mod compute; -mod encode; +pub mod encode; mod stored; mod vtable; diff --git a/vortex-array/src/arrays/widen/tests/compute.rs b/vortex-array/src/arrays/widen/tests/compute.rs index c7b9df3bfb5..3d148ca6ff4 100644 --- a/vortex-array/src/arrays/widen/tests/compute.rs +++ b/vortex-array/src/arrays/widen/tests/compute.rs @@ -25,6 +25,7 @@ use crate::arrays::BoolArray; use crate::arrays::Constant; use crate::arrays::ConstantArray; use crate::arrays::Dict; +use crate::arrays::DictArray; use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; use crate::arrays::Widen; @@ -115,6 +116,30 @@ fn test_take_keeps_constant_values() -> VortexResult<()> { Ok(()) } +/// When `indices.len() > array.len()` (as in `Dict(codes, Widen(values))`), `Widen::take` defers +/// to `Dict` so the small values table is widened once rather than widening every gathered row. +#[test] +fn test_take_defers_when_expanding_dict_values() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = widen(buffer![-0.0_f32, 1.5_f32, 2.5_f32], PType::F64).into_array(); + let codes = buffer![0u8, 1, 2, 1, 0, 2, 1, 0].into_array(); + let dict = DictArray::try_new(codes, values)?.into_array(); + + let executed = dict.execute::(&mut ctx)?; + assert!(executed.is::()); + let dict_values = executed.as_::().values(); + assert!(!dict_values.is::()); + assert_eq!(dict_values.len(), 3); + assert_eq!(dict_values.dtype(), &DType::from(PType::F64)); + assert_arrays_eq!( + executed, + PrimitiveArray::from_iter([-0.0_f64, 1.5, 2.5, 1.5, -0.0, 2.5, 1.5, -0.0]), + &mut ctx + ); + + Ok(()) +} + #[test] fn test_cast_preserves_checked_nullability() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); diff --git a/vortex-array/src/arrays/widen/tests/decimal.rs b/vortex-array/src/arrays/widen/tests/decimal.rs index aef6414b4e6..e231a1fdb55 100644 --- a/vortex-array/src/arrays/widen/tests/decimal.rs +++ b/vortex-array/src/arrays/widen/tests/decimal.rs @@ -43,12 +43,12 @@ fn dtype(precision: u8, scale: i8, nullability: Nullability) -> DType { #[case::integer_child( PType::I32.into(), dtype(18, 2, NonNullable), - "integer dtypes or decimal dtypes", + "integer, float, or decimal dtypes", )] #[case::integer_parent( dtype(9, 2, NonNullable), PType::I64.into(), - "integer dtypes or decimal dtypes", + "integer, float, or decimal dtypes", )] fn test_rejects_invalid_decimal_dtypes( #[case] child: DType, diff --git a/vortex-array/src/arrays/widen/tests/encoding.rs b/vortex-array/src/arrays/widen/tests/encoding.rs index e58d84131bd..3975639966a 100644 --- a/vortex-array/src/arrays/widen/tests/encoding.rs +++ b/vortex-array/src/arrays/widen/tests/encoding.rs @@ -133,8 +133,8 @@ fn test_smallest_integer_ptype( /// Both `try_new` and `VTable::validate`, which `try_from_parts` runs, reject the dtypes. #[rstest] -#[case::bool_values( DType::Bool(Nullability::NonNullable), PType::I64.into(), "integer dtypes")] -#[case::float_values( PType::F32.into(), PType::I64.into(), "integer dtypes")] +#[case::bool_values( DType::Bool(Nullability::NonNullable), PType::I64.into(), "integer, float, or decimal dtypes")] +#[case::float_values( PType::F32.into(), PType::I64.into(), "integer, float, or decimal dtypes")] #[case::signedness( PType::I8.into(), PType::U64.into(), "signedness")] #[case::equal_width( PType::I8.into(), PType::I8.into(), "narrower")] #[case::nullability( diff --git a/vortex-array/src/arrays/widen/tests/float.rs b/vortex-array/src/arrays/widen/tests/float.rs new file mode 100644 index 00000000000..0b2425d6d02 --- /dev/null +++ b/vortex-array/src/arrays/widen/tests/float.rs @@ -0,0 +1,851 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Construction, execution, compute, and aggregate tests for floating-point [`Widen`] arrays. + +use rstest::rstest; +use vortex_buffer::Buffer; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_mask::Mask; + +use super::SESSION; +use super::assert_compare_matches_canonical; +use super::canonical; +use super::stored_ptype; +use super::widen; +use crate::ArrayParts; +use crate::ArrayRef; +use crate::Canonical; +use crate::EmptyArrayData; +use crate::IntoArray; +use crate::VortexSessionExecute; +use crate::aggregate_fn::AggregateFnVTableExt; +use crate::aggregate_fn::EmptyOptions; +use crate::aggregate_fn::NumericalAggregateOpts; +use crate::aggregate_fn::fns::is_constant::IsConstant; +use crate::aggregate_fn::fns::is_sorted::IsSorted; +use crate::aggregate_fn::fns::is_sorted::IsSortedOptions; +use crate::aggregate_fn::fns::max::Max; +use crate::aggregate_fn::fns::min::Min; +use crate::aggregate_fn::fns::min_max::MinMax; +use crate::aggregate_fn::fns::sum::Sum; +use crate::aggregate_fn::fns::sum_v2::SumV2; +use crate::aggregate_fn::kernels::DynAggregateKernel; +use crate::arrays::BoolArray; +use crate::arrays::ChunkedArray; +use crate::arrays::ConstantArray; +use crate::arrays::Dict; +use crate::arrays::DictArray; +use crate::arrays::Primitive; +use crate::arrays::PrimitiveArray; +use crate::arrays::Widen; +use crate::arrays::WidenArray; +use crate::arrays::dict::DictArraySlotsExt; +use crate::arrays::widen::WidenArraySlotsExt; +use crate::arrays::widen::WidenSlots; +use crate::arrays::widen::compute::aggregate::WidenArrayAggregate; +use crate::arrays::widen::compute::ptype_holding_both_values; +use crate::arrays::widen::compute::ptype_holding_values_and_scalar; +use crate::assert_arrays_eq; +use crate::builtins::ArrayBuiltins; +use crate::dtype::DType; +use crate::dtype::DecimalDType; +use crate::dtype::Nullability; +use crate::dtype::PType; +use crate::dtype::half::f16; +use crate::optimizer::ArrayOptimizer; +use crate::scalar::NumericOperator; +use crate::scalar::Scalar; +use crate::scalar_fn::builtin::operators::CompareOperator; +use crate::validity::Validity; + +const ALL_COMPARE_OPERATORS: [CompareOperator; 6] = [ + CompareOperator::Eq, + CompareOperator::NotEq, + CompareOperator::Lt, + CompareOperator::Lte, + CompareOperator::Gt, + CompareOperator::Gte, +]; + +/// Edge-case `f32` values covering infinities, finite bounds, subnormals, signed zeros, and +/// canonical quiet NaN, sorted in IEEE-754 total order. +fn f32_edge_values() -> Vec { + vec![ + f32::NEG_INFINITY, + -f32::MAX, + -100.0, + -0.1_f32, + -f32::from_bits(1), + -0.0_f32, + 0.0_f32, + f32::from_bits(1), + 0.1_f32, + 1.0, + f32::MAX, + f32::INFINITY, + f32::NAN, + ] +} + +/// Edge-case `f16` values sorted in IEEE-754 total order. +fn f16_edge_values() -> Vec { + vec![ + f16::NEG_INFINITY, + f16::MIN, + f16::from_f32(-1.5), + -f16::from_bits(1), + f16::NEG_ZERO, + f16::ZERO, + f16::from_bits(1), + f16::from_f32(1.5), + f16::MAX, + f16::INFINITY, + f16::NAN, + ] +} + +#[rstest] +#[case::f16_to_f32(PType::F16, PType::F32, Nullability::NonNullable)] +#[case::f16_to_f64(PType::F16, PType::F64, Nullability::Nullable)] +#[case::f32_to_f64(PType::F32, PType::F64, Nullability::NonNullable)] +#[case::f32_to_f64_nullable(PType::F32, PType::F64, Nullability::Nullable)] +fn test_try_new_accepts_narrower_float_dtypes( + #[case] child: PType, + #[case] logical: PType, + #[case] nullability: Nullability, +) -> VortexResult<()> { + let values = Canonical::empty(&DType::Primitive(child, nullability)).into_array(); + let widened = WidenArray::try_new(values, DType::Primitive(logical, nullability))?; + + assert_eq!(widened.dtype(), &DType::Primitive(logical, nullability)); + assert_eq!( + widened.values().dtype(), + &DType::Primitive(child, nullability) + ); + + Ok(()) +} + +#[rstest] +#[case::equal_f16(PType::F16.into(), PType::F16.into(), "narrower")] +#[case::equal_f32(PType::F32.into(), PType::F32.into(), "narrower")] +#[case::equal_f64(PType::F64.into(), PType::F64.into(), "narrower")] +#[case::wider_f64_to_f32(PType::F64.into(), PType::F32.into(), "narrower")] +#[case::wider_f32_to_f16(PType::F32.into(), PType::F16.into(), "narrower")] +#[case::int_to_float(PType::I16.into(), PType::F64.into(), "integer, float, or decimal dtypes")] +#[case::float_to_int(PType::F32.into(), PType::I64.into(), "integer, float, or decimal dtypes")] +#[case::float_to_decimal( + PType::F32.into(), + DType::Decimal(DecimalDType::new(18, 2), Nullability::NonNullable), + "integer, float, or decimal dtypes", +)] +#[case::nullability_mismatch( + PType::F32.into(), + DType::Primitive(PType::F64, Nullability::Nullable), + "nullability", +)] +fn test_rejects_invalid_float_dtypes( + #[case] values: DType, + #[case] logical: DType, + #[case] requirement: &str, +) { + let values = Canonical::empty(&values).into_array(); + let slots = WidenSlots { + values: values.clone(), + } + .into_slots(); + let parts = ArrayParts::new(Widen, logical.clone(), 0, EmptyArrayData, slots); + + let try_new_error = WidenArray::try_new(values, logical) + .expect_err("invalid float Widen dtypes must fail") + .to_string(); + let validate_error = WidenArray::try_from_parts(parts) + .expect_err("invalid float Widen dtypes must fail validation") + .to_string(); + + assert!(try_new_error.contains(requirement), "{try_new_error}"); + assert!(validate_error.contains(requirement), "{validate_error}"); +} + +#[test] +fn test_try_new_and_reduce_flatten_nested_float_widen() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = PrimitiveArray::from_option_iter([ + Some(f16::NEG_ZERO), + None, + Some(f16::from_f32(1.5)), + Some(f16::INFINITY), + ]) + .into_array(); + + let inner = widen(values.clone(), PType::F32).into_array(); + let outer = WidenArray::try_new( + inner.clone(), + DType::Primitive(PType::F64, Nullability::Nullable), + )?; + assert!(outer.values().is::()); + assert_eq!( + outer.values().dtype(), + &DType::Primitive(PType::F16, Nullability::Nullable) + ); + + let nested = WidenArray::try_from_parts(ArrayParts::new( + Widen, + DType::Primitive(PType::F64, Nullability::Nullable), + inner.len(), + EmptyArrayData, + WidenSlots { values: inner }.into_slots(), + ))?; + assert!(nested.values().is::()); + let flattened = nested.into_array().optimize_ctx(&SESSION)?; + assert!(ArrayRef::ptr_eq(flattened.as_::().values(), &values)); + + let expected = PrimitiveArray::from_option_iter([ + Some(-0.0_f64), + None, + Some(1.5_f64), + Some(f64::INFINITY), + ]); + assert_arrays_eq!(outer, expected, &mut ctx); + assert_arrays_eq!(flattened, expected, &mut ctx); + + Ok(()) +} + +#[test] +fn test_encode_float_f64_bit_exact_round_trip() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + + // All values representable in f16 -> narrows to f16. + let f16_in_f64: Vec = f16_edge_values().into_iter().map(f16::to_f64).collect(); + let input = PrimitiveArray::from_iter(f16_in_f64.clone()); + let encoded = WidenArray::encode_float(input.clone(), &mut ctx)?; + assert_eq!(stored_ptype(&encoded), PType::F16); + assert_eq!(encoded.dtype(), input.dtype()); + let decoded = encoded.clone().execute::(&mut ctx)?; + for (idx, (&actual, &expected)) in decoded + .as_slice::() + .iter() + .zip(&f16_in_f64) + .enumerate() + { + assert_eq!( + actual.to_bits(), + expected.to_bits(), + "f16->f64 bit mismatch at row {idx}" + ); + let scalar = encoded.execute_scalar(idx, &mut ctx)?; + assert_eq!( + scalar.as_primitive().typed_value::().map(f64::to_bits), + Some(expected.to_bits()), + "f16->f64 scalar_at bit mismatch at row {idx}" + ); + } + + // Values representable in f32 (including -0.0, subnormals, canonical NaN) -> narrows to f32. + let f32_in_f64: Vec = f32_edge_values().into_iter().map(f64::from).collect(); + let input = PrimitiveArray::from_iter(f32_in_f64.clone()); + let encoded = WidenArray::encode_float(input, &mut ctx)?; + assert_eq!(stored_ptype(&encoded), PType::F32); + let decoded = encoded.execute::(&mut ctx)?; + for (idx, (&actual, &expected)) in decoded + .as_slice::() + .iter() + .zip(&f32_in_f64) + .enumerate() + { + assert_eq!( + actual.to_bits(), + expected.to_bits(), + "f32->f64 bit mismatch at row {idx}" + ); + } + + Ok(()) +} + +#[rstest] +#[case::inexact_decimal(vec![0.0_f64, 0.1_f64, 1.0_f64])] +#[case::overflow_f32(vec![1.0_f64, 1e100_f64])] +#[case::underflow_f32(vec![1.0_f64, 1e-100_f64])] +#[case::f64_max(vec![f64::MAX])] +#[case::non_f32_qnan_payload(vec![1.0_f64, f64::from_bits(0x7ff8_0000_0000_0001)])] +#[case::f64_neg_nan(vec![1.0_f64, -f64::NAN])] +#[case::f64_snan_low(vec![1.0_f64, f64::from_bits(0x7ff0_0000_0000_0001)])] +#[case::f64_snan_aligned(vec![1.0_f64, f64::from_bits(0x7ff0_0000_2000_0000)])] +fn test_encode_float_f64_rejects_lossy_and_snan(#[case] values: Vec) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let input = PrimitiveArray::from_iter(values); + let encoded = WidenArray::encode_float(input.clone(), &mut ctx)?; + + assert_eq!(stored_ptype(&encoded), PType::F64); + assert!(!encoded.is::()); + assert_arrays_eq!(encoded, input, &mut ctx); + + Ok(()) +} + +#[rstest] +#[case::f16_exact( + PrimitiveArray::from_iter(f16_edge_values().into_iter().map(f16::to_f32).collect::>()), + PType::F16, +)] +#[case::f32_inexact(PrimitiveArray::from_iter([0.1_f32, 1.0_f32]), PType::F32)] +#[case::f32_non_f16_qnan(PrimitiveArray::from_iter([1.0_f32, f32::from_bits(0x7fc0_0001)]), PType::F32)] +#[case::f32_neg_nan(PrimitiveArray::from_iter([1.0_f32, -f32::NAN]), PType::F32)] +#[case::f32_snan(PrimitiveArray::from_iter([1.0_f32, f32::from_bits(0x7f80_2000)]), PType::F32)] +#[case::f16_unchanged(PrimitiveArray::from_iter([f16::ONE, f16::NEG_ZERO]), PType::F16)] +#[case::empty_f64(PrimitiveArray::empty::(Nullability::NonNullable), PType::F16)] +#[case::empty_f32(PrimitiveArray::empty::(Nullability::Nullable), PType::F16)] +#[case::all_null_f64( + PrimitiveArray::new(buffer![0.1_f64, f64::from_bits(0x7ff0_0000_0000_0001)], Validity::AllInvalid), + PType::F16, +)] +#[case::null_payloads_ignored_and_zeroed( + PrimitiveArray::new( + buffer![0.1_f64, 1.5_f64, f64::from_bits(0x7ff0_0000_0000_0001)], + Validity::from_iter([false, true, false]), + ), + PType::F16, +)] +fn test_encode_float_selection( + #[case] input: PrimitiveArray, + #[case] expected_stored: PType, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let encoded = WidenArray::encode_float(input.clone(), &mut ctx)?; + + assert_eq!(stored_ptype(&encoded), expected_stored); + assert_eq!(encoded.dtype(), input.dtype()); + assert_arrays_eq!(encoded, input, &mut ctx); + + // Null slots in a narrowed child are zeroed so signaling NaNs cannot leak into the child. + if let Some(w) = encoded.as_opt::() + && w.values().dtype().as_ptype() == PType::F16 + && input.len() == 3 + { + let child = w.values().as_::(); + assert_eq!(child.as_slice::()[0].to_bits(), 0); + assert_eq!(child.as_slice::()[2].to_bits(), 0); + } + + Ok(()) +} + +#[test] +fn test_encode_float_rejects_integer() { + let mut ctx = SESSION.create_execution_ctx(); + let error = WidenArray::encode_float(PrimitiveArray::from_iter([1i32, 2, 3]), &mut ctx) + .expect_err("encode_float must reject integers"); + assert!(error.to_string().contains("floating-point"), "{error}"); +} + +#[test] +fn test_float_execute_encoded_dict_child() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let codes = buffer![2u8, 0, 1, 2].into_array(); + let values = DictArray::try_new( + codes.clone(), + buffer![-0.0_f32, 0.0_f32, 1.5_f32].into_array(), + )?; + let array = WidenArray::try_new(values.into_array(), PType::F64.into())?; + + let step = array + .clone() + .into_array() + .execute::(&mut ctx)? + .optimize_ctx(&SESSION)?; + assert!(step.is::()); + assert!(ArrayRef::ptr_eq(step.as_::().codes(), &codes)); + assert_eq!(step.dtype(), &DType::from(PType::F64)); + assert_arrays_eq!( + array, + PrimitiveArray::from_iter([1.5_f64, -0.0, 0.0, 1.5]), + &mut ctx + ); + + Ok(()) +} + +#[rstest] +#[case::non_nullable(widen(Buffer::from(f32_edge_values()), PType::F64).into_array())] +#[case::nullable( + widen( + PrimitiveArray::from_option_iter( + f32_edge_values() + .into_iter() + .enumerate() + .map(|(i, v)| (i % 4 != 1).then_some(v)) + ), + PType::F64, + ) + .into_array() +)] +#[case::all_invalid( + widen( + PrimitiveArray::new(Buffer::from(f32_edge_values()), Validity::AllInvalid), + PType::F64, + ) + .into_array() +)] +fn test_compare_f32_widen_to_f64_constants(#[case] array: ArrayRef) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let constants = [ + // Exact f32 values + f64::NEG_INFINITY, + f64::from(-f32::MAX), + -0.0_f64, + 0.0_f64, + f64::from(f32::from_bits(1)), + f64::from(0.1_f32), + 1.0_f64, + f64::from(f32::MAX), + f64::INFINITY, + // Strictly between adjacent f32 values, including beyond ±f32::MAX and inside ±min_sub + -1e100_f64, + f64::from(-f32::MAX).next_down(), + f64::from(-f32::MAX).next_up(), + -0.1_f64, + -1e-45_f64, + -1e-100_f64, + 1e-100_f64, + 1e-45_f64, + 0.1_f64, + f64::from(f32::MAX).next_down(), + f64::from(f32::MAX).next_up(), + 1e100_f64, + // NaN variants (fallback to canonical) + f64::NAN, + -f64::NAN, + f64::from_bits(0x7ff8_0000_0000_0001), + f64::from_bits(0x7ff0_0000_0000_0001), + f64::from_bits(0xfff8_0000_0000_0001), + ]; + + for c in constants { + for nullability in [Nullability::NonNullable, Nullability::Nullable] { + let rhs = + ConstantArray::new(Scalar::primitive(c, nullability), array.len()).into_array(); + for op in ALL_COMPARE_OPERATORS { + assert_compare_matches_canonical(&array, &rhs, op, &mut ctx)?; + } + } + } + + let null_rhs = ConstantArray::new( + Scalar::null(DType::Primitive(PType::F64, Nullability::Nullable)), + array.len(), + ) + .into_array(); + for op in ALL_COMPARE_OPERATORS { + assert_compare_matches_canonical(&array, &null_rhs, op, &mut ctx)?; + } + + Ok(()) +} + +#[test] +fn test_compare_f16_widen_constants_and_constant_folding() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let f16_to_f64 = widen(Buffer::from(f16_edge_values()), PType::F64).into_array(); + let f64_constants = [ + f64::NEG_INFINITY, + -1e10_f64, + f16::MIN.to_f64().next_down(), + f16::MIN.to_f64(), + f16::MIN.to_f64().next_up(), + -0.1_f64, + -1e-10_f64, + -0.0_f64, + 0.0_f64, + 1e-10_f64, + 0.1_f64, + f16::MAX.to_f64().next_down(), + f16::MAX.to_f64(), + f16::MAX.to_f64().next_up(), + 1e10_f64, + f64::INFINITY, + f64::NAN, + -f64::NAN, + ]; + for c in f64_constants { + let rhs = ConstantArray::new(c, f16_to_f64.len()).into_array(); + for op in ALL_COMPARE_OPERATORS { + assert_compare_matches_canonical(&f16_to_f64, &rhs, op, &mut ctx)?; + } + } + + let f16_to_f32 = widen(Buffer::from(f16_edge_values()), PType::F32).into_array(); + let f32_constants = [ + f32::NEG_INFINITY, + -1e10_f32, + f16::MIN.to_f32(), + -0.1_f32, + -1e-10_f32, + -0.0_f32, + 0.0_f32, + 1e-10_f32, + 0.1_f32, + f16::MAX.to_f32(), + 1e10_f32, + f32::INFINITY, + f32::NAN, + -f32::NAN, + ]; + for c in f32_constants { + let rhs = ConstantArray::new(c, f16_to_f32.len()).into_array(); + for op in ALL_COMPARE_OPERATORS { + assert_compare_matches_canonical(&f16_to_f32, &rhs, op, &mut ctx)?; + } + } + + Ok(()) +} + +#[test] +fn test_compare_two_float_widens() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let lhs = widen( + PrimitiveArray::from_option_iter([ + Some(-f16::NAN), + Some(f16::NEG_INFINITY), + Some(f16::NEG_ZERO), + Some(f16::ZERO), + Some(f16::ONE), + None, + Some(f16::INFINITY), + Some(f16::NAN), + ]), + PType::F64, + ) + .into_array(); + let rhs = widen( + PrimitiveArray::from_option_iter([ + Some(f32::NAN), + Some(f32::NEG_INFINITY), + Some(0.0_f32), + Some(-0.0_f32), + Some(1.0_f32), + Some(2.0_f32), + None, + Some(f32::NAN), + ]), + PType::F64, + ) + .into_array(); + + assert_eq!( + ptype_holding_both_values(lhs.as_::(), rhs.as_::()), + Some(PType::F32) + ); + for op in ALL_COMPARE_OPERATORS { + assert_compare_matches_canonical(&lhs, &rhs, op, &mut ctx)?; + } + + Ok(()) +} + +#[test] +fn test_float_cast_rules() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let f16_to_f64 = widen( + PrimitiveArray::from_option_iter([ + Some(f16::from_f32(-2.0)), + None, + Some(f16::from_f32(3.0)), + ]), + PType::F64, + ) + .into_array(); + + // Strictly wider float keeps Widen. + let to_f32 = f16_to_f64 + .cast(DType::Primitive(PType::F32, Nullability::Nullable))? + .optimize_ctx(&SESSION)?; + assert_eq!(stored_ptype(&to_f32), PType::F16); + assert_arrays_eq!( + to_f32, + canonical(&f16_to_f64, &mut ctx)? + .cast(DType::Primitive(PType::F32, Nullability::Nullable))?, + &mut ctx + ); + + // Same width as child unwraps Widen. + let to_f16 = f16_to_f64 + .cast(DType::Primitive(PType::F16, Nullability::Nullable))? + .optimize_ctx(&SESSION)?; + assert!(!to_f16.is::()); + assert_arrays_eq!( + to_f16, + canonical(&f16_to_f64, &mut ctx)? + .cast(DType::Primitive(PType::F16, Nullability::Nullable))?, + &mut ctx + ); + + // Float-to-int cast delegates to child and matches canonical. + let to_i32 = f16_to_f64 + .cast(DType::Primitive(PType::I32, Nullability::Nullable))? + .optimize_ctx(&SESSION)?; + assert_arrays_eq!( + to_i32, + canonical(&f16_to_f64, &mut ctx)? + .cast(DType::Primitive(PType::I32, Nullability::Nullable))?, + &mut ctx + ); + + // Float Widen (F32 -> F64) narrowed to F16 matches canonical f64 -> f16 rounding. + let f32_to_f64 = widen( + buffer![0.1_f32, -0.0_f32, 100_000.0_f32, f32::NAN], + PType::F64, + ) + .into_array(); + let to_f16 = f32_to_f64.cast(PType::F16.into())?; + let expected = canonical(&f32_to_f64, &mut ctx)?.cast(PType::F16.into())?; + assert_arrays_eq!(to_f16, expected, &mut ctx); + + // Out-of-range float-to-int fails just like canonical. + let big = widen(buffer![1e20_f32], PType::F64).into_array(); + assert!( + big.cast(PType::I32.into())? + .execute::(&mut ctx) + .is_err() + ); + + // Float-to-decimal fails just like canonical. + let dec = DType::Decimal(DecimalDType::new(18, 2), Nullability::NonNullable); + assert!( + f32_to_f64 + .cast(dec)? + .execute::(&mut ctx) + .is_err() + ); + + Ok(()) +} + +#[rstest] +#[case::fits_f16(Scalar::primitive(0.5_f64, Nullability::NonNullable), PType::F16)] +#[case::neg_zero(Scalar::primitive(-0.0_f64, Nullability::NonNullable), PType::F16)] +#[case::infinity(Scalar::primitive(f64::INFINITY, Nullability::NonNullable), PType::F16)] +#[case::quiet_nan(Scalar::primitive(f64::NAN, Nullability::NonNullable), PType::F16)] +#[case::needs_f32(Scalar::primitive(100_000.0_f64, Nullability::NonNullable), PType::F32)] +#[case::needs_f64(Scalar::primitive(0.1_f64, Nullability::NonNullable), PType::F64)] +#[case::snan_needs_f64( + Scalar::primitive(f64::from_bits(0x7ff0_0000_0000_0001), Nullability::NonNullable), + PType::F64 +)] +fn test_float_fill_null( + #[case] fill_value: Scalar, + #[case] expected_stored: PType, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = widen( + PrimitiveArray::from_option_iter([Some(f16::from_f32(-1.5)), None, Some(f16::ONE)]), + PType::F64, + ) + .into_array(); + + assert_eq!( + ptype_holding_values_and_scalar(array.as_::(), &fill_value), + Some(expected_stored) + ); + + let filled = array + .clone() + .fill_null(fill_value.clone())? + .optimize_ctx(&SESSION)?; + assert_eq!(stored_ptype(&filled), expected_stored); + let expected = canonical(&array, &mut ctx)?.fill_null(fill_value)?; + assert_arrays_eq!(filled, expected, &mut ctx); + + Ok(()) +} + +#[test] +fn test_ptype_holding_values_and_null_float_scalar() { + let array = widen( + PrimitiveArray::from_option_iter([Some(f16::from_f32(-1.5)), None, Some(f16::ONE)]), + PType::F64, + ); + let null_scalar = Scalar::null(DType::Primitive(PType::F64, Nullability::Nullable)); + assert_eq!( + ptype_holding_values_and_scalar(array.as_view(), &null_scalar), + Some(PType::F16) + ); +} + +#[test] +fn test_float_filter_mask_slice_take() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = widen( + PrimitiveArray::from_option_iter([ + Some(-0.0_f32), + None, + Some(1.5_f32), + Some(f32::INFINITY), + Some(f32::NAN), + ]), + PType::F64, + ) + .into_array(); + let expected_canonical = canonical(&array, &mut ctx)?; + + let filter_mask = Mask::from_iter([true, false, true, true, true]); + let filtered = array.filter(filter_mask.clone())?.optimize_ctx(&SESSION)?; + assert_eq!(stored_ptype(&filtered), PType::F32); + assert_arrays_eq!(filtered, expected_canonical.filter(filter_mask)?, &mut ctx); + + let keep_mask = BoolArray::from_iter([true, true, false, true, true]).into_array(); + let masked = array + .clone() + .mask(keep_mask.clone())? + .optimize_ctx(&SESSION)?; + assert_eq!(stored_ptype(&masked), PType::F32); + assert_arrays_eq!( + masked, + expected_canonical.clone().mask(keep_mask)?, + &mut ctx + ); + + let sliced = array.slice(1..4)?.optimize_ctx(&SESSION)?; + assert_eq!(stored_ptype(&sliced), PType::F32); + assert_arrays_eq!(sliced, expected_canonical.slice(1..4)?, &mut ctx); + + let indices = buffer![4u32, 0, 1, 3].into_array(); + let taken = array.take(indices.clone())?.execute::(&mut ctx)?; + assert_eq!(stored_ptype(&taken), PType::F32); + assert_arrays_eq!(taken, expected_canonical.take(indices)?, &mut ctx); + + Ok(()) +} + +#[test] +fn test_float_numeric_declines_and_preserves_f64_precision() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + // 16_777_216.0 + 1.0 loses precision in f32 (rounds to 16_777_216.0), and 1e20 * 1e20 overflows + // f32 to +inf, while both are exact/finite in f64. + let lhs = widen(buffer![16_777_216.0_f32, 1e20_f32], PType::F64).into_array(); + let rhs = widen(buffer![1.0_f32, 1e20_f32], PType::F64).into_array(); + + for op in [ + NumericOperator::Add, + NumericOperator::Sub, + NumericOperator::Mul, + NumericOperator::Div, + ] { + let actual = lhs.numeric(rhs.clone(), op)?; + let expected = canonical(&lhs, &mut ctx)?.numeric(canonical(&rhs, &mut ctx)?, op)?; + assert_arrays_eq!(actual, expected, &mut ctx); + } + + // Double-check the exact f64 result values didn't suffer f32 rounding/overflow. + let sum = lhs + .numeric(rhs.clone(), NumericOperator::Add)? + .execute::(&mut ctx)?; + assert_eq!(sum.as_slice::()[0], 16_777_217.0_f64); + let prod = lhs + .numeric(rhs, NumericOperator::Mul)? + .execute::(&mut ctx)?; + assert!(prod.as_slice::()[1].is_finite()); + + Ok(()) +} + +#[test] +fn test_float_aggregates_match_canonical_and_sum_declines() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let skip_nans = NumericalAggregateOpts::default(); + let include_nans = NumericalAggregateOpts { skip_nans: false }; + + let aggregates = [ + (MinMax.bind(skip_nans), true), + (MinMax.bind(include_nans), true), + (Min.bind(skip_nans), true), + (Min.bind(include_nans), true), + (Max.bind(skip_nans), true), + (Max.bind(include_nans), true), + (IsConstant.bind(EmptyOptions), true), + (IsSorted.bind(IsSortedOptions { strict: false }), true), + (IsSorted.bind(IsSortedOptions { strict: true }), true), + (Sum.bind(skip_nans), false), + (Sum.bind(include_nans), false), + (SumV2.bind(skip_nans), false), + ]; + + let fixtures = [ + widen(Buffer::from(f32_edge_values()), PType::F64).into_array(), + widen(buffer![-0.0_f32, 0.0_f32], PType::F64).into_array(), + widen(buffer![-0.0_f32, -0.0_f32], PType::F64).into_array(), + widen(buffer![0.0_f32, -0.0_f32], PType::F64).into_array(), + widen(buffer![f32::NAN, f32::NAN], PType::F64).into_array(), + widen( + buffer![ + 16_777_216.0_f32, + 1.0_f32, + 1.0_f32, + 1e38_f32, + 1e38_f32, + 1e38_f32, + 1e38_f32 + ], + PType::F64, + ) + .into_array(), + widen( + PrimitiveArray::from_option_iter([ + None, + Some(f16::NEG_ZERO), + Some(f16::ZERO), + Some(f16::ONE), + ]), + PType::F64, + ) + .into_array(), + widen( + PrimitiveArray::new(buffer![1.0_f32, 2.0_f32], Validity::AllInvalid), + PType::F64, + ) + .into_array(), + widen( + PrimitiveArray::empty::(Nullability::NonNullable), + PType::F32, + ) + .into_array(), + ]; + + for fixture in fixtures { + let canonical_fixture = canonical(&fixture, &mut ctx)?; + for (aggregate_fn, expected_served) in &aggregates { + let kernel_result = WidenArrayAggregate.aggregate(aggregate_fn, &fixture, &mut ctx)?; + assert_eq!( + kernel_result.is_some(), + *expected_served, + "unexpected kernel coverage for {aggregate_fn} on {}", + fixture.dtype() + ); + + let mut actual_acc = aggregate_fn.accumulator(fixture.dtype())?; + actual_acc.accumulate(&fixture, &mut ctx)?; + let actual = actual_acc.finish()?; + + let mut expected_acc = aggregate_fn.accumulator(canonical_fixture.dtype())?; + expected_acc.accumulate(&canonical_fixture, &mut ctx)?; + let expected = expected_acc.finish()?; + + assert_eq!(actual, expected, "mismatch for {aggregate_fn}"); + } + } + + // Multi-chunk IsSorted merges partial structs across float Widen chunks cleanly. + let chunk1 = widen(buffer![-0.0_f32, 0.0_f32], PType::F64).into_array(); + let chunk2 = widen(buffer![1.0_f32, 2.0_f32], PType::F64).into_array(); + let chunked = ChunkedArray::try_new(vec![chunk1, chunk2], PType::F64.into())?.into_array(); + let is_strict = IsSorted.bind(IsSortedOptions { strict: true }); + let mut acc = is_strict.accumulator(chunked.dtype())?; + acc.accumulate(&chunked, &mut ctx)?; + assert_eq!(acc.finish()?, Scalar::from(Some(true))); + + Ok(()) +} diff --git a/vortex-array/src/arrays/widen/tests/mod.rs b/vortex-array/src/arrays/widen/tests/mod.rs index ccb3ee03e25..872ce00972a 100644 --- a/vortex-array/src/arrays/widen/tests/mod.rs +++ b/vortex-array/src/arrays/widen/tests/mod.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Tests of the `Widen` encoding over integer and decimal values. +//! Tests of the `Widen` encoding over integer, floating-point, and decimal values. //! //! The named integer fixtures cover signed and unsigned values, each kind of validity and a single -//! row, and the `compute` tests run their operations over them. The `decimal` modules build their -//! own decimal fixtures, and compare each result with the result on the canonical array. +//! row, and the `compute` tests run their operations over them. The `decimal` and `float` modules +//! build their own fixtures and compare each result with the result on the canonical array. mod aggregates; mod compute; @@ -16,6 +16,7 @@ mod decimal_compare; mod decimal_fallback; mod decimal_stored; mod encoding; +mod float; mod integer_stored; mod numeric; mod serde; diff --git a/vortex-array/src/arrays/widen/tests/serde.rs b/vortex-array/src/arrays/widen/tests/serde.rs index 9aa3506f664..5d08b8bcb18 100644 --- a/vortex-array/src/arrays/widen/tests/serde.rs +++ b/vortex-array/src/arrays/widen/tests/serde.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Tests for the `Widen` wire formats. +//! Tests for the `Widen` wire format. //! //! A decimal leaf can use the `vortex.decimal` wire ID while preserving the values of the original //! `Widen`. The tests check the wire ID and the decoded values separately. @@ -43,6 +43,7 @@ use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::Nullability; use crate::dtype::PType; +use crate::dtype::half::f16; use crate::scalar::Scalar; use crate::serde::SerializeOptions; use crate::serde::SerializedArray; @@ -372,3 +373,116 @@ fn serialization_does_not_execute_validity() -> VortexResult<()> { Ok(()) } + +#[rstest] +#[case::f32_to_f64( + buffer![-0.0_f32, 0.0_f32, 1.5_f32, f32::INFINITY, f32::NAN].into_array(), + DType::from(PType::F64), + [8, PType::F32 as u8], +)] +#[case::f16_to_f64( + buffer![f16::NEG_ZERO, f16::ZERO, f16::ONE, f16::NEG_INFINITY, f16::NAN].into_array(), + DType::from(PType::F64), + [8, PType::F16 as u8], +)] +#[case::f16_to_f32_dict( + DictArray::try_new( + buffer![2u8, 0, 1, 2].into_array(), + buffer![f16::NEG_ZERO, f16::from_f32(1.5), f16::INFINITY].into_array(), + )?.into_array(), + DType::from(PType::F32), + [8, PType::F16 as u8], +)] +fn test_float_widen_wire_round_trip( + #[case] child: ArrayRef, + #[case] dtype: DType, + #[case] metadata: [u8; 2], +) -> VortexResult<()> { + let widen = widen_over(child.clone(), dtype)?; + let ctx = ArrayContext::empty(); + let serialized = SerializedArray::try_from(serialize_blob(&widen, &ctx, &SESSION)?)?; + let read_ctx = ReadContext::new(ctx.to_ids()); + + assert_eq!( + read_ctx.resolve(serialized.encoding_id()), + Some(ArrayVTable::id(&Widen)) + ); + assert_eq!(serialized.metadata(), metadata.as_slice()); + assert_eq!(serialized.nbuffers(), 0); + assert_eq!(serialized.nchildren(), 1); + + let decoded = serialized.decode(widen.dtype(), widen.len(), &read_ctx, &SESSION)?; + let decoded_widen = decoded.as_::(); + assert_eq!(decoded_widen.values().dtype(), child.dtype()); + assert_eq!(decoded_widen.values().encoding_id(), child.encoding_id()); + assert_arrays_eq!(decoded, widen, &mut SESSION.create_execution_ctx()); + + Ok(()) +} + +#[test] +fn test_float_widen_requires_permission() -> VortexResult<()> { + let widen = widen_over(buffer![1.0_f32, -0.0_f32], DType::from(PType::F64))?; + let without_widen = + ArrayContext::empty().with_allowed_ids([ArrayVTable::id(&Primitive)].into_iter().collect()); + let error = serialize_blob(&widen, &without_widen, &SESSION) + .expect_err("float Widen must require vortex.widen permission"); + assert!( + error.to_string().contains("vortex.widen not permitted"), + "{error}" + ); + + let with_widen = ArrayContext::empty().with_allowed_ids( + [ArrayVTable::id(&Primitive), ArrayVTable::id(&Widen)] + .into_iter() + .collect(), + ); + let serialized = SerializedArray::try_from(serialize_blob(&widen, &with_widen, &SESSION)?)?; + let read_ctx = ReadContext::new(with_widen.to_ids()); + let decoded = serialized.decode(widen.dtype(), widen.len(), &read_ctx, &SESSION)?; + assert_arrays_eq!(decoded, widen, &mut SESSION.create_execution_ctx()); + + Ok(()) +} + +#[rstest] +#[case::float_parent_int_child( + PType::F64.into(), + &[8, PType::I32 as u8], + "does not match the parent", +)] +#[case::int_parent_float_child( + PType::I64.into(), + &[8, PType::F32 as u8], + "does not match the parent", +)] +#[case::float_parent_decimal_tag( + PType::F64.into(), + &[16, 9], + "does not match the parent", +)] +#[case::float_same_width( + PType::F64.into(), + &[8, PType::F64 as u8], + "narrower", +)] +#[case::float_wider_child( + PType::F32.into(), + &[8, PType::F64 as u8], + "narrower", +)] +#[case::float_unknown_tag( + PType::F64.into(), + &[24, PType::F32 as u8], + "must name the child type", +)] +fn test_float_widen_wire_rejects_invalid_metadata( + #[case] dtype: DType, + #[case] metadata: &[u8], + #[case] expected_error: &str, +) { + let children = [buffer![1.0_f32].into_array()]; + let parts = + ArrayDeserialization::new(ArrayVTable::id(&Widen), &dtype, 1, metadata, &[], &children); + assert_widen_decode_error(parts, expected_error); +} diff --git a/vortex-array/src/arrays/widen/vtable/mod.rs b/vortex-array/src/arrays/widen/vtable/mod.rs index 2065646750f..48b8a3ea289 100644 --- a/vortex-array/src/arrays/widen/vtable/mod.rs +++ b/vortex-array/src/arrays/widen/vtable/mod.rs @@ -50,7 +50,7 @@ use crate::require_child; #[derive(Clone, Debug)] pub struct Widen; -/// A [`Widen`]-encoded integer or decimal array. +/// A [`Widen`]-encoded integer, floating-point, or decimal array. pub type WidenArray = Array; impl VTable for Widen { @@ -118,13 +118,15 @@ impl VTable for Widen { Ok(ExecutionResult::done(widened.into_array())) } DType::Primitive(..) => { - // Integer casts let the child's kernel decode and widen its values in one pass. + // Primitive casts let the child's kernel decode and widen its values in one pass. let widened = array.values().cast(array.dtype().clone())?; Ok(ExecutionResult::done(widened)) } dtype => { - vortex_panic!("Widen validation requires an integer or decimal dtype, got {dtype}") + vortex_panic!( + "Widen validation requires an integer, float, or decimal dtype, got {dtype}" + ) } } } diff --git a/vortex-array/src/arrays/widen/vtable/plugin.rs b/vortex-array/src/arrays/widen/vtable/plugin.rs index 2d429c27210..9043fcb32ef 100644 --- a/vortex-array/src/arrays/widen/vtable/plugin.rs +++ b/vortex-array/src/arrays/widen/vtable/plugin.rs @@ -12,9 +12,9 @@ //! same values, such as a statistic or an index. A child, buffer or metadata field that changes the //! decoded values needs a new ID. //! -//! A protobuf `oneof` supplies the rest of the child dtype. Tag 1 holds the integer [`PType`]. -//! Tag 2 holds the decimal precision as a `uint32`. The child dtype must meet the requirements -//! of [`WidenArray::try_new`]. +//! A protobuf `oneof` supplies the rest of the child dtype. Tag 1 holds the primitive (integer or +//! floating-point) [`PType`]. Tag 2 holds the decimal precision as a `uint32`. The child dtype +//! must meet the requirements of [`WidenArray::try_new`]. use prost::Message as _; use vortex_error::VortexResult; @@ -50,7 +50,7 @@ struct WidenMetadata { #[derive(Clone, prost::Oneof)] enum ChildType { #[prost(enumeration = "PType", tag = "1")] - Integer(i32), + Primitive(i32), #[prost(uint32, tag = "2")] DecimalPrecision(u32), } @@ -58,8 +58,8 @@ enum ChildType { /// Reads and writes serialized [`Widen`] arrays. /// /// Writing reuses the child without executing its values or validity. When the child is a -/// [`Decimal`] array, this plugin writes `vortex.decimal` so older readers can read it. The decimal -/// reader handles those nodes. +/// [`Decimal`] array, this plugin writes `vortex.decimal` so older readers can read it. Integer, +/// floating-point, and encoded decimal children use `vortex.widen`. #[derive(Clone, Debug)] pub struct WidenPlugin; @@ -93,11 +93,13 @@ impl ArrayPlugin for WidenPlugin { } let child_type = match values.dtype() { - DType::Primitive(ptype, _) if ptype.is_int() => ChildType::Integer(*ptype as i32), + DType::Primitive(ptype, _) if ptype.is_int() || ptype.is_float() => { + ChildType::Primitive(*ptype as i32) + } DType::Decimal(dtype, _) => ChildType::DecimalPrecision(u32::from(dtype.precision())), dtype => { vortex_bail!( - "Widen serialization requires an integer or decimal child, got {dtype}" + "Widen serialization requires an integer, float, or decimal child, got {dtype}" ) } }; @@ -131,8 +133,15 @@ impl ArrayPlugin for WidenPlugin { .ok_or_else(|| vortex_err!("Widen metadata must name the child type"))?; let nullability = parts.dtype.nullability(); let child_dtype = match (child_type, parts.dtype) { - (ChildType::Integer(ptype), DType::Primitive(parent, _)) if parent.is_int() => { - DType::Primitive(PType::try_from(ptype)?, nullability) + (ChildType::Primitive(ptype), DType::Primitive(parent, _)) => { + let child_ptype = PType::try_from(ptype)?; + vortex_ensure!( + (child_ptype.is_int() && parent.is_int()) + || (child_ptype.is_float() && parent.is_float()), + "Widen child metadata {child_ptype} does not match the parent dtype {}", + parts.dtype + ); + DType::Primitive(child_ptype, nullability) } (ChildType::DecimalPrecision(precision), DType::Decimal(parent, _)) => { let precision = u8::try_from(precision).map_err(|_| { diff --git a/vortex-btrblocks/src/builder.rs b/vortex-btrblocks/src/builder.rs index bddbc63ee7c..2dd7f2ba920 100644 --- a/vortex-btrblocks/src/builder.rs +++ b/vortex-btrblocks/src/builder.rs @@ -82,6 +82,10 @@ impl CompressionMode { integer::SparseScheme.id(), integer::IntRLEScheme.id(), float::FloatRLEScheme.id(), + // Float `Widen` has no GPU decode kernel: CUDA scans stage float `Widen` on + // host, so CUDA writers skip `FloatWidenScheme` while keeping `vortex.widen` + // allowed for integer `Widen` (used by `DecimalByteParts` MSP on CUDA). + float::FloatWidenScheme.id(), float::NullDominatedSparseScheme.id(), string::NullDominatedSparseScheme.id(), fixed_size_list::FixedSizeListSparseScheme.id(), @@ -120,7 +124,7 @@ impl CompressionMode { fn excluded_encodings(self) -> Vec { match self { Self::All | Self::Default | Self::Compact => Vec::new(), - // Multi-part DecimalByteParts arrays, FoR arrays with per-chunk references and + // Multi-part DecimalByteParts arrays, FoR arrays with per-chunk references, and // BitPacked arrays with per-block bit widths have no CUDA decode kernel. Self::Cuda => vec![decimal_byte_parts_v2_id(), for_v2_id(), bitpacked_v2_id()], } @@ -352,6 +356,7 @@ mod tests { use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBin; use vortex_array::arrays::VarBinViewArray; + use vortex_array::arrays::Widen; use vortex_array::assert_arrays_eq; use vortex_array::dtype::FieldNames; use vortex_array::validity::Validity; @@ -434,6 +439,16 @@ mod tests { vec![vortex_alp::ALPRD.id(), bitpacked_v1_id(), Constant.id()], true )] + #[case::float_widen_without_widen( + &float::FloatWidenScheme, + vec![], + false + )] + #[case::float_widen_with_widen( + &float::FloatWidenScheme, + vec![Widen.id()], + true + )] fn test_allowed_schemes( #[case] scheme: &'static dyn Scheme, #[case] allowed: Vec, @@ -772,4 +787,18 @@ mod tests { assert_arrays_eq!(compressed_nullable, nullable, &mut ctx); Ok(()) } + + #[test] + fn float_widen_is_excluded_by_cuda() { + let builder = BtrBlocksCompressorBuilder::from_session(&SESSION).unrestricted(); + let has_float_widen = |builder: BtrBlocksCompressorBuilder| { + builder + .allowed_schemes() + .iter() + .any(|s| s.id() == float::FloatWidenScheme.id()) + }; + assert!(has_float_widen(builder.clone())); + assert!(has_float_widen(builder.clone().with_compact())); + assert!(!has_float_widen(builder.only_cuda_compatible())); + } } diff --git a/vortex-btrblocks/src/schemes/float/mod.rs b/vortex-btrblocks/src/schemes/float/mod.rs index 5898d43e8c1..1a4f6bdd946 100644 --- a/vortex-btrblocks/src/schemes/float/mod.rs +++ b/vortex-btrblocks/src/schemes/float/mod.rs @@ -7,6 +7,7 @@ mod alp; mod alprd; mod rle; mod sparse; +mod widen; #[cfg(feature = "pco")] mod pco; @@ -20,6 +21,7 @@ pub use sparse::NullDominatedSparseScheme; // Re-export builtin schemes from vortex-compressor. pub use vortex_compressor::builtins::FloatDictScheme; pub use vortex_compressor::stats::FloatStats; +pub use widen::FloatWidenScheme; #[cfg(test)] mod tests { diff --git a/vortex-btrblocks/src/schemes/float/widen.rs b/vortex-btrblocks/src/schemes/float/widen.rs new file mode 100644 index 00000000000..72a41f38616 --- /dev/null +++ b/vortex-btrblocks/src/schemes/float/widen.rs @@ -0,0 +1,687 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Lossless floating-point width-narrowing scheme backed by [`WidenArray`]. +//! +//! Narrowing an `f64` column whose valid values all round-trip bit-for-bit through `f32` (or +//! narrowing `f64`/`f32` through `f16`) halves or quarters raw storage and lets child float +//! schemes such as `ALP` and `ALPRD` operate at the narrower width without losing a single bit. + +use std::sync::OnceLock; + +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::aggregate_fn::fns::uncompressed_size_in_bytes::uncompressed_size_in_bytes; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::Widen; +use vortex_array::arrays::WidenArray; +use vortex_array::arrays::widen::encode::narrow_float_values; +use vortex_array::arrays::widen::encode::narrowest_float_ptype; +use vortex_array::dtype::PType; +use vortex_compressor::sample_aligned_chunks; +use vortex_compressor::scheme::ChildSelection; +use vortex_compressor::scheme::CompressionEstimate; +use vortex_compressor::scheme::DeferredEstimate; +use vortex_compressor::scheme::DescendantExclusion; +use vortex_compressor::scheme::EstimateVerdict; +use vortex_error::VortexResult; +use vortex_mask::Mask; + +use crate::ArrayAndStats; +use crate::CascadingCompressor; +use crate::Child; +use crate::CompressorContext; +use crate::Encoded; +use crate::Scheme; +use crate::SchemeExt; +use crate::schemes::float::FloatDictScheme; +use crate::schemes::float::FloatRLEScheme; + +/// Cached narrowest fitting width computed during estimation so [`FloatWidenScheme::compress`] +/// avoids re-scanning the full array. +#[derive(Debug, Clone, Copy)] +struct NarrowestFloatTarget(Option); + +/// Cached full-array compressed output from estimation when the array is too short to sample, +/// reused directly by [`FloatWidenScheme::compress`] to avoid compressing the array twice. +struct CachedFullWiden(OnceLock); + +const SAMPLE_CHUNK_LEN: usize = 1024; +const SAMPLE_CHUNK_COUNT: u32 = 2; + +fn compress_with_target( + compressor: &CascadingCompressor, + primitive: &PrimitiveArray, + mask: &Mask, + narrowest: PType, + compress_ctx: CompressorContext, + exec_ctx: &mut ExecutionCtx, +) -> VortexResult { + // When an `f64` array fits both `f16` and `f32`, compare both compressed children because + // `ALP` and `ALPRD` skip `f16` and may compress `f32` smaller than raw `f16`. + let candidates: &[PType] = match (primitive.ptype(), narrowest) { + (PType::F64, PType::F16) if !compress_ctx.finished_cascading() => &[PType::F16, PType::F32], + _ => &[narrowest], + }; + + let mut best: Option = None; + for &target in candidates { + let narrowed = narrow_float_values(primitive, target, mask)?; + let logical_dtype = primitive.dtype().clone(); + let encoded = Encoded::new( + vec![Child::new(&FloatWidenScheme, 0, narrowed.into_array())], + Vec::new(), + move |children, _| { + let [values] = children.compressed()?; + Ok(WidenArray::try_new(values, logical_dtype)?.into_array()) + }, + ); + let candidate = + compressor.compress_encoded(FloatWidenScheme.id(), encoded, &compress_ctx, exec_ctx)?; + if best + .as_ref() + .is_none_or(|current| candidate.nbytes() < current.nbytes()) + { + best = Some(candidate); + } + } + + Ok(best.unwrap_or_else(|| primitive.clone().into_array())) +} + +/// Lossless floating-point narrowing scheme (`f64 -> f32/f16`, `f32 -> f16`). +/// +/// Produces `vortex.widen` wire nodes, which belong to the `preview2026.11.0` edition; builders +/// whose allowed encodings do not include `vortex.widen` (or CUDA presets) drop this scheme. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct FloatWidenScheme; + +impl Scheme for FloatWidenScheme { + fn scheme_name(&self) -> &'static str { + "vortex.float.widen" + } + + fn matches(&self, canonical: &Canonical) -> bool { + canonical.dtype().is_float() + } + + fn produced_encodings(&self) -> Vec { + vec![Widen.id()] + } + + /// Children: narrowed values = 0. + fn num_children(&self) -> usize { + 1 + } + + /// Keep `Dict` and `RLE` at the root rather than under `Widen`. + /// + /// Leaving `Dict` at the root preserves DuckDB exporter and dict-layout fast paths; `Dict` + /// and `RLE` still compress their values children through `FloatWidenScheme` when beneficial. + fn descendant_exclusions(&self) -> Vec { + vec![ + DescendantExclusion { + excluded: FloatDictScheme.id(), + children: ChildSelection::All, + }, + DescendantExclusion { + excluded: FloatRLEScheme.id(), + children: ChildSelection::All, + }, + ] + } + + fn expected_compression_ratio( + &self, + data: &ArrayAndStats, + compress_ctx: CompressorContext, + exec_ctx: &mut ExecutionCtx, + ) -> CompressionEstimate { + let primitive = data.array_as_primitive().into_owned(); + let ptype = primitive.ptype(); + if ptype == PType::F16 || primitive.is_empty() { + return CompressionEstimate::Verdict(EstimateVerdict::Skip); + } + + let Ok(mask) = primitive + .validity() + .and_then(|v| v.execute_mask(primitive.len(), exec_ctx)) + else { + return CompressionEstimate::Verdict(EstimateVerdict::Skip); + }; + if matches!(mask, Mask::AllFalse(_)) { + return CompressionEstimate::Verdict(EstimateVerdict::Skip); + } + + // `narrowest_float_ptype` exits on the first non-fitting 64-element chunk for general + // columns and confirms 100% full-array bit-exact fit before returning a target. + let Some(narrowest) = data + .get_or_insert_with(|| NarrowestFloatTarget(narrowest_float_ptype(&primitive, &mask))) + .0 + else { + return CompressionEstimate::Verdict(EstimateVerdict::Skip); + }; + + // When the cascade budget is exhausted, `compress_child` leaves the narrowed primitive + // values uncompressed, so the exact ratio is known without sampling. + if compress_ctx.finished_cascading() { + let Ok(before) = uncompressed_size_in_bytes(data.array(), exec_ctx) else { + return CompressionEstimate::Verdict(EstimateVerdict::Skip); + }; + let before = before as u64; + let validity_bytes = before.saturating_sub( + u64::try_from(primitive.len() * ptype.byte_width()).unwrap_or(before), + ); + let after = u64::try_from(primitive.len() * narrowest.byte_width()) + .unwrap_or(before) + .saturating_add(validity_bytes); + if after == 0 { + return CompressionEstimate::Verdict(EstimateVerdict::Skip); + } + return CompressionEstimate::Verdict(EstimateVerdict::Ratio( + before as f64 / after as f64, + )); + } + + // Use a callback so the sampled estimate reuses the full-array `narrowest` target rather + // than re-deriving a narrower target (such as `f16`) from a sample that misses an + // `f32`-only outlier. + CompressionEstimate::Deferred(DeferredEstimate::Callback(Box::new( + move |compressor, data, _best_so_far, compress_ctx, exec_ctx| { + let (sample, sample_ctx, is_full_array) = + match sample_aligned_chunks(data.array(), SAMPLE_CHUNK_LEN, SAMPLE_CHUNK_COUNT) + { + Some(sample) => (sample, compress_ctx.with_sampling(), false), + None => (data.array().clone(), compress_ctx, true), + }; + let sample_before = uncompressed_size_in_bytes(&sample, exec_ctx)?; + if sample_before == 0 { + return Ok(EstimateVerdict::Skip); + } + let sample_primitive = sample.execute::(exec_ctx)?; + let sample_mask = sample_primitive + .validity()? + .execute_mask(sample_primitive.len(), exec_ctx)?; + if matches!(sample_mask, Mask::AllFalse(_)) { + return Ok(EstimateVerdict::Skip); + } + let compressed = compress_with_target( + compressor, + &sample_primitive, + &sample_mask, + narrowest, + sample_ctx, + exec_ctx, + )?; + let sample_after = compressed.nbytes(); + if is_full_array { + drop( + data.get_or_insert_with(|| CachedFullWiden(OnceLock::new())) + .0 + .set(compressed), + ); + } + if sample_after == 0 { + return Ok(EstimateVerdict::Skip); + } + Ok(EstimateVerdict::Ratio( + sample_before as f64 / sample_after as f64, + )) + }, + ))) + } + + fn compress( + &self, + compressor: &CascadingCompressor, + data: &ArrayAndStats, + compress_ctx: CompressorContext, + exec_ctx: &mut ExecutionCtx, + ) -> VortexResult { + if let Some(cached) = data + .get_or_insert_with(|| CachedFullWiden(OnceLock::new())) + .0 + .get() + { + return Ok(cached.clone()); + } + + let primitive = data.array_as_primitive().into_owned(); + let mask = primitive + .validity()? + .execute_mask(primitive.len(), exec_ctx)?; + let Some(narrowest) = data + .get_or_insert_with(|| NarrowestFloatTarget(narrowest_float_ptype(&primitive, &mask))) + .0 + else { + return Ok(data.array().clone()); + }; + + compress_with_target( + compressor, + &primitive, + &mask, + narrowest, + compress_ctx, + exec_ctx, + ) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::LazyLock; + + use rstest::rstest; + use vortex_array::ArrayContext; + use vortex_array::ArrayRef; + use vortex_array::ExecutionCtx; + use vortex_array::IntoArray; + use vortex_array::VTable; + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::Primitive; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::Widen; + use vortex_array::arrays::widen::WidenArraySlotsExt; + use vortex_array::assert_arrays_eq; + use vortex_array::dtype::PType; + use vortex_array::dtype::half::f16; + 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::FloatWidenScheme; + use crate::BtrBlocksCompressor; + use crate::BtrBlocksCompressorBuilder; + use crate::ChildDecision; + use crate::ChildPolicy; + use crate::ChildRequest; + use crate::CompressionSession; + use crate::SchemeExt; + use crate::schemes::float::ALPRDScheme; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty().with::(); + vortex_array::initialize(&session); + session + }); + + fn unrestricted_compressor() -> BtrBlocksCompressor { + BtrBlocksCompressorBuilder::from_session(&SESSION) + .unrestricted() + .build() + } + + /// Deterministic pseudorandom f32-exact values widened to f64 (modeled after OpenAI embeddings + /// stored as f64) so ALP cannot exploit small decimal scale and ALPRD+Widen wins decisively. + fn pseudo_random_f32_in_f64(len: usize) -> Vec { + let mut state = 0x9e37_79b9_7f4a_7c15u64; + (0..len) + .map(|_| { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1); + let u = ((state >> 40) as f32) / ((1u32 << 24) as f32) - 0.5_f32; + f64::from(u) + }) + .collect() + } + + /// Deterministic diverse finite f16 bit patterns. + fn pseudo_random_f16(len: usize) -> Vec { + let mut state = 0x1234_5678u32; + (0..len) + .map(|_| { + state = state.wrapping_mul(1664525).wrapping_add(1013904223); + let exp = u16::try_from((state >> 24) % 28 + 1).unwrap_or(1); + let mant = (state & 0x03ff) as u16; + let sign = ((state >> 31) as u16) << 15; + f16::from_bits(sign | (exp << 10) | mant) + }) + .collect() + } + + fn assert_bit_exact_f64( + actual: &ArrayRef, + expected: &PrimitiveArray, + ctx: &mut ExecutionCtx, + ) -> VortexResult<()> { + let actual_prim = actual.clone().execute::(ctx)?; + assert_arrays_eq!(actual_prim, expected, ctx); + let mask = expected.validity()?.execute_mask(expected.len(), ctx)?; + let actual_slice = actual_prim.as_slice::(); + let expected_slice = expected.as_slice::(); + for i in 0..expected.len() { + if mask.value(i) { + assert_eq!( + actual_slice[i].to_bits(), + expected_slice[i].to_bits(), + "bit mismatch at row {i}" + ); + } + } + Ok(()) + } + + #[test] + fn compresses_f32_exact_f64_with_widen() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = pseudo_random_f32_in_f64(8192); + let input = PrimitiveArray::from_iter(values); + + let without_widen = BtrBlocksCompressorBuilder::from_session(&SESSION) + .unrestricted() + .exclude_schemes([FloatWidenScheme.id()]) + .build() + .compress(&input.clone().into_array(), &mut ctx)?; + let with_widen = + unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; + + assert!( + with_widen.is::(), + "expected Widen at root, got {}", + with_widen.encoding_id() + ); + assert_eq!( + with_widen.as_::().values().dtype().as_ptype(), + PType::F32 + ); + assert!( + with_widen.nbytes() < without_widen.nbytes(), + "expected Widen to compress smaller, got {} vs {}", + with_widen.nbytes(), + without_widen.nbytes() + ); + assert_bit_exact_f64(&with_widen, &input, &mut ctx)?; + + Ok(()) + } + + #[test] + fn compresses_f16_exact_f64_choosing_best_narrow_width() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values: Vec = pseudo_random_f16(4096) + .into_iter() + .map(f16::to_f64) + .collect(); + let input = PrimitiveArray::from_iter(values); + + let compressed = + unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; + assert!( + compressed.is::(), + "expected Widen at root, got {}", + compressed.encoding_id() + ); + assert_eq!( + compressed.as_::().values().dtype().as_ptype(), + PType::F16 + ); + assert_bit_exact_f64(&compressed, &input, &mut ctx)?; + + Ok(()) + } + + #[test] + fn preserves_neg_zero_and_canonical_nan_bits() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let mut values = pseudo_random_f32_in_f64(4096); + values[0] = -0.0_f64; + values[1] = 0.0_f64; + values[2] = f64::INFINITY; + values[3] = f64::NEG_INFINITY; + values[4] = f64::NAN; + let input = PrimitiveArray::from_iter(values); + + let compressed = + unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; + assert!(compressed.is::()); + assert_bit_exact_f64(&compressed, &input, &mut ctx)?; + + Ok(()) + } + + #[test] + fn skips_non_f32_outlier_and_still_compresses_normally() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let mut values = pseudo_random_f32_in_f64(16_384); + values[100] = 0.1_f64; + let input = PrimitiveArray::from_iter(values); + + let compressed = + unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; + assert!(!compressed.is::()); + // Must still compress with ALPRD rather than bailing out to uncompressed Primitive. + assert!( + compressed.nbytes() < input.nbytes(), + "expected fallback float scheme to compress, got {} vs {}", + compressed.nbytes(), + input.nbytes() + ); + assert_bit_exact_f64(&compressed, &input, &mut ctx)?; + + Ok(()) + } + + #[test] + fn skips_signaling_and_negative_nan() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + for nan in [f64::from_bits(0x7ff0_0000_2000_0000), -f64::NAN] { + let mut values = pseudo_random_f32_in_f64(4096); + values[77] = nan; + let input = PrimitiveArray::from_iter(values); + + let compressed = + unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; + assert!(!compressed.is::()); + assert_bit_exact_f64(&compressed, &input, &mut ctx)?; + } + + Ok(()) + } + + #[test] + fn ignores_non_f32_null_garbage() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let mut values = pseudo_random_f32_in_f64(4096); + let mut valid = vec![true; values.len()]; + for i in (0..values.len()).step_by(13) { + values[i] = 0.1_f64; + valid[i] = false; + } + let input = PrimitiveArray::new(Buffer::from(values), Validity::from_iter(valid)); + + let compressed = + unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; + assert!(compressed.is::()); + assert_bit_exact_f64(&compressed, &input, &mut ctx)?; + + Ok(()) + } + + #[test] + fn compresses_f16_exact_f32_to_f16_widen() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values: Vec = pseudo_random_f16(4096) + .into_iter() + .map(f16::to_f32) + .collect(); + let input = PrimitiveArray::from_iter(values); + + let compressed = + unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; + assert!(compressed.is::()); + assert_eq!( + compressed.as_::().values().dtype().as_ptype(), + PType::F16 + ); + assert_arrays_eq!(compressed, input, &mut ctx); + + Ok(()) + } + + #[test] + fn f32_outlier_outside_sample_uses_f32_target() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let mut values: Vec = pseudo_random_f16(16_384) + .into_iter() + .map(f16::to_f64) + .collect(); + // Append an f32-exact, non-f16 outlier in the partial trailing chunk, which + // `sample_aligned_chunks` never samples. + values.push(f64::from(100_000.25_f32)); + let input = PrimitiveArray::from_iter(values); + + let compressed = + unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; + assert!(compressed.is::()); + assert_eq!( + compressed.as_::().values().dtype().as_ptype(), + PType::F32 + ); + assert_bit_exact_f64(&compressed, &input, &mut ctx)?; + + Ok(()) + } + + #[test] + fn uniform_sampled_prefix_does_not_crowd_out_better_scheme() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let mut values = vec![1.0_f32; 11_264]; + values.extend(std::iter::repeat_n(2.0_f32, 1_023)); + let input = PrimitiveArray::from_iter(values); + + let compressed = + unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; + assert!( + !compressed.is::(), + "expected RLE or Dict to beat Widen on two-run column, got {} ({} bytes)", + compressed.encoding_id(), + compressed.nbytes(), + ); + assert_arrays_eq!(compressed, input, &mut ctx); + + Ok(()) + } + + #[test] + fn all_null_sample_does_not_crowd_out_better_scheme() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let values = std::iter::repeat_n(None::, 3_072) + .chain(std::iter::repeat_n(Some(1.0_f32), 511)) + .chain(std::iter::repeat_n(Some(2.0_f32), 512)); + let input = PrimitiveArray::from_option_iter(values); + + let compressed = + unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; + assert!( + !compressed.is::() && !compressed.is::(), + "expected Sparse/RLE/Dict to beat Widen when sampled chunks are all null, got {} ({} bytes)", + compressed.encoding_id(), + compressed.nbytes(), + ); + assert_arrays_eq!(compressed, input, &mut ctx); + + Ok(()) + } + + #[test] + fn test_short_column_uses_cached_full_widen() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let input = PrimitiveArray::from_iter(pseudo_random_f32_in_f64(512)); + + let compressed = + unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; + assert!(compressed.is::()); + assert_eq!( + compressed.as_::().values().dtype().as_ptype(), + PType::F32 + ); + assert_bit_exact_f64(&compressed, &input, &mut ctx)?; + + Ok(()) + } + + #[test] + fn wire_round_trip_uses_widen_id() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let input = PrimitiveArray::from_iter(pseudo_random_f32_in_f64(4096)); + let compressed = BtrBlocksCompressorBuilder::empty() + .with_new_scheme(&FloatWidenScheme) + .build() + .compress(&input.clone().into_array(), &mut ctx)?; + assert!(compressed.is::()); + + let array_ctx = ArrayContext::empty(); + let mut blob = ByteBufferMut::empty(); + for buf in compressed.serialize(&array_ctx, &SESSION, &SerializeOptions::default())? { + blob.extend_from_slice(buf.as_ref()); + } + let ids = array_ctx.to_ids(); + assert!( + ids.contains(&Widen.id()), + "expected vortex.widen in {ids:?}" + ); + + let serialized = SerializedArray::try_from(blob.freeze())?; + let decoded = serialized.decode( + compressed.dtype(), + compressed.len(), + &ReadContext::new(ids), + &SESSION, + )?; + assert_bit_exact_f64(&decoded, &input, &mut ctx)?; + + Ok(()) + } + + #[derive(Debug)] + struct KeepAllChildren; + + impl ChildPolicy for KeepAllChildren { + fn decide(&self, _request: &ChildRequest<'_>) -> ChildDecision { + ChildDecision::Keep + } + } + + #[rstest] + #[case::cascades_without_policy(false)] + #[case::keeps_canonical_child_with_policy(true)] + fn honors_child_policy(#[case] keep: bool) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let input = PrimitiveArray::from_iter(pseudo_random_f32_in_f64(4096)); + let mut builder = BtrBlocksCompressorBuilder::empty() + .with_new_scheme(&FloatWidenScheme) + .with_new_scheme(&ALPRDScheme); + if keep { + builder = builder.with_child_policy(Arc::new(KeepAllChildren)); + } + + let compressed = builder + .build() + .compress(&input.clone().into_array(), &mut ctx)?; + assert!( + compressed.is::(), + "expected Widen at root, got {}", + compressed.encoding_id() + ); + let child = compressed.as_::().values(); + assert_eq!( + child.is_canonical(), + keep, + "expected child canonical={keep}, got {}", + child.encoding_id() + ); + assert_bit_exact_f64(&compressed, &input, &mut ctx)?; + + Ok(()) + } +} diff --git a/vortex-btrblocks/src/session.rs b/vortex-btrblocks/src/session.rs index b73a72583b5..41128bd857e 100644 --- a/vortex-btrblocks/src/session.rs +++ b/vortex-btrblocks/src/session.rs @@ -81,6 +81,7 @@ impl Default for CompressionSession { &float::FloatDictScheme, &float::NullDominatedSparseScheme, &float::FloatRLEScheme, + &float::FloatWidenScheme, #[cfg(feature = "pco")] &float::PcoScheme, //////////////////////////////////////////////////////////////////////////////////// diff --git a/vortex-compressor/src/scheme/ctx.rs b/vortex-compressor/src/scheme/ctx.rs index e52c04c5981..557c74a8bcd 100644 --- a/vortex-compressor/src/scheme/ctx.rs +++ b/vortex-compressor/src/scheme/ctx.rs @@ -101,7 +101,11 @@ impl CompressorContext { } /// Returns a context marked as sample compression. - pub(crate) fn with_sampling(mut self) -> Self { + /// + /// Schemes that estimate ratios via [`DeferredEstimate::Callback`](crate::scheme::DeferredEstimate::Callback) + /// on a sampled subset must mark the context before compressing sample children so the + /// compressor does not treat a uniform sample as a constant column. + pub fn with_sampling(mut self) -> Self { self.is_sample = true; self } diff --git a/vortex-cuda/src/kernel/encodings/widen/mod.rs b/vortex-cuda/src/kernel/encodings/widen/mod.rs index 1f130eb8e02..9d63fc75605 100644 --- a/vortex-cuda/src/kernel/encodings/widen/mod.rs +++ b/vortex-cuda/src/kernel/encodings/widen/mod.rs @@ -12,9 +12,11 @@ use async_trait::async_trait; use tracing::instrument; use vortex::array::ArrayRef; use vortex::array::Canonical; +use vortex::array::IntoArray; use vortex::array::arrays::DecimalArray; use vortex::array::arrays::PrimitiveArray; use vortex::array::arrays::Widen; +use vortex::array::arrays::WidenArray; use vortex::array::arrays::widen::WidenArraySlotsExt; use vortex::array::buffer::BufferHandle; use vortex::array::match_each_integer_ptype; @@ -26,6 +28,7 @@ use vortex::error::vortex_err; use vortex_cuda_driver::DeviceRepr; use vortex_cuda_driver::PushKernelArg; +use crate::CanonicalCudaExt; use crate::CudaBufferExt; use crate::CudaDeviceBuffer; use crate::CudaExecutionCtx; @@ -52,9 +55,18 @@ impl CudaExecute for WidenExecutor { ) })?; let child = array.values().clone().execute_cuda(ctx).await?; + if array.dtype().is_float() { + let host_child = child.into_host(ctx.execution_ctx()).await?.into_array(); + let host_widen = WidenArray::try_new(host_child, array.dtype().clone())?; + return host_widen + .into_array() + .execute::(ctx.execution_ctx()); + } match (array.dtype(), child) { - (DType::Primitive(output_ptype, _), Canonical::Primitive(child)) => { + (DType::Primitive(output_ptype, _), Canonical::Primitive(child)) + if output_ptype.is_int() && child.ptype().is_int() => + { let len = child.len(); let parts = child.into_data_parts(); let values = ctx.ensure_on_device(parts.buffer)?; diff --git a/vortex-cuda/src/kernel/encodings/widen/tests.rs b/vortex-cuda/src/kernel/encodings/widen/tests.rs index 0f1c8f353d1..e62f2e92fee 100644 --- a/vortex-cuda/src/kernel/encodings/widen/tests.rs +++ b/vortex-cuda/src/kernel/encodings/widen/tests.rs @@ -10,8 +10,10 @@ use vortex::array::Canonical; use vortex::array::IntoArray; use vortex::array::arrays::DecimalArray; use vortex::array::arrays::PrimitiveArray; +use vortex::array::arrays::Widen; use vortex::array::arrays::WidenArray; use vortex::array::arrays::decimal::DecimalArrayExt; +use vortex::array::arrays::widen::WidenArraySlotsExt; use vortex::array::assert_arrays_eq; use vortex::array::buffer::BufferHandle; use vortex::array::buffer::DeviceBuffer; @@ -245,3 +247,30 @@ async fn test_kernel_boundaries(#[case] len: usize) -> VortexResult<()> { check_widen(child, device_child, PType::I64.into(), &mut ctx).await } + +#[rstest] +#[crate::test] +async fn test_float_host_fallback( + #[values(false, true)] nullable: bool, + #[values(CudaDispatchMode::Auto, CudaDispatchMode::StandaloneOnly)] mode: CudaDispatchMode, +) -> VortexResult<()> { + let values = Buffer::from_iter([0.0_f64, -0.0, 1.5, f64::NAN, -42.25, 100_000.0]); + let input = PrimitiveArray::new(values, validity(nullable, 6)); + let expected = input.clone().into_array(); + let mut ctx = CudaSession::create_execution_ctx(&cuda_session())?.with_dispatch_mode(mode); + let encoded = WidenArray::encode_float(input, ctx.execution_ctx())?; + let widen = encoded + .as_opt::() + .expect("f64 array fits losslessly in f32"); + assert_eq!(widen.values().dtype().as_ptype(), PType::F32); + + let device_child = upload(widen.values().clone(), &mut ctx).await?; + let device = WidenArray::try_new(device_child, widen.dtype().clone())?.into_array(); + assert!(!device.is_host()); + + let result = device.execute_cuda(&mut ctx).await?; + let actual = result.into_host(ctx.execution_ctx()).await?.into_array(); + assert_arrays_eq!(actual, expected, ctx.execution_ctx()); + + Ok(()) +} diff --git a/vortex-functions/src/zip/widen.rs b/vortex-functions/src/zip/widen.rs index fb1631e2663..48eb282f9ca 100644 --- a/vortex-functions/src/zip/widen.rs +++ b/vortex-functions/src/zip/widen.rs @@ -70,6 +70,7 @@ mod tests { use vortex_array::dtype::DecimalDType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; + use vortex_array::dtype::half::f16; use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexExpect; @@ -209,4 +210,93 @@ mod tests { Ok(()) } + + /// Nullable `f64` values stored in an `f16` `Widen`, including `-0.0`, canonical `NaN`, and nulls. + fn float_widen_f16() -> WidenArray { + let values = [ + Some(f16::from_f32(-0.0)), + None, + Some(f16::from_f32(1.5)), + Some(f16::NAN), + None, + Some(f16::from_f32(-4.0)), + ]; + widen(PrimitiveArray::from_option_iter(values), PType::F64) + } + + #[rstest] + #[case::widen_both( + float_widen_f16().into_array(), + widen(buffer![100_000.0_f32, -0.0, 2.5, 3.0, 4.0, -5.0], PType::F64).into_array(), + PType::F32, + )] + #[case::constant_fits_f16( + float_widen_f16().into_array(), + ConstantArray::new(2.5_f64, 6).into_array(), + PType::F16, + )] + #[case::constant_fits_f32( + float_widen_f16().into_array(), + ConstantArray::new(100_000.0_f64, 6).into_array(), + PType::F32, + )] + #[case::constant_requires_f64( + float_widen_f16().into_array(), + ConstantArray::new(0.1_f64, 6).into_array(), + PType::F64, + )] + #[case::constant_non_canonical_nan( + float_widen_f16().into_array(), + ConstantArray::new(f64::from_bits(0x7ff8_0000_0000_0001), 6).into_array(), + PType::F64, + )] + fn test_float_zip( + #[case] if_true: ArrayRef, + #[case] if_false: ArrayRef, + #[case] expected_stored: PType, + ) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + // Row 1 has a null mask (taking `if_false`) and row 4 selects a null from the `if_true` + // `Widen` branch. + let mask = BoolArray::from_iter([ + Some(true), + None, + Some(false), + Some(true), + Some(true), + Some(false), + ]) + .into_array(); + + let zipped = mask + .zip(if_true.clone(), if_false.clone())? + .execute::(&mut ctx)?; + + assert_eq!(stored_ptype(&zipped), expected_stored); + let expected = mask.zip( + canonical(&if_true, &mut ctx)?, + canonical(&if_false, &mut ctx)?, + )?; + assert_arrays_eq!(zipped, expected, &mut ctx); + + // Verify `-0.0` sign bit and NaN payload are preserved bit-for-bit on valid lanes, and + // that the selected null row from `if_true` remains null. + let actual_prim = zipped.execute::(&mut ctx)?; + let expected_prim = expected.execute::(&mut ctx)?; + let valid = expected_prim + .validity()? + .execute_mask(expected_prim.len(), &mut ctx)?; + assert!(!valid.value(4), "row 4 must select the null from if_true"); + for i in 0..expected_prim.len() { + if valid.value(i) { + assert_eq!( + actual_prim.as_slice::()[i].to_bits(), + expected_prim.as_slice::()[i].to_bits(), + "bit mismatch at row {i}", + ); + } + } + + Ok(()) + } } From 5b316a195ecbcab9cfc11b7a4cca0ee82a3841e5 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Thu, 26 Nov 2026 04:14:30 +0000 Subject: [PATCH 2/6] Cache winning float Widen target and tighten serde/scheme tests Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-array/src/arrays/widen/tests/serde.rs | 148 +++----------- vortex-btrblocks/src/schemes/float/widen.rs | 203 +++++++++---------- 2 files changed, 127 insertions(+), 224 deletions(-) diff --git a/vortex-array/src/arrays/widen/tests/serde.rs b/vortex-array/src/arrays/widen/tests/serde.rs index 5d08b8bcb18..00fb58512bd 100644 --- a/vortex-array/src/arrays/widen/tests/serde.rs +++ b/vortex-array/src/arrays/widen/tests/serde.rs @@ -234,6 +234,24 @@ fn serialization_keeps_parent_statistics() -> VortexResult<()> { DType::Decimal(DecimalDType::new(38, 2), Nullability::Nullable), [16, 9], )] +#[case::f32_to_f64( + buffer![-0.0_f32, 0.0_f32, 1.5_f32, f32::INFINITY, f32::NAN].into_array(), + DType::from(PType::F64), + [8, 9], // Field 1, PType::F32 = 9. +)] +#[case::f16_to_f64( + buffer![f16::NEG_ZERO, f16::ZERO, f16::ONE, f16::NEG_INFINITY, f16::NAN].into_array(), + DType::from(PType::F64), + [8, 8], // Field 1, PType::F16 = 8. +)] +#[case::f16_to_f32_dict( + DictArray::try_new( + buffer![2u8, 0, 1, 2].into_array(), + buffer![f16::NEG_ZERO, f16::from_f32(1.5), f16::INFINITY].into_array(), + )?.into_array(), + DType::from(PType::F32), + [8, 8], // Field 1, PType::F16 = 8. +)] fn test_widen_wire_round_trip( #[case] child: ArrayRef, #[case] dtype: DType, @@ -262,9 +280,14 @@ fn test_widen_wire_round_trip( Ok(()) } -#[test] -fn test_widen_wire_id_requires_permission() -> VortexResult<()> { - let widen = widen_over(buffer![1i8, 2, 3], DType::from(PType::I64))?; +#[rstest] +#[case::int(buffer![1i8, 2, 3].into_array(), DType::from(PType::I64))] +#[case::float(buffer![1.0_f32, -0.0_f32].into_array(), DType::from(PType::F64))] +fn test_widen_wire_id_requires_permission( + #[case] child: ArrayRef, + #[case] dtype: DType, +) -> VortexResult<()> { + let widen = widen_over(child, dtype)?; let restricted = ArrayContext::empty().with_allowed_ids([ArrayVTable::id(&Primitive)].into_iter().collect()); let error = serialize_blob(&widen, &restricted, &SESSION) @@ -293,6 +316,12 @@ fn test_widen_wire_id_requires_permission() -> VortexResult<()> { &[16, 1], "scale", )] +#[case::float_parent_int_child(PType::F64.into(), &[8, 6], "does not match the parent")] +#[case::int_parent_float_child(PType::I64.into(), &[8, 9], "does not match the parent")] +#[case::float_parent_decimal_tag(PType::F64.into(), &[16, 9], "does not match the parent")] +#[case::float_same_width(PType::F64.into(), &[8, 10], "narrower")] +#[case::float_wider_child(PType::F32.into(), &[8, 10], "narrower")] +#[case::float_unknown_tag(PType::F64.into(), &[24, 9], "must name the child type")] fn test_widen_wire_rejects_invalid_child_metadata( #[case] dtype: DType, #[case] metadata: &[u8], @@ -373,116 +402,3 @@ fn serialization_does_not_execute_validity() -> VortexResult<()> { Ok(()) } - -#[rstest] -#[case::f32_to_f64( - buffer![-0.0_f32, 0.0_f32, 1.5_f32, f32::INFINITY, f32::NAN].into_array(), - DType::from(PType::F64), - [8, PType::F32 as u8], -)] -#[case::f16_to_f64( - buffer![f16::NEG_ZERO, f16::ZERO, f16::ONE, f16::NEG_INFINITY, f16::NAN].into_array(), - DType::from(PType::F64), - [8, PType::F16 as u8], -)] -#[case::f16_to_f32_dict( - DictArray::try_new( - buffer![2u8, 0, 1, 2].into_array(), - buffer![f16::NEG_ZERO, f16::from_f32(1.5), f16::INFINITY].into_array(), - )?.into_array(), - DType::from(PType::F32), - [8, PType::F16 as u8], -)] -fn test_float_widen_wire_round_trip( - #[case] child: ArrayRef, - #[case] dtype: DType, - #[case] metadata: [u8; 2], -) -> VortexResult<()> { - let widen = widen_over(child.clone(), dtype)?; - let ctx = ArrayContext::empty(); - let serialized = SerializedArray::try_from(serialize_blob(&widen, &ctx, &SESSION)?)?; - let read_ctx = ReadContext::new(ctx.to_ids()); - - assert_eq!( - read_ctx.resolve(serialized.encoding_id()), - Some(ArrayVTable::id(&Widen)) - ); - assert_eq!(serialized.metadata(), metadata.as_slice()); - assert_eq!(serialized.nbuffers(), 0); - assert_eq!(serialized.nchildren(), 1); - - let decoded = serialized.decode(widen.dtype(), widen.len(), &read_ctx, &SESSION)?; - let decoded_widen = decoded.as_::(); - assert_eq!(decoded_widen.values().dtype(), child.dtype()); - assert_eq!(decoded_widen.values().encoding_id(), child.encoding_id()); - assert_arrays_eq!(decoded, widen, &mut SESSION.create_execution_ctx()); - - Ok(()) -} - -#[test] -fn test_float_widen_requires_permission() -> VortexResult<()> { - let widen = widen_over(buffer![1.0_f32, -0.0_f32], DType::from(PType::F64))?; - let without_widen = - ArrayContext::empty().with_allowed_ids([ArrayVTable::id(&Primitive)].into_iter().collect()); - let error = serialize_blob(&widen, &without_widen, &SESSION) - .expect_err("float Widen must require vortex.widen permission"); - assert!( - error.to_string().contains("vortex.widen not permitted"), - "{error}" - ); - - let with_widen = ArrayContext::empty().with_allowed_ids( - [ArrayVTable::id(&Primitive), ArrayVTable::id(&Widen)] - .into_iter() - .collect(), - ); - let serialized = SerializedArray::try_from(serialize_blob(&widen, &with_widen, &SESSION)?)?; - let read_ctx = ReadContext::new(with_widen.to_ids()); - let decoded = serialized.decode(widen.dtype(), widen.len(), &read_ctx, &SESSION)?; - assert_arrays_eq!(decoded, widen, &mut SESSION.create_execution_ctx()); - - Ok(()) -} - -#[rstest] -#[case::float_parent_int_child( - PType::F64.into(), - &[8, PType::I32 as u8], - "does not match the parent", -)] -#[case::int_parent_float_child( - PType::I64.into(), - &[8, PType::F32 as u8], - "does not match the parent", -)] -#[case::float_parent_decimal_tag( - PType::F64.into(), - &[16, 9], - "does not match the parent", -)] -#[case::float_same_width( - PType::F64.into(), - &[8, PType::F64 as u8], - "narrower", -)] -#[case::float_wider_child( - PType::F32.into(), - &[8, PType::F64 as u8], - "narrower", -)] -#[case::float_unknown_tag( - PType::F64.into(), - &[24, PType::F32 as u8], - "must name the child type", -)] -fn test_float_widen_wire_rejects_invalid_metadata( - #[case] dtype: DType, - #[case] metadata: &[u8], - #[case] expected_error: &str, -) { - let children = [buffer![1.0_f32].into_array()]; - let parts = - ArrayDeserialization::new(ArrayVTable::id(&Widen), &dtype, 1, metadata, &[], &children); - assert_widen_decode_error(parts, expected_error); -} diff --git a/vortex-btrblocks/src/schemes/float/widen.rs b/vortex-btrblocks/src/schemes/float/widen.rs index 72a41f38616..27b59c1caaa 100644 --- a/vortex-btrblocks/src/schemes/float/widen.rs +++ b/vortex-btrblocks/src/schemes/float/widen.rs @@ -50,25 +50,37 @@ struct NarrowestFloatTarget(Option); /// reused directly by [`FloatWidenScheme::compress`] to avoid compressing the array twice. struct CachedFullWiden(OnceLock); +/// Cached winning target width from sampled estimation so [`FloatWidenScheme::compress`] encodes +/// only the winning width rather than trying both `f16` and `f32` again on the full array. +struct CachedBestTarget(OnceLock); + const SAMPLE_CHUNK_LEN: usize = 1024; const SAMPLE_CHUNK_COUNT: u32 = 2; -fn compress_with_target( - compressor: &CascadingCompressor, - primitive: &PrimitiveArray, - mask: &Mask, +fn candidate_targets( + source: PType, narrowest: PType, - compress_ctx: CompressorContext, - exec_ctx: &mut ExecutionCtx, -) -> VortexResult { + compress_ctx: &CompressorContext, +) -> &'static [PType] { // When an `f64` array fits both `f16` and `f32`, compare both compressed children because // `ALP` and `ALPRD` skip `f16` and may compress `f32` smaller than raw `f16`. - let candidates: &[PType] = match (primitive.ptype(), narrowest) { + match (source, narrowest) { (PType::F64, PType::F16) if !compress_ctx.finished_cascading() => &[PType::F16, PType::F32], - _ => &[narrowest], - }; + (_, PType::F16) => &[PType::F16], + (_, PType::F32) => &[PType::F32], + _ => &[], + } +} - let mut best: Option = None; +fn compress_with_candidates( + compressor: &CascadingCompressor, + primitive: &PrimitiveArray, + mask: &Mask, + candidates: &[PType], + compress_ctx: CompressorContext, + exec_ctx: &mut ExecutionCtx, +) -> VortexResult<(ArrayRef, Option)> { + let mut best: Option<(ArrayRef, PType)> = None; for &target in candidates { let narrowed = narrow_float_values(primitive, target, mask)?; let logical_dtype = primitive.dtype().clone(); @@ -84,13 +96,16 @@ fn compress_with_target( compressor.compress_encoded(FloatWidenScheme.id(), encoded, &compress_ctx, exec_ctx)?; if best .as_ref() - .is_none_or(|current| candidate.nbytes() < current.nbytes()) + .is_none_or(|(current, _)| candidate.nbytes() < current.nbytes()) { - best = Some(candidate); + best = Some((candidate, target)); } } - Ok(best.unwrap_or_else(|| primitive.clone().into_array())) + Ok(match best { + Some((array, target)) => (array, Some(target)), + None => (primitive.clone().into_array(), None), + }) } /// Lossless floating-point narrowing scheme (`f64 -> f32/f16`, `f32 -> f16`). @@ -209,11 +224,13 @@ impl Scheme for FloatWidenScheme { if matches!(sample_mask, Mask::AllFalse(_)) { return Ok(EstimateVerdict::Skip); } - let compressed = compress_with_target( + let candidates = + candidate_targets(sample_primitive.ptype(), narrowest, &sample_ctx); + let (compressed, best_target) = compress_with_candidates( compressor, &sample_primitive, &sample_mask, - narrowest, + candidates, sample_ctx, exec_ctx, )?; @@ -224,6 +241,11 @@ impl Scheme for FloatWidenScheme { .0 .set(compressed), ); + } else if let Some(target) = best_target { + let _ = data + .get_or_insert_with(|| CachedBestTarget(OnceLock::new())) + .0 + .set(target); } if sample_after == 0 { return Ok(EstimateVerdict::Skip); @@ -261,14 +283,33 @@ impl Scheme for FloatWidenScheme { return Ok(data.array().clone()); }; - compress_with_target( + if let Some(target) = data + .get_or_insert_with(|| CachedBestTarget(OnceLock::new())) + .0 + .get() + .copied() + { + return Ok(compress_with_candidates( + compressor, + &primitive, + &mask, + &[target], + compress_ctx, + exec_ctx, + )? + .0); + } + + let candidates = candidate_targets(primitive.ptype(), narrowest, &compress_ctx); + Ok(compress_with_candidates( compressor, &primitive, &mask, - narrowest, + candidates, compress_ctx, exec_ctx, - ) + )? + .0) } } @@ -374,7 +415,12 @@ mod tests { #[test] fn compresses_f32_exact_f64_with_widen() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let values = pseudo_random_f32_in_f64(8192); + let mut values = pseudo_random_f32_in_f64(8192); + values[0] = -0.0_f64; + values[1] = 0.0_f64; + values[2] = f64::INFINITY; + values[3] = f64::NEG_INFINITY; + values[4] = f64::NAN; let input = PrimitiveArray::from_iter(values); let without_widen = BtrBlocksCompressorBuilder::from_session(&SESSION) @@ -405,15 +451,24 @@ mod tests { Ok(()) } - #[test] - fn compresses_f16_exact_f64_choosing_best_narrow_width() -> VortexResult<()> { + #[rstest] + #[case::f16_exact_f64( + PrimitiveArray::from_iter(pseudo_random_f16(4096).into_iter().map(f16::to_f64)), + PType::F16, + )] + #[case::f16_exact_f32( + PrimitiveArray::from_iter(pseudo_random_f16(4096).into_iter().map(f16::to_f32)), + PType::F16, + )] + #[case::short_f32_exact_f64( + PrimitiveArray::from_iter(pseudo_random_f32_in_f64(512)), + PType::F32 + )] + fn compresses_narrow_targets( + #[case] input: PrimitiveArray, + #[case] expected_child: PType, + ) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let values: Vec = pseudo_random_f16(4096) - .into_iter() - .map(f16::to_f64) - .collect(); - let input = PrimitiveArray::from_iter(values); - let compressed = unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; assert!( @@ -423,43 +478,30 @@ mod tests { ); assert_eq!( compressed.as_::().values().dtype().as_ptype(), - PType::F16 + expected_child ); - assert_bit_exact_f64(&compressed, &input, &mut ctx)?; + if input.ptype() == PType::F64 { + assert_bit_exact_f64(&compressed, &input, &mut ctx)?; + } else { + assert_arrays_eq!(compressed, input, &mut ctx); + } Ok(()) } - #[test] - fn preserves_neg_zero_and_canonical_nan_bits() -> VortexResult<()> { + #[rstest] + #[case::non_f32_outlier(0.1_f64)] + #[case::signaling_nan(f64::from_bits(0x7ff0_0000_2000_0000))] + #[case::negative_nan(-f64::NAN)] + fn skips_unnarrowable_values(#[case] outlier: f64) -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); let mut values = pseudo_random_f32_in_f64(4096); - values[0] = -0.0_f64; - values[1] = 0.0_f64; - values[2] = f64::INFINITY; - values[3] = f64::NEG_INFINITY; - values[4] = f64::NAN; - let input = PrimitiveArray::from_iter(values); - - let compressed = - unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; - assert!(compressed.is::()); - assert_bit_exact_f64(&compressed, &input, &mut ctx)?; - - Ok(()) - } - - #[test] - fn skips_non_f32_outlier_and_still_compresses_normally() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let mut values = pseudo_random_f32_in_f64(16_384); - values[100] = 0.1_f64; + values[77] = outlier; let input = PrimitiveArray::from_iter(values); let compressed = unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; assert!(!compressed.is::()); - // Must still compress with ALPRD rather than bailing out to uncompressed Primitive. assert!( compressed.nbytes() < input.nbytes(), "expected fallback float scheme to compress, got {} vs {}", @@ -471,23 +513,6 @@ mod tests { Ok(()) } - #[test] - fn skips_signaling_and_negative_nan() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - for nan in [f64::from_bits(0x7ff0_0000_2000_0000), -f64::NAN] { - let mut values = pseudo_random_f32_in_f64(4096); - values[77] = nan; - let input = PrimitiveArray::from_iter(values); - - let compressed = - unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; - assert!(!compressed.is::()); - assert_bit_exact_f64(&compressed, &input, &mut ctx)?; - } - - Ok(()) - } - #[test] fn ignores_non_f32_null_garbage() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); @@ -507,27 +532,6 @@ mod tests { Ok(()) } - #[test] - fn compresses_f16_exact_f32_to_f16_widen() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let values: Vec = pseudo_random_f16(4096) - .into_iter() - .map(f16::to_f32) - .collect(); - let input = PrimitiveArray::from_iter(values); - - let compressed = - unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; - assert!(compressed.is::()); - assert_eq!( - compressed.as_::().values().dtype().as_ptype(), - PType::F16 - ); - assert_arrays_eq!(compressed, input, &mut ctx); - - Ok(()) - } - #[test] fn f32_outlier_outside_sample_uses_f32_target() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); @@ -593,23 +597,6 @@ mod tests { Ok(()) } - #[test] - fn test_short_column_uses_cached_full_widen() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let input = PrimitiveArray::from_iter(pseudo_random_f32_in_f64(512)); - - let compressed = - unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; - assert!(compressed.is::()); - assert_eq!( - compressed.as_::().values().dtype().as_ptype(), - PType::F32 - ); - assert_bit_exact_f64(&compressed, &input, &mut ctx)?; - - Ok(()) - } - #[test] fn wire_round_trip_uses_widen_id() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); From a220f6ca475580afe3e09497f613e5bc283b64cb Mon Sep 17 00:00:00 2001 From: Will Manning Date: Thu, 26 Nov 2026 23:05:55 +0000 Subject: [PATCH 3/6] Document default IEEE-754 FP environment assumption for float Widen Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-array/src/arrays/widen/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/vortex-array/src/arrays/widen/mod.rs b/vortex-array/src/arrays/widen/mod.rs index 9b3e3e131b0..3ac51d45839 100644 --- a/vortex-array/src/arrays/widen/mod.rs +++ b/vortex-array/src/arrays/widen/mod.rs @@ -15,8 +15,9 @@ //! //! A floating-point child has a strictly narrower IEEE-754 type (`f16 < f32 < f64`) and **must //! not** contain signaling NaNs. [`WidenArray::encode_float`] selects the narrowest type that -//! reproduces every valid value bit-for-bit on widening back, preserving `-0.0` vs `+0.0` and -//! canonical quiet NaNs. +//! reproduces every valid value bit-for-bit on widening back under the default IEEE-754 +//! floating-point environment (without DAZ/FTZ flushing `f32` subnormals to zero), preserving +//! `-0.0` vs `+0.0` and canonical quiet NaNs. //! //! A decimal child has the logical scale and a lower precision, and **must** be valid for its dtype. //! Comparisons, bounds checks, and fills use the child dtype to bound its valid values. From 8fd28d7f91d3f7d677a45cfc6c265c00e1522c95 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Sat, 28 Nov 2026 23:48:26 +0000 Subject: [PATCH 4/6] Check float narrowing, simplify FloatWidenScheme, and tighten float Widen tests Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-array/src/arrays/widen/encode/float.rs | 80 +++-- .../src/arrays/widen/tests/compute.rs | 15 + vortex-array/src/arrays/widen/tests/float.rs | 280 ++++++++---------- vortex-btrblocks/src/schemes/float/widen.rs | 112 ++----- 4 files changed, 212 insertions(+), 275 deletions(-) diff --git a/vortex-array/src/arrays/widen/encode/float.rs b/vortex-array/src/arrays/widen/encode/float.rs index e702e8f85f8..085857372f2 100644 --- a/vortex-array/src/arrays/widen/encode/float.rs +++ b/vortex-array/src/arrays/widen/encode/float.rs @@ -30,35 +30,53 @@ use crate::scalar::PValue; /// exiting early on non-narrowable columns. const FIT_CHECK_CHUNK_LEN: usize = 64; -/// Returns whether `value` round-trips bit-for-bit through `f32`, accepting only the positive -/// canonical quiet NaN (`f64::NAN`) among NaN bit patterns. #[inline] -pub(in crate::arrays::widen) fn f64_fits_in_f32(value: f64) -> bool { +fn f64_to_f32_exact(value: f64) -> Option { #[expect( clippy::cast_possible_truncation, reason = "round-trip bit comparison immediately verifies that narrowing to f32 was lossless" )] let narrowed = value as f32; - f64::from(narrowed).to_bits() == value.to_bits() - && (!value.is_nan() || value.to_bits() == f64::NAN.to_bits()) + (f64::from(narrowed).to_bits() == value.to_bits() + && (!value.is_nan() || value.to_bits() == f64::NAN.to_bits())) + .then_some(narrowed) +} + +#[inline] +fn f32_to_f16_exact(value: f32) -> Option { + let narrowed = f16::from_f32(value); + (narrowed.to_f32().to_bits() == value.to_bits() + && (!value.is_nan() || value.to_bits() == f32::NAN.to_bits())) + .then_some(narrowed) +} + +#[inline] +fn f64_to_f16_exact(value: f64) -> Option { + let narrowed = f16::from_f64(value); + (narrowed.to_f64().to_bits() == value.to_bits() + && (!value.is_nan() || value.to_bits() == f64::NAN.to_bits())) + .then_some(narrowed) +} + +/// Returns whether `value` round-trips bit-for-bit through `f32`, accepting only the positive +/// canonical quiet NaN (`f64::NAN`) among NaN bit patterns. +#[inline] +pub(in crate::arrays::widen) fn f64_fits_in_f32(value: f64) -> bool { + f64_to_f32_exact(value).is_some() } /// Returns whether `value` round-trips bit-for-bit through `f16`, accepting only the positive /// canonical quiet NaN (`f32::NAN`) among NaN bit patterns. #[inline] pub(in crate::arrays::widen) fn f32_fits_in_f16(value: f32) -> bool { - let narrowed = f16::from_f32(value); - narrowed.to_f32().to_bits() == value.to_bits() - && (!value.is_nan() || value.to_bits() == f32::NAN.to_bits()) + f32_to_f16_exact(value).is_some() } /// Returns whether `value` round-trips bit-for-bit through `f16`, accepting only the positive /// canonical quiet NaN (`f64::NAN`) among NaN bit patterns. #[inline] pub(in crate::arrays::widen) fn f64_fits_in_f16(value: f64) -> bool { - let narrowed = f16::from_f64(value); - narrowed.to_f64().to_bits() == value.to_bits() - && (!value.is_nan() || value.to_bits() == f64::NAN.to_bits()) + f64_to_f16_exact(value).is_some() } fn f64_slice_fits_in_f32(values: &[f64]) -> bool { @@ -130,9 +148,9 @@ pub fn narrowest_float_ptype(array: &PrimitiveArray, mask: &Mask) -> Option { - #[expect( - clippy::cast_possible_truncation, - reason = "caller verified bit-exact f32 representation on valid lanes; null lanes are zeroed" - )] - let buffer = narrow_slice_with_mask(array.as_slice::(), mask, |v| v as f32); + let buffer = + narrow_slice_with_mask(array.as_slice::(), mask, f64_to_f32_exact, target)?; Ok(PrimitiveArray::new(buffer, validity)) } (PType::F64, PType::F16) => { - let buffer = narrow_slice_with_mask(array.as_slice::(), mask, f16::from_f64); + let buffer = + narrow_slice_with_mask(array.as_slice::(), mask, f64_to_f16_exact, target)?; Ok(PrimitiveArray::new(buffer, validity)) } (PType::F32, PType::F16) => { - let buffer = narrow_slice_with_mask(array.as_slice::(), mask, f16::from_f32); + let buffer = + narrow_slice_with_mask(array.as_slice::(), mask, f32_to_f16_exact, target)?; Ok(PrimitiveArray::new(buffer, validity)) } (src, dst) => { @@ -172,26 +189,33 @@ pub fn narrow_float_values( fn narrow_slice_with_mask( slice: &[W], mask: &Mask, - narrow: impl Fn(W) -> N, -) -> Buffer { + try_narrow: impl Fn(W) -> Option, + target: PType, +) -> VortexResult> { let len = slice.len(); match mask { Mask::AllTrue(_) => { let mut out = BufferMut::::with_capacity(len); for &value in slice { - out.push(narrow(value)); + let Some(narrowed) = try_narrow(value) else { + vortex_bail!("float value cannot be narrowed losslessly to {target}"); + }; + out.push(narrowed); } - out.freeze() + Ok(out.freeze()) } - Mask::AllFalse(_) => Buffer::::zeroed(len), + Mask::AllFalse(_) => Ok(Buffer::::zeroed(len)), Mask::Values(values) => { let mut out = BufferMut::::zeroed(len); for (start, end) in values.bit_buffer().set_slices() { for (dst, &src) in out[start..end].iter_mut().zip(&slice[start..end]) { - *dst = narrow(src); + let Some(narrowed) = try_narrow(src) else { + vortex_bail!("float value cannot be narrowed losslessly to {target}"); + }; + *dst = narrowed; } } - out.freeze() + Ok(out.freeze()) } } } diff --git a/vortex-array/src/arrays/widen/tests/compute.rs b/vortex-array/src/arrays/widen/tests/compute.rs index 3d148ca6ff4..88bb2b19360 100644 --- a/vortex-array/src/arrays/widen/tests/compute.rs +++ b/vortex-array/src/arrays/widen/tests/compute.rs @@ -358,6 +358,20 @@ fn test_compare_out_of_range_keeps_validity( Ok(()) } +fn nullable_float() -> WidenArray { + widen( + PrimitiveArray::from_option_iter([ + Some(-0.0_f32), + None, + Some(1.5_f32), + Some(f32::NEG_INFINITY), + Some(f32::INFINITY), + Some(f32::NAN), + ]), + PType::F64, + ) +} + /// Runs the shared compute conformance suites on each fixture. The cast suite needs the partially /// valid fixture to check the nullability contract of `CastReduce`. #[rstest] @@ -367,6 +381,7 @@ fn test_compare_out_of_range_keeps_validity( #[case::partially_valid(partially_valid())] #[case::all_invalid(all_invalid())] #[case::one_row(one_row())] +#[case::nullable_float(nullable_float())] fn test_conformance(#[case] array: WidenArray) { let mut ctx = SESSION.create_execution_ctx(); let array = array.into_array(); diff --git a/vortex-array/src/arrays/widen/tests/float.rs b/vortex-array/src/arrays/widen/tests/float.rs index 0b2425d6d02..6bb8e5eb649 100644 --- a/vortex-array/src/arrays/widen/tests/float.rs +++ b/vortex-array/src/arrays/widen/tests/float.rs @@ -3,11 +3,16 @@ //! Construction, execution, compute, and aggregate tests for floating-point [`Widen`] arrays. +#[cfg(feature = "_test-harness-hegel")] +use hegel::TestCase; +#[cfg(feature = "_test-harness-hegel")] +use hegel::generators as gs; use rstest::rstest; use vortex_buffer::Buffer; use vortex_buffer::buffer; +#[cfg(feature = "_test-harness-hegel")] +use vortex_error::VortexExpect; use vortex_error::VortexResult; -use vortex_mask::Mask; use super::SESSION; use super::assert_compare_matches_canonical; @@ -32,7 +37,6 @@ use crate::aggregate_fn::fns::min_max::MinMax; use crate::aggregate_fn::fns::sum::Sum; use crate::aggregate_fn::fns::sum_v2::SumV2; use crate::aggregate_fn::kernels::DynAggregateKernel; -use crate::arrays::BoolArray; use crate::arrays::ChunkedArray; use crate::arrays::ConstantArray; use crate::arrays::Dict; @@ -47,8 +51,19 @@ use crate::arrays::widen::WidenSlots; use crate::arrays::widen::compute::aggregate::WidenArrayAggregate; use crate::arrays::widen::compute::ptype_holding_both_values; use crate::arrays::widen::compute::ptype_holding_values_and_scalar; +#[cfg(feature = "_test-harness-hegel")] +use crate::arrays::widen::encode::f64_fits_in_f16; +#[cfg(feature = "_test-harness-hegel")] +use crate::arrays::widen::encode::f64_fits_in_f32; +use crate::arrays::widen::encode::narrow_float_values; use crate::assert_arrays_eq; use crate::builtins::ArrayBuiltins; +#[cfg(feature = "_test-harness-hegel")] +use crate::compute::conformance::hegel::EncodingCheckOptions; +#[cfg(feature = "_test-harness-hegel")] +use crate::compute::conformance::hegel::check_encoding_roundtrip_and_ops; +#[cfg(feature = "_test-harness-hegel")] +use crate::compute::conformance::hegel::draw_validity; use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::Nullability; @@ -57,6 +72,7 @@ use crate::dtype::half::f16; use crate::optimizer::ArrayOptimizer; use crate::scalar::NumericOperator; use crate::scalar::Scalar; +use crate::scalar_fn::builtin::compare::CompareKernel; use crate::scalar_fn::builtin::operators::CompareOperator; use crate::validity::Validity; @@ -214,55 +230,100 @@ fn test_try_new_and_reduce_flatten_nested_float_widen() -> VortexResult<()> { Ok(()) } -#[test] -fn test_encode_float_f64_bit_exact_round_trip() -> VortexResult<()> { +#[cfg(feature = "_test-harness-hegel")] +#[hegel::test(test_cases = 50, print_blob = true)] +fn test_encode_float_hegel_bit_exact_and_ops(tc: TestCase) { let mut ctx = SESSION.create_execution_ctx(); + let f16_edges = f16_edge_values(); + let f32_edges = f32_edge_values(); + let len = tc.draw(gs::integers::().min_value(0).max_value(32)); + // Pick a whole-array mode so f16-only, f32-only, and mixed/arbitrary f64 arrays are all + // exercised, while still allowing arbitrary f64 bits and edge values. + let mode = tc.draw(gs::integers::().min_value(0).max_value(3)); + let mut values = Vec::with_capacity(len); + for _ in 0..len { + let v = match mode { + 0 => tc.draw(gs::sampled_from(&f16_edges)).to_f64(), + 1 => { + if tc.draw(gs::booleans()) { + f64::from(tc.draw(gs::sampled_from(&f32_edges))) + } else { + f64::from(f32::from_bits(tc.draw(gs::integers::()))) + } + } + 2 => { + if tc.draw(gs::booleans()) { + f64::from(tc.draw(gs::sampled_from(&f32_edges))) + } else { + f64::from_bits(tc.draw(gs::integers::())) + } + } + _ => f64::from_bits(tc.draw(gs::integers::())), + }; + values.push(v); + } - // All values representable in f16 -> narrows to f16. - let f16_in_f64: Vec = f16_edge_values().into_iter().map(f16::to_f64).collect(); - let input = PrimitiveArray::from_iter(f16_in_f64.clone()); - let encoded = WidenArray::encode_float(input.clone(), &mut ctx)?; - assert_eq!(stored_ptype(&encoded), PType::F16); - assert_eq!(encoded.dtype(), input.dtype()); - let decoded = encoded.clone().execute::(&mut ctx)?; - for (idx, (&actual, &expected)) in decoded - .as_slice::() - .iter() - .zip(&f16_in_f64) - .enumerate() - { - assert_eq!( - actual.to_bits(), - expected.to_bits(), - "f16->f64 bit mismatch at row {idx}" - ); - let scalar = encoded.execute_scalar(idx, &mut ctx)?; - assert_eq!( - scalar.as_primitive().typed_value::().map(f64::to_bits), - Some(expected.to_bits()), - "f16->f64 scalar_at bit mismatch at row {idx}" - ); + let validity = if tc.draw(gs::booleans()) { + Validity::NonNullable + } else { + draw_validity(&tc, len) + }; + let mask = validity + .execute_mask(len, &mut ctx) + .vortex_expect("valid mask"); + let input = PrimitiveArray::new(Buffer::from(values.clone()), validity); + let encoded = WidenArray::encode_float(input.clone(), &mut ctx).vortex_expect("encode_float"); + + let all_fit_f16 = (0..len).all(|i| !mask.value(i) || f64_fits_in_f16(values[i])); + let all_fit_f32 = (0..len).all(|i| !mask.value(i) || f64_fits_in_f32(values[i])); + let expected_ptype = if all_fit_f16 { + PType::F16 + } else if all_fit_f32 { + PType::F32 + } else { + PType::F64 + }; + assert_eq!(stored_ptype(&encoded), expected_ptype); + assert_eq!(encoded.is::(), expected_ptype != PType::F64); + + let decoded = encoded + .clone() + .execute::(&mut ctx) + .vortex_expect("decode float widen"); + for (idx, (&actual, &expected)) in decoded.as_slice::().iter().zip(&values).enumerate() { + if mask.value(idx) { + assert_eq!( + actual.to_bits(), + expected.to_bits(), + "bit mismatch at row {idx}" + ); + } } - // Values representable in f32 (including -0.0, subnormals, canonical NaN) -> narrows to f32. - let f32_in_f64: Vec = f32_edge_values().into_iter().map(f64::from).collect(); - let input = PrimitiveArray::from_iter(f32_in_f64.clone()); - let encoded = WidenArray::encode_float(input, &mut ctx)?; - assert_eq!(stored_ptype(&encoded), PType::F32); - let decoded = encoded.execute::(&mut ctx)?; - for (idx, (&actual, &expected)) in decoded - .as_slice::() - .iter() - .zip(&f32_in_f64) - .enumerate() - { - assert_eq!( - actual.to_bits(), - expected.to_bits(), - "f32->f64 bit mismatch at row {idx}" - ); + if !values.is_empty() { + check_encoding_roundtrip_and_ops( + &tc, + &encoded, + &input.into_array(), + &EncodingCheckOptions::default(), + &mut ctx, + ) + .vortex_expect("hegel encoding harness"); } +} +#[rstest] +#[case::lossy_f64_to_f32(PrimitiveArray::from_iter([1.0_f64, 0.1_f64]), PType::F32)] +#[case::snan_f64_to_f32(PrimitiveArray::from_iter([1.0_f64, f64::from_bits(0x7ff0_0000_0000_0001)]), PType::F32)] +#[case::lossy_f32_to_f16(PrimitiveArray::from_iter([1.0_f32, 0.1_f32]), PType::F16)] +#[case::neg_nan_f64_to_f16(PrimitiveArray::from_iter([1.0_f64, -f64::NAN]), PType::F16)] +fn test_narrow_float_values_rejects_lossy_and_non_canonical_nan( + #[case] input: PrimitiveArray, + #[case] target: PType, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let mask = input.validity()?.execute_mask(input.len(), &mut ctx)?; + assert!(narrow_float_values(&input, target, &mask).is_err()); Ok(()) } @@ -370,77 +431,37 @@ fn test_float_execute_encoded_dict_child() -> VortexResult<()> { } #[rstest] -#[case::non_nullable(widen(Buffer::from(f32_edge_values()), PType::F64).into_array())] -#[case::nullable( - widen( +#[case::exact_neg_zero(-0.0_f64, true)] +#[case::exact_subnormal(f64::from(f32::from_bits(1)), true)] +#[case::exact_infinity(f64::INFINITY, true)] +#[case::in_between_decimal(0.1_f64, false)] +#[case::above_f32_max(f64::from(f32::MAX).next_up(), false)] +#[case::subnormal_gap(1e-100_f64, false)] +#[case::canonical_nan(f64::NAN, false)] +#[case::neg_nan(-f64::NAN, false)] +#[case::snan(f64::from_bits(0x7ff0_0000_0000_0001), false)] +fn test_compare_f32_widen_to_f64_constant_pushdown_and_decline( + #[case] constant: f64, + #[case] pushes_down: bool, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = widen( PrimitiveArray::from_option_iter( f32_edge_values() .into_iter() .enumerate() - .map(|(i, v)| (i % 4 != 1).then_some(v)) + .map(|(i, v)| (i % 4 != 1).then_some(v)), ), PType::F64, - ) - .into_array() -)] -#[case::all_invalid( - widen( - PrimitiveArray::new(Buffer::from(f32_edge_values()), Validity::AllInvalid), - PType::F64, - ) - .into_array() -)] -fn test_compare_f32_widen_to_f64_constants(#[case] array: ArrayRef) -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let constants = [ - // Exact f32 values - f64::NEG_INFINITY, - f64::from(-f32::MAX), - -0.0_f64, - 0.0_f64, - f64::from(f32::from_bits(1)), - f64::from(0.1_f32), - 1.0_f64, - f64::from(f32::MAX), - f64::INFINITY, - // Strictly between adjacent f32 values, including beyond ±f32::MAX and inside ±min_sub - -1e100_f64, - f64::from(-f32::MAX).next_down(), - f64::from(-f32::MAX).next_up(), - -0.1_f64, - -1e-45_f64, - -1e-100_f64, - 1e-100_f64, - 1e-45_f64, - 0.1_f64, - f64::from(f32::MAX).next_down(), - f64::from(f32::MAX).next_up(), - 1e100_f64, - // NaN variants (fallback to canonical) - f64::NAN, - -f64::NAN, - f64::from_bits(0x7ff8_0000_0000_0001), - f64::from_bits(0x7ff0_0000_0000_0001), - f64::from_bits(0xfff8_0000_0000_0001), - ]; + ); + let rhs = ConstantArray::new(constant, array.len()).into_array(); - for c in constants { - for nullability in [Nullability::NonNullable, Nullability::Nullable] { - let rhs = - ConstantArray::new(Scalar::primitive(c, nullability), array.len()).into_array(); - for op in ALL_COMPARE_OPERATORS { - assert_compare_matches_canonical(&array, &rhs, op, &mut ctx)?; - } - } - } + let pushed = Widen::compare(array.as_view(), &rhs, CompareOperator::Lt, &mut ctx)?; + assert_eq!(pushed.is_some(), pushes_down); - let null_rhs = ConstantArray::new( - Scalar::null(DType::Primitive(PType::F64, Nullability::Nullable)), - array.len(), - ) - .into_array(); + let array = array.into_array(); for op in ALL_COMPARE_OPERATORS { - assert_compare_matches_canonical(&array, &null_rhs, op, &mut ctx)?; + assert_compare_matches_canonical(&array, &rhs, op, &mut ctx)?; } Ok(()) @@ -676,51 +697,6 @@ fn test_ptype_holding_values_and_null_float_scalar() { ); } -#[test] -fn test_float_filter_mask_slice_take() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let array = widen( - PrimitiveArray::from_option_iter([ - Some(-0.0_f32), - None, - Some(1.5_f32), - Some(f32::INFINITY), - Some(f32::NAN), - ]), - PType::F64, - ) - .into_array(); - let expected_canonical = canonical(&array, &mut ctx)?; - - let filter_mask = Mask::from_iter([true, false, true, true, true]); - let filtered = array.filter(filter_mask.clone())?.optimize_ctx(&SESSION)?; - assert_eq!(stored_ptype(&filtered), PType::F32); - assert_arrays_eq!(filtered, expected_canonical.filter(filter_mask)?, &mut ctx); - - let keep_mask = BoolArray::from_iter([true, true, false, true, true]).into_array(); - let masked = array - .clone() - .mask(keep_mask.clone())? - .optimize_ctx(&SESSION)?; - assert_eq!(stored_ptype(&masked), PType::F32); - assert_arrays_eq!( - masked, - expected_canonical.clone().mask(keep_mask)?, - &mut ctx - ); - - let sliced = array.slice(1..4)?.optimize_ctx(&SESSION)?; - assert_eq!(stored_ptype(&sliced), PType::F32); - assert_arrays_eq!(sliced, expected_canonical.slice(1..4)?, &mut ctx); - - let indices = buffer![4u32, 0, 1, 3].into_array(); - let taken = array.take(indices.clone())?.execute::(&mut ctx)?; - assert_eq!(stored_ptype(&taken), PType::F32); - assert_arrays_eq!(taken, expected_canonical.take(indices)?, &mut ctx); - - Ok(()) -} - #[test] fn test_float_numeric_declines_and_preserves_f64_precision() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); diff --git a/vortex-btrblocks/src/schemes/float/widen.rs b/vortex-btrblocks/src/schemes/float/widen.rs index 27b59c1caaa..1a2419ee042 100644 --- a/vortex-btrblocks/src/schemes/float/widen.rs +++ b/vortex-btrblocks/src/schemes/float/widen.rs @@ -7,8 +7,6 @@ //! narrowing `f64`/`f32` through `f16`) halves or quarters raw storage and lets child float //! schemes such as `ALP` and `ALPRD` operate at the narrower width without losing a single bit. -use std::sync::OnceLock; - use vortex_array::ArrayId; use vortex_array::ArrayRef; use vortex_array::Canonical; @@ -46,26 +44,14 @@ use crate::schemes::float::FloatRLEScheme; #[derive(Debug, Clone, Copy)] struct NarrowestFloatTarget(Option); -/// Cached full-array compressed output from estimation when the array is too short to sample, -/// reused directly by [`FloatWidenScheme::compress`] to avoid compressing the array twice. -struct CachedFullWiden(OnceLock); - -/// Cached winning target width from sampled estimation so [`FloatWidenScheme::compress`] encodes -/// only the winning width rather than trying both `f16` and `f32` again on the full array. -struct CachedBestTarget(OnceLock); - const SAMPLE_CHUNK_LEN: usize = 1024; const SAMPLE_CHUNK_COUNT: u32 = 2; -fn candidate_targets( - source: PType, - narrowest: PType, - compress_ctx: &CompressorContext, -) -> &'static [PType] { +fn candidate_targets(source: PType, narrowest: PType) -> &'static [PType] { // When an `f64` array fits both `f16` and `f32`, compare both compressed children because // `ALP` and `ALPRD` skip `f16` and may compress `f32` smaller than raw `f16`. match (source, narrowest) { - (PType::F64, PType::F16) if !compress_ctx.finished_cascading() => &[PType::F16, PType::F32], + (PType::F64, PType::F16) => &[PType::F16, PType::F32], (_, PType::F16) => &[PType::F16], (_, PType::F32) => &[PType::F32], _ => &[], @@ -79,8 +65,8 @@ fn compress_with_candidates( candidates: &[PType], compress_ctx: CompressorContext, exec_ctx: &mut ExecutionCtx, -) -> VortexResult<(ArrayRef, Option)> { - let mut best: Option<(ArrayRef, PType)> = None; +) -> VortexResult { + let mut best: Option = None; for &target in candidates { let narrowed = narrow_float_values(primitive, target, mask)?; let logical_dtype = primitive.dtype().clone(); @@ -96,16 +82,13 @@ fn compress_with_candidates( compressor.compress_encoded(FloatWidenScheme.id(), encoded, &compress_ctx, exec_ctx)?; if best .as_ref() - .is_none_or(|(current, _)| candidate.nbytes() < current.nbytes()) + .is_none_or(|current| candidate.nbytes() < current.nbytes()) { - best = Some((candidate, target)); + best = Some(candidate); } } - Ok(match best { - Some((array, target)) => (array, Some(target)), - None => (primitive.clone().into_array(), None), - }) + Ok(best.unwrap_or_else(|| primitive.clone().into_array())) } /// Lossless floating-point narrowing scheme (`f64 -> f32/f16`, `f32 -> f16`). @@ -153,12 +136,11 @@ impl Scheme for FloatWidenScheme { fn expected_compression_ratio( &self, data: &ArrayAndStats, - compress_ctx: CompressorContext, + _compress_ctx: CompressorContext, exec_ctx: &mut ExecutionCtx, ) -> CompressionEstimate { let primitive = data.array_as_primitive().into_owned(); - let ptype = primitive.ptype(); - if ptype == PType::F16 || primitive.is_empty() { + if primitive.ptype() == PType::F16 || primitive.is_empty() { return CompressionEstimate::Verdict(EstimateVerdict::Skip); } @@ -181,37 +163,16 @@ impl Scheme for FloatWidenScheme { return CompressionEstimate::Verdict(EstimateVerdict::Skip); }; - // When the cascade budget is exhausted, `compress_child` leaves the narrowed primitive - // values uncompressed, so the exact ratio is known without sampling. - if compress_ctx.finished_cascading() { - let Ok(before) = uncompressed_size_in_bytes(data.array(), exec_ctx) else { - return CompressionEstimate::Verdict(EstimateVerdict::Skip); - }; - let before = before as u64; - let validity_bytes = before.saturating_sub( - u64::try_from(primitive.len() * ptype.byte_width()).unwrap_or(before), - ); - let after = u64::try_from(primitive.len() * narrowest.byte_width()) - .unwrap_or(before) - .saturating_add(validity_bytes); - if after == 0 { - return CompressionEstimate::Verdict(EstimateVerdict::Skip); - } - return CompressionEstimate::Verdict(EstimateVerdict::Ratio( - before as f64 / after as f64, - )); - } - // Use a callback so the sampled estimate reuses the full-array `narrowest` target rather // than re-deriving a narrower target (such as `f16`) from a sample that misses an // `f32`-only outlier. CompressionEstimate::Deferred(DeferredEstimate::Callback(Box::new( move |compressor, data, _best_so_far, compress_ctx, exec_ctx| { - let (sample, sample_ctx, is_full_array) = + let (sample, sample_ctx) = match sample_aligned_chunks(data.array(), SAMPLE_CHUNK_LEN, SAMPLE_CHUNK_COUNT) { - Some(sample) => (sample, compress_ctx.with_sampling(), false), - None => (data.array().clone(), compress_ctx, true), + Some(sample) => (sample, compress_ctx.with_sampling()), + None => (data.array().clone(), compress_ctx), }; let sample_before = uncompressed_size_in_bytes(&sample, exec_ctx)?; if sample_before == 0 { @@ -224,9 +185,8 @@ impl Scheme for FloatWidenScheme { if matches!(sample_mask, Mask::AllFalse(_)) { return Ok(EstimateVerdict::Skip); } - let candidates = - candidate_targets(sample_primitive.ptype(), narrowest, &sample_ctx); - let (compressed, best_target) = compress_with_candidates( + let candidates = candidate_targets(sample_primitive.ptype(), narrowest); + let compressed = compress_with_candidates( compressor, &sample_primitive, &sample_mask, @@ -235,18 +195,6 @@ impl Scheme for FloatWidenScheme { exec_ctx, )?; let sample_after = compressed.nbytes(); - if is_full_array { - drop( - data.get_or_insert_with(|| CachedFullWiden(OnceLock::new())) - .0 - .set(compressed), - ); - } else if let Some(target) = best_target { - let _ = data - .get_or_insert_with(|| CachedBestTarget(OnceLock::new())) - .0 - .set(target); - } if sample_after == 0 { return Ok(EstimateVerdict::Skip); } @@ -264,14 +212,6 @@ impl Scheme for FloatWidenScheme { compress_ctx: CompressorContext, exec_ctx: &mut ExecutionCtx, ) -> VortexResult { - if let Some(cached) = data - .get_or_insert_with(|| CachedFullWiden(OnceLock::new())) - .0 - .get() - { - return Ok(cached.clone()); - } - let primitive = data.array_as_primitive().into_owned(); let mask = primitive .validity()? @@ -283,33 +223,15 @@ impl Scheme for FloatWidenScheme { return Ok(data.array().clone()); }; - if let Some(target) = data - .get_or_insert_with(|| CachedBestTarget(OnceLock::new())) - .0 - .get() - .copied() - { - return Ok(compress_with_candidates( - compressor, - &primitive, - &mask, - &[target], - compress_ctx, - exec_ctx, - )? - .0); - } - - let candidates = candidate_targets(primitive.ptype(), narrowest, &compress_ctx); - Ok(compress_with_candidates( + let candidates = candidate_targets(primitive.ptype(), narrowest); + compress_with_candidates( compressor, &primitive, &mask, candidates, compress_ctx, exec_ctx, - )? - .0) + ) } } From 3e28425c66df1d7726586e52737e65a5be9bf568 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Mon, 30 Nov 2026 00:53:06 +0000 Subject: [PATCH 5/6] Remove redundant float Widen tests covered by Hegel property Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-array/src/arrays/widen/tests/float.rs | 371 +++++-------------- vortex-array/src/arrays/widen/tests/serde.rs | 91 +---- vortex-btrblocks/src/schemes/float/widen.rs | 185 +++------ vortex-functions/src/between/widen.rs | 151 +++----- 4 files changed, 209 insertions(+), 589 deletions(-) diff --git a/vortex-array/src/arrays/widen/tests/float.rs b/vortex-array/src/arrays/widen/tests/float.rs index 39ade9a6ad3..974b2667b07 100644 --- a/vortex-array/src/arrays/widen/tests/float.rs +++ b/vortex-array/src/arrays/widen/tests/float.rs @@ -118,7 +118,6 @@ fn f32_edge_values() -> Vec { vec![ f32::NEG_INFINITY, -f32::MAX, - -100.0, -0.1_f32, -f32::from_bits(1), -0.0_f32, @@ -133,6 +132,7 @@ fn f32_edge_values() -> Vec { } /// Edge-case `f16` values sorted in IEEE-754 total order. +#[cfg(feature = "_test-harness-hegel")] fn f16_edge_values() -> Vec { vec![ f16::NEG_INFINITY, @@ -150,91 +150,62 @@ fn f16_edge_values() -> Vec { } #[test] -fn test_float_try_new_validation_and_flatten() -> VortexResult<()> { +fn test_float_try_new_and_flatten() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - // Accepts strictly narrower float child dtypes with matching nullability. - for (child, logical, nullability) in [ - (PType::F16, PType::F32, Nullability::NonNullable), - (PType::F16, PType::F64, Nullability::Nullable), - (PType::F32, PType::F64, Nullability::NonNullable), - (PType::F32, PType::F64, Nullability::Nullable), - ] { - let values = Canonical::empty(&DType::Primitive(child, nullability)).into_array(); - let widened = WidenArray::try_new(values, DType::Primitive(logical, nullability))?; - assert_eq!(widened.dtype(), &DType::Primitive(logical, nullability)); - assert_eq!( - widened.values().dtype(), - &DType::Primitive(child, nullability) - ); - } + // Valid strictly-narrower float pairs succeed; equal/wider, cross-kind, and mismatched + // nullability fail both `try_new` and `try_from_parts`. + let values = + Canonical::empty(&DType::Primitive(PType::F16, Nullability::Nullable)).into_array(); + let widened = WidenArray::try_new(values, DType::Primitive(PType::F64, Nullability::Nullable))?; + assert_eq!( + widened.values().dtype(), + &DType::Primitive(PType::F16, Nullability::Nullable) + ); - // Rejects equal/wider float dtypes, cross-kind dtypes, and mismatched nullability. - let invalid_cases = [ - (PType::F16.into(), PType::F16.into(), "narrower"), - (PType::F32.into(), PType::F32.into(), "narrower"), - (PType::F64.into(), PType::F64.into(), "narrower"), + for (values_dtype, logical, requirement) in [ (PType::F64.into(), PType::F32.into(), "narrower"), - (PType::F32.into(), PType::F16.into(), "narrower"), - ( - PType::I16.into(), - PType::F64.into(), - "integer, float, or decimal dtypes", - ), ( PType::F32.into(), PType::I64.into(), "integer, float, or decimal dtypes", ), - ( - PType::F32.into(), - DType::Decimal(DecimalDType::new(18, 2), Nullability::NonNullable), - "integer, float, or decimal dtypes", - ), ( PType::F32.into(), DType::Primitive(PType::F64, Nullability::Nullable), "nullability", ), - ]; - for (values_dtype, logical, requirement) in invalid_cases { - let values = Canonical::empty(&values_dtype).into_array(); - let slots = WidenSlots { - values: values.clone(), - } - .into_slots(); - let parts = ArrayParts::new(Widen, logical.clone(), 0, EmptyArrayData, slots); - - let try_new_error = WidenArray::try_new(values, logical) - .expect_err("invalid float Widen dtypes must fail") + ] { + let child = Canonical::empty(&values_dtype).into_array(); + let parts = ArrayParts::new( + Widen, + logical.clone(), + 0, + EmptyArrayData, + WidenSlots { + values: child.clone(), + } + .into_slots(), + ); + let try_new_err = WidenArray::try_new(child, logical) + .expect_err("invalid float Widen must fail") .to_string(); - let validate_error = WidenArray::try_from_parts(parts) - .expect_err("invalid float Widen dtypes must fail validation") + let validate_err = WidenArray::try_from_parts(parts) + .expect_err("invalid float Widen parts must fail") .to_string(); - - assert!(try_new_error.contains(requirement), "{try_new_error}"); - assert!(validate_error.contains(requirement), "{validate_error}"); + assert!(try_new_err.contains(requirement), "{try_new_err}"); + assert!(validate_err.contains(requirement), "{validate_err}"); } // `try_new` and `optimize` flatten nested float Widens directly to the narrowest child. - let values = PrimitiveArray::from_option_iter([ - Some(f16::NEG_ZERO), - None, - Some(f16::from_f32(1.5)), - Some(f16::INFINITY), - ]) - .into_array(); - - let inner = widen(values.clone(), PType::F32).into_array(); + let leaf = PrimitiveArray::from_option_iter([Some(f16::NEG_ZERO), None, Some(f16::INFINITY)]) + .into_array(); + let inner = widen(leaf.clone(), PType::F32).into_array(); let outer = WidenArray::try_new( inner.clone(), DType::Primitive(PType::F64, Nullability::Nullable), )?; assert!(outer.values().is::()); - assert_eq!( - outer.values().dtype(), - &DType::Primitive(PType::F16, Nullability::Nullable) - ); let nested = WidenArray::try_from_parts(ArrayParts::new( Widen, @@ -243,16 +214,10 @@ fn test_float_try_new_validation_and_flatten() -> VortexResult<()> { EmptyArrayData, WidenSlots { values: inner }.into_slots(), ))?; - assert!(nested.values().is::()); let flattened = nested.into_array().optimize_ctx(&SESSION)?; - assert!(ArrayRef::ptr_eq(flattened.as_::().values(), &values)); - - let expected = PrimitiveArray::from_option_iter([ - Some(-0.0_f64), - None, - Some(1.5_f64), - Some(f64::INFINITY), - ]); + assert!(ArrayRef::ptr_eq(flattened.as_::().values(), &leaf)); + + let expected = PrimitiveArray::from_option_iter([Some(-0.0_f64), None, Some(f64::INFINITY)]); assert_arrays_eq!(outer, expected, &mut ctx); assert_arrays_eq!(flattened, expected, &mut ctx); @@ -341,8 +306,6 @@ fn test_encode_float_hegel_bit_exact_and_ops(tc: TestCase) { }); (input, encoded) } else { - // Pick a whole-array mode so f16-only, f32-only, and mixed/arbitrary f64 arrays are all - // exercised, while still allowing arbitrary f64 bits and edge values. let mode = tc.draw(gs::integers::().min_value(0).max_value(3)); let mut values = Vec::with_capacity(len); for _ in 0..len { @@ -415,10 +378,10 @@ fn test_encode_float_hegel_bit_exact_and_ops(tc: TestCase) { } #[test] -fn test_encode_float_selection_and_rejection() -> VortexResult<()> { +fn test_float_nan_and_snan_rejection() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - // `narrow_float_values` rejects lossy and non-canonical NaN inputs. + // `narrow_float_values` rejects lossy values, signaling NaNs, and negative NaNs. for (input, target) in [ (PrimitiveArray::from_iter([1.0_f64, 0.1_f64]), PType::F32), ( @@ -432,89 +395,40 @@ fn test_encode_float_selection_and_rejection() -> VortexResult<()> { assert!(narrow_float_values(&input, target, &mask).is_err()); } - // `encode_float` keeps f64 unchanged on lossy values, non-canonical qNaN, -NaN, and sNaN. - for values in [ - vec![0.0_f64, 0.1_f64, 1.0_f64], - vec![1.0_f64, 1e100_f64], - vec![1.0_f64, 1e-100_f64], - vec![f64::MAX], - vec![1.0_f64, f64::from_bits(0x7ff8_0000_0000_0001)], - vec![1.0_f64, -f64::NAN], - vec![1.0_f64, f64::from_bits(0x7ff0_0000_0000_0001)], - vec![1.0_f64, f64::from_bits(0x7ff0_0000_2000_0000)], + // `encode_float` declines non-canonical qNaN, -NaN, and sNaN for both f64 and f32. + for bad in [ + f64::from_bits(0x7ff8_0000_0000_0001), + -f64::NAN, + f64::from_bits(0x7ff0_0000_0000_0001), + f64::from_bits(0x7ff0_0000_2000_0000), ] { - let input = PrimitiveArray::from_iter(values); - let encoded = WidenArray::encode_float(input.clone(), &mut ctx)?; - assert_eq!(stored_ptype(&encoded), PType::F64); + let encoded = + WidenArray::encode_float(PrimitiveArray::from_iter([1.0_f64, bad]), &mut ctx)?; assert!(!encoded.is::()); - assert_arrays_eq!(encoded, input, &mut ctx); } - - // Target selection across f32, f16, empty, all-null, and null-payload zeroing. - let selection_cases = [ - ( - PrimitiveArray::from_iter( - f16_edge_values() - .into_iter() - .map(f16::to_f32) - .collect::>(), - ), - PType::F16, - ), - (PrimitiveArray::from_iter([0.1_f32, 1.0_f32]), PType::F32), - ( - PrimitiveArray::from_iter([1.0_f32, f32::from_bits(0x7fc0_0001)]), - PType::F32, - ), - (PrimitiveArray::from_iter([1.0_f32, -f32::NAN]), PType::F32), - ( - PrimitiveArray::from_iter([1.0_f32, f32::from_bits(0x7f80_2000)]), - PType::F32, - ), - ( - PrimitiveArray::from_iter([f16::ONE, f16::NEG_ZERO]), - PType::F16, - ), - ( - PrimitiveArray::empty::(Nullability::NonNullable), - PType::F16, - ), - ( - PrimitiveArray::empty::(Nullability::Nullable), - PType::F16, - ), - ( - PrimitiveArray::new( - buffer![0.1_f64, f64::from_bits(0x7ff0_0000_0000_0001)], - Validity::AllInvalid, - ), - PType::F16, - ), - ( - PrimitiveArray::new( - buffer![0.1_f64, 1.5_f64, f64::from_bits(0x7ff0_0000_0000_0001)], - Validity::from_iter([false, true, false]), - ), - PType::F16, - ), - ]; - for (input, expected_stored) in selection_cases { - let encoded = WidenArray::encode_float(input.clone(), &mut ctx)?; - assert_eq!(stored_ptype(&encoded), expected_stored); - assert_eq!(encoded.dtype(), input.dtype()); - assert_arrays_eq!(encoded, input, &mut ctx); - - // Null slots in a narrowed child are zeroed so signaling NaNs cannot leak into the child. - if let Some(w) = encoded.as_opt::() - && w.values().dtype().as_ptype() == PType::F16 - && input.len() == 3 - { - let child = w.values().as_::(); - assert_eq!(child.as_slice::()[0].to_bits(), 0); - assert_eq!(child.as_slice::()[2].to_bits(), 0); - } + for bad in [ + f32::from_bits(0x7fc0_0001), + -f32::NAN, + f32::from_bits(0x7f80_2000), + ] { + let encoded = + WidenArray::encode_float(PrimitiveArray::from_iter([1.0_f32, bad]), &mut ctx)?; + assert!(!encoded.is::()); } + // Null-slot sNaNs are ignored during narrowing and zeroed in the child buffer. + let with_null_snan = PrimitiveArray::new( + buffer![0.1_f64, 1.5_f64, f64::from_bits(0x7ff0_0000_0000_0001)], + Validity::from_iter([false, true, false]), + ); + let encoded = WidenArray::encode_float(with_null_snan.clone(), &mut ctx)?; + assert_eq!(stored_ptype(&encoded), PType::F16); + let child = encoded.as_::().values().as_::(); + assert_eq!(child.as_slice::()[0].to_bits(), 0); + assert_eq!(child.as_slice::()[2].to_bits(), 0); + assert_arrays_eq!(encoded, with_null_snan, &mut ctx); + + // Non-float primitive input is rejected. let error = WidenArray::encode_float(PrimitiveArray::from_iter([1i32, 2, 3]), &mut ctx) .expect_err("encode_float must reject integers"); assert!(error.to_string().contains("floating-point"), "{error}"); @@ -550,10 +464,9 @@ fn test_float_execute_encoded_dict_child() -> VortexResult<()> { } #[test] -fn test_float_compare_constants_and_widens() -> VortexResult<()> { +fn test_float_compare_pushdown_and_decline() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - // f32 -> f64 constant pushdown vs decline across exact, in-between, and NaN constants. let f32_widen = widen( PrimitiveArray::from_option_iter( f32_edge_values() @@ -584,58 +497,7 @@ fn test_float_compare_constants_and_widens() -> VortexResult<()> { } } - // f16 -> f64 and f16 -> f32 constants across all CompareModes. - let f16_to_f64 = widen(Buffer::from(f16_edge_values()), PType::F64).into_array(); - for c in [ - f64::NEG_INFINITY, - -1e10_f64, - f16::MIN.to_f64().next_down(), - f16::MIN.to_f64(), - f16::MIN.to_f64().next_up(), - -0.1_f64, - -1e-10_f64, - -0.0_f64, - 0.0_f64, - 1e-10_f64, - 0.1_f64, - f16::MAX.to_f64().next_down(), - f16::MAX.to_f64(), - f16::MAX.to_f64().next_up(), - 1e10_f64, - f64::INFINITY, - f64::NAN, - -f64::NAN, - ] { - let rhs = ConstantArray::new(c, f16_to_f64.len()).into_array(); - for op in ALL_COMPARE_OPERATORS { - assert_float_compare_matches_canonical(&f16_to_f64, &rhs, op, &mut ctx)?; - } - } - - let f16_to_f32 = widen(Buffer::from(f16_edge_values()), PType::F32).into_array(); - for c in [ - f32::NEG_INFINITY, - -1e10_f32, - f16::MIN.to_f32(), - -0.1_f32, - -1e-10_f32, - -0.0_f32, - 0.0_f32, - 1e-10_f32, - 0.1_f32, - f16::MAX.to_f32(), - 1e10_f32, - f32::INFINITY, - f32::NAN, - -f32::NAN, - ] { - let rhs = ConstantArray::new(c, f16_to_f32.len()).into_array(); - for op in ALL_COMPARE_OPERATORS { - assert_float_compare_matches_canonical(&f16_to_f32, &rhs, op, &mut ctx)?; - } - } - - // Comparing two float Widens (f16 -> f64 vs f32 -> f64) across all CompareModes. + // Two float Widens (f16 -> f64 vs f32 -> f64) compare at f32 across all CompareModes. let lhs = widen( PrimitiveArray::from_option_iter([ Some(-f16::NAN), @@ -644,7 +506,6 @@ fn test_float_compare_constants_and_widens() -> VortexResult<()> { Some(f16::ZERO), Some(f16::ONE), None, - Some(f16::INFINITY), Some(f16::NAN), ]), PType::F64, @@ -658,7 +519,6 @@ fn test_float_compare_constants_and_widens() -> VortexResult<()> { Some(-0.0_f32), Some(1.0_f32), Some(2.0_f32), - None, Some(f32::NAN), ]), PType::F64, @@ -676,7 +536,7 @@ fn test_float_compare_constants_and_widens() -> VortexResult<()> { } #[test] -fn test_float_cast_and_fill_null() -> VortexResult<()> { +fn test_float_cast_rules() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); let f16_to_f64 = widen( PrimitiveArray::from_option_iter([ @@ -688,7 +548,7 @@ fn test_float_cast_and_fill_null() -> VortexResult<()> { ) .into_array(); - // Strictly wider float keeps Widen. + // Strictly wider float keeps Widen; same width unwraps; float-to-int delegates. let to_f32 = f16_to_f64 .cast(DType::Primitive(PType::F32, Nullability::Nullable))? .optimize_ctx(&SESSION)?; @@ -700,7 +560,6 @@ fn test_float_cast_and_fill_null() -> VortexResult<()> { &mut ctx ); - // Same width as child unwraps Widen. let to_f16 = f16_to_f64 .cast(DType::Primitive(PType::F16, Nullability::Nullable))? .optimize_ctx(&SESSION)?; @@ -712,7 +571,6 @@ fn test_float_cast_and_fill_null() -> VortexResult<()> { &mut ctx ); - // Float-to-int cast delegates to child and matches canonical. let to_i32 = f16_to_f64 .cast(DType::Primitive(PType::I32, Nullability::Nullable))? .optimize_ctx(&SESSION)?; @@ -723,17 +581,17 @@ fn test_float_cast_and_fill_null() -> VortexResult<()> { &mut ctx ); - // Float Widen (F32 -> F64) narrowed to F16 matches canonical f64 -> f16 rounding. + // Narrowing f32->f64 to f16 matches canonical rounding; out-of-range int and decimal fail. let f32_to_f64 = widen( buffer![0.1_f32, -0.0_f32, 100_000.0_f32, f32::NAN], PType::F64, ) .into_array(); - let to_f16 = f32_to_f64.cast(PType::F16.into())?; - let expected = canonical(&f32_to_f64, &mut ctx)?.cast(PType::F16.into())?; - assert_arrays_eq!(to_f16, expected, &mut ctx); - - // Out-of-range float-to-int and float-to-decimal fail just like canonical. + assert_arrays_eq!( + f32_to_f64.cast(PType::F16.into())?, + canonical(&f32_to_f64, &mut ctx)?.cast(PType::F16.into())?, + &mut ctx + ); let big = widen(buffer![1e20_f32], PType::F64).into_array(); assert!( big.cast(PType::I32.into())? @@ -748,7 +606,12 @@ fn test_float_cast_and_fill_null() -> VortexResult<()> { .is_err() ); - // `fill_null` selects the narrowest float type holding both child values and fill scalar. + Ok(()) +} + +#[test] +fn test_float_fill_null() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); let array = widen( PrimitiveArray::from_option_iter([Some(f16::from_f32(-1.5)), None, Some(f16::ONE)]), PType::F64, @@ -759,19 +622,13 @@ fn test_float_cast_and_fill_null() -> VortexResult<()> { ptype_holding_values_and_scalar(array.as_::(), &null_scalar), Some(PType::F16) ); + + let canonical_array = canonical(&array, &mut ctx)?; for (fill_value, expected_stored) in [ - ( - Scalar::primitive(0.5_f64, Nullability::NonNullable), - PType::F16, - ), ( Scalar::primitive(-0.0_f64, Nullability::NonNullable), PType::F16, ), - ( - Scalar::primitive(f64::INFINITY, Nullability::NonNullable), - PType::F16, - ), ( Scalar::primitive(f64::NAN, Nullability::NonNullable), PType::F16, @@ -801,7 +658,7 @@ fn test_float_cast_and_fill_null() -> VortexResult<()> { .fill_null(fill_value.clone())? .optimize_ctx(&SESSION)?; assert_eq!(stored_ptype(&filled), expected_stored); - let expected = canonical(&array, &mut ctx)?.fill_null(fill_value)?; + let expected = canonical_array.clone().fill_null(fill_value)?; assert_arrays_eq!(filled, expected, &mut ctx); } @@ -811,8 +668,7 @@ fn test_float_cast_and_fill_null() -> VortexResult<()> { #[test] fn test_float_numeric_declines_and_preserves_f64_precision() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - // 16_777_216.0 + 1.0 loses precision in f32 (rounds to 16_777_216.0), and 1e20 * 1e20 overflows - // f32 to +inf, while both are exact/finite in f64. + // 16_777_216.0 + 1.0 loses precision in f32, and 1e20 * 1e20 overflows f32 to +inf. let lhs = widen(buffer![16_777_216.0_f32, 1e20_f32], PType::F64).into_array(); let rhs = widen(buffer![1.0_f32, 1e20_f32], PType::F64).into_array(); @@ -827,7 +683,6 @@ fn test_float_numeric_declines_and_preserves_f64_precision() -> VortexResult<()> assert_arrays_eq!(actual, expected, &mut ctx); } - // Double-check the exact f64 result values didn't suffer f32 rounding/overflow. let sum = lhs .numeric(rhs.clone(), NumericOperator::Add)? .execute::(&mut ctx)?; @@ -850,78 +705,39 @@ fn test_float_aggregates_match_canonical_and_sum_declines() -> VortexResult<()> (MinMax.bind(skip_nans), true), (MinMax.bind(include_nans), true), (Min.bind(skip_nans), true), - (Min.bind(include_nans), true), - (Max.bind(skip_nans), true), (Max.bind(include_nans), true), (IsConstant.bind(EmptyOptions), true), (IsSorted.bind(IsSortedOptions { strict: false }), true), (IsSorted.bind(IsSortedOptions { strict: true }), true), (Sum.bind(skip_nans), false), - (Sum.bind(include_nans), false), (SumV2.bind(skip_nans), false), ]; let fixtures = [ widen(Buffer::from(f32_edge_values()), PType::F64).into_array(), - widen(buffer![-0.0_f32, 0.0_f32], PType::F64).into_array(), - widen(buffer![-0.0_f32, -0.0_f32], PType::F64).into_array(), - widen(buffer![0.0_f32, -0.0_f32], PType::F64).into_array(), - widen(buffer![f32::NAN, f32::NAN], PType::F64).into_array(), widen( - buffer![ - 16_777_216.0_f32, - 1.0_f32, - 1.0_f32, - 1e38_f32, - 1e38_f32, - 1e38_f32, - 1e38_f32 - ], + buffer![16_777_216.0_f32, 1.0_f32, 1.0_f32, 1e38_f32, 1e38_f32], PType::F64, ) .into_array(), widen( - PrimitiveArray::from_option_iter([ - None, - Some(f16::NEG_ZERO), - Some(f16::ZERO), - Some(f16::ONE), - ]), + PrimitiveArray::from_option_iter([None, Some(f16::NEG_ZERO), Some(f16::ZERO)]), PType::F64, ) .into_array(), - widen( - PrimitiveArray::new(buffer![1.0_f32, 2.0_f32], Validity::AllInvalid), - PType::F64, - ) - .into_array(), - widen( - PrimitiveArray::empty::(Nullability::NonNullable), - PType::F32, - ) - .into_array(), ]; for fixture in fixtures { let canonical_fixture = canonical(&fixture, &mut ctx)?; for (aggregate_fn, expected_served) in &aggregates { let kernel_result = WidenArrayAggregate.aggregate(aggregate_fn, &fixture, &mut ctx)?; - assert_eq!( - kernel_result.is_some(), - *expected_served, - "unexpected kernel coverage for {aggregate_fn} on {}", - fixture.dtype() - ); + assert_eq!(kernel_result.is_some(), *expected_served); let mut actual_acc = aggregate_fn.accumulator(fixture.dtype())?; actual_acc.accumulate(&fixture, &mut ctx)?; - let actual = actual_acc.finish()?; - let mut expected_acc = aggregate_fn.accumulator(canonical_fixture.dtype())?; expected_acc.accumulate(&canonical_fixture, &mut ctx)?; - let expected = expected_acc.finish()?; - - assert_eq!(actual, expected, "mismatch for {aggregate_fn}"); + assert_eq!(actual_acc.finish()?, expected_acc.finish()?); } } @@ -929,8 +745,9 @@ fn test_float_aggregates_match_canonical_and_sum_declines() -> VortexResult<()> let chunk1 = widen(buffer![-0.0_f32, 0.0_f32], PType::F64).into_array(); let chunk2 = widen(buffer![1.0_f32, 2.0_f32], PType::F64).into_array(); let chunked = ChunkedArray::try_new(vec![chunk1, chunk2], PType::F64.into())?.into_array(); - let is_strict = IsSorted.bind(IsSortedOptions { strict: true }); - let mut acc = is_strict.accumulator(chunked.dtype())?; + let mut acc = IsSorted + .bind(IsSortedOptions { strict: true }) + .accumulator(chunked.dtype())?; acc.accumulate(&chunked, &mut ctx)?; assert_eq!(acc.finish()?, Scalar::from(Some(true))); diff --git a/vortex-array/src/arrays/widen/tests/serde.rs b/vortex-array/src/arrays/widen/tests/serde.rs index 6c4ee2d8583..cbe1587c88d 100644 --- a/vortex-array/src/arrays/widen/tests/serde.rs +++ b/vortex-array/src/arrays/widen/tests/serde.rs @@ -234,6 +234,19 @@ fn serialization_keeps_parent_statistics() -> VortexResult<()> { DType::Decimal(DecimalDType::new(38, 2), Nullability::Nullable), [16, 9], )] +#[case::f32_to_f64( + buffer![-0.0_f32, 0.0_f32, 1.5_f32, f32::INFINITY, f32::NAN].into_array(), + DType::from(PType::F64), + [8, 9], // Field 1, PType::F32 = 9. +)] +#[case::f16_to_f32_dict( + DictArray::try_new( + buffer![2u8, 0, 1, 2].into_array(), + buffer![f16::NEG_ZERO, f16::from_f32(1.5), f16::INFINITY].into_array(), + )?.into_array(), + DType::from(PType::F32), + [8, 8], // Field 1, PType::F16 = 8. +)] fn test_widen_wire_round_trip( #[case] child: ArrayRef, #[case] dtype: DType, @@ -293,6 +306,8 @@ fn test_widen_wire_id_requires_permission() -> VortexResult<()> { &[16, 1], "scale", )] +#[case::float_parent_int_child(PType::F64.into(), &[8, 6], "does not match the parent")] +#[case::float_wider_child(PType::F32.into(), &[8, 10], "narrower")] fn test_widen_wire_rejects_invalid_child_metadata( #[case] dtype: DType, #[case] metadata: &[u8], @@ -305,82 +320,6 @@ fn test_widen_wire_rejects_invalid_child_metadata( assert_widen_decode_error(parts, expected_error); } -#[test] -fn test_float_widen_wire_serde() -> VortexResult<()> { - let round_trip_cases = [ - ( - buffer![-0.0_f32, 0.0_f32, 1.5_f32, f32::INFINITY, f32::NAN].into_array(), - DType::from(PType::F64), - [8, 9], // Field 1, PType::F32 = 9. - ), - ( - buffer![ - f16::NEG_ZERO, - f16::ZERO, - f16::ONE, - f16::NEG_INFINITY, - f16::NAN - ] - .into_array(), - DType::from(PType::F64), - [8, 8], // Field 1, PType::F16 = 8. - ), - ( - DictArray::try_new( - buffer![2u8, 0, 1, 2].into_array(), - buffer![f16::NEG_ZERO, f16::from_f32(1.5), f16::INFINITY].into_array(), - )? - .into_array(), - DType::from(PType::F32), - [8, 8], // Field 1, PType::F16 = 8. - ), - ]; - for (child, dtype, metadata) in round_trip_cases { - let widen = widen_over(child.clone(), dtype)?; - let ctx = ArrayContext::empty(); - let serialized = SerializedArray::try_from(serialize_blob(&widen, &ctx, &SESSION)?)?; - let read_ctx = ReadContext::new(ctx.to_ids()); - - assert_eq!( - read_ctx.resolve(serialized.encoding_id()), - Some(ArrayVTable::id(&Widen)) - ); - assert_eq!(serialized.metadata(), metadata.as_slice()); - assert_eq!(serialized.nbuffers(), 0); - assert_eq!(serialized.nchildren(), 1); - - let decoded = serialized.decode(widen.dtype(), widen.len(), &read_ctx, &SESSION)?; - let values = decoded.as_::().values(); - assert_eq!(values.dtype(), child.dtype()); - assert_eq!(values.encoding_id(), child.encoding_id()); - assert_arrays_eq!(decoded, widen, &mut SESSION.create_execution_ctx()); - } - - let float_widen = widen_over(buffer![1.0_f32, -0.0_f32], DType::from(PType::F64))?; - let restricted = - ArrayContext::empty().with_allowed_ids([ArrayVTable::id(&Primitive)].into_iter().collect()); - let error = serialize_blob(&float_widen, &restricted, &SESSION) - .expect_err("the target must permit the Widen wire ID"); - assert!(error.to_string().contains("vortex.widen not permitted")); - - let children = [buffer![1u32].into_array()]; - let invalid_cases: [(DType, &[u8], &str); 6] = [ - (PType::F64.into(), &[8, 6], "does not match the parent"), - (PType::I64.into(), &[8, 9], "does not match the parent"), - (PType::F64.into(), &[16, 9], "does not match the parent"), - (PType::F64.into(), &[8, 10], "narrower"), - (PType::F32.into(), &[8, 10], "narrower"), - (PType::F64.into(), &[24, 9], "must name the child type"), - ]; - for (dtype, metadata, expected_error) in invalid_cases { - let parts = - ArrayDeserialization::new(ArrayVTable::id(&Widen), &dtype, 1, metadata, &[], &children); - assert_widen_decode_error(parts, expected_error); - } - - Ok(()) -} - #[test] fn test_widen_wire_rejects_invalid_node() { let dtype = DType::from(PType::I64); diff --git a/vortex-btrblocks/src/schemes/float/widen.rs b/vortex-btrblocks/src/schemes/float/widen.rs index 1340a5869f3..9708bc6b48e 100644 --- a/vortex-btrblocks/src/schemes/float/widen.rs +++ b/vortex-btrblocks/src/schemes/float/widen.rs @@ -240,11 +240,9 @@ mod tests { use std::sync::Arc; use std::sync::LazyLock; - use vortex_array::ArrayContext; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; - use vortex_array::VTable; use vortex_array::VortexSessionExecute; use vortex_array::arrays::Primitive; use vortex_array::arrays::PrimitiveArray; @@ -253,14 +251,10 @@ mod tests { use vortex_array::assert_arrays_eq; use vortex_array::dtype::PType; use vortex_array::dtype::half::f16; - 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::FloatWidenScheme; use crate::BtrBlocksCompressor; @@ -332,7 +326,7 @@ mod tests { } #[test] - fn compresses_narrow_targets_and_skips_unnarrowable() -> VortexResult<()> { + fn compresses_f32_and_f16_exact_columns() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); // f32-exact f64 beats compressing without Widen and preserves special values bit-for-bit. @@ -351,101 +345,71 @@ mod tests { .compress(&input.clone().into_array(), &mut ctx)?; let with_widen = unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; - assert!( - with_widen.is::(), - "expected Widen at root, got {}", - with_widen.encoding_id() - ); assert_eq!( with_widen.as_::().values().dtype().as_ptype(), PType::F32 ); - assert!( - with_widen.nbytes() < without_widen.nbytes(), - "expected Widen to compress smaller, got {} vs {}", - with_widen.nbytes(), - without_widen.nbytes() - ); + assert!(with_widen.nbytes() < without_widen.nbytes()); assert_bit_exact_f64(&with_widen, &input, &mut ctx)?; - // Narrow targets across f16-in-f64, f16-in-f32, short f32-in-f64, null garbage, and - // unsampled trailing f32 outlier. - let mut null_garbage_values = pseudo_random_f32_in_f64(4096); - let mut valid = vec![true; null_garbage_values.len()]; - for i in (0..null_garbage_values.len()).step_by(13) { - null_garbage_values[i] = 0.1_f64; - valid[i] = false; - } - let mut trailing_outlier_values: Vec = pseudo_random_f16(16_384) + // f16-exact f64 narrows to f16; an unsampled trailing f32 outlier falls back to f32. + let f16_in_f64 = + PrimitiveArray::from_iter(pseudo_random_f16(4096).into_iter().map(f16::to_f64)); + let compressed_f16 = + unrestricted_compressor().compress(&f16_in_f64.clone().into_array(), &mut ctx)?; + assert_eq!( + compressed_f16.as_::().values().dtype().as_ptype(), + PType::F16 + ); + assert_bit_exact_f64(&compressed_f16, &f16_in_f64, &mut ctx)?; + + let mut trailing: Vec = pseudo_random_f16(16_384) .into_iter() .map(f16::to_f64) .collect(); - // Append an f32-exact, non-f16 outlier in the partial trailing chunk, which - // `sample_aligned_chunks` never samples. - trailing_outlier_values.push(f64::from(100_000.25_f32)); - - let narrow_cases = [ - ( - PrimitiveArray::from_iter(pseudo_random_f16(4096).into_iter().map(f16::to_f64)), - PType::F16, - ), - ( - PrimitiveArray::from_iter(pseudo_random_f16(4096).into_iter().map(f16::to_f32)), - PType::F16, - ), - ( - PrimitiveArray::from_iter(pseudo_random_f32_in_f64(512)), - PType::F32, - ), - ( - PrimitiveArray::new( - Buffer::from(null_garbage_values), - Validity::from_iter(valid), - ), - PType::F32, - ), - ( - PrimitiveArray::from_iter(trailing_outlier_values), - PType::F32, - ), - ]; - for (input, expected_child) in narrow_cases { - let compressed = - unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; - assert!( - compressed.is::(), - "expected Widen at root, got {}", - compressed.encoding_id() - ); - assert_eq!( - compressed.as_::().values().dtype().as_ptype(), - expected_child - ); - if input.ptype() == PType::F64 { - assert_bit_exact_f64(&compressed, &input, &mut ctx)?; - } else { - assert_arrays_eq!(compressed, input, &mut ctx); - } - } + trailing.push(f64::from(100_000.25_f32)); + let trailing_input = PrimitiveArray::from_iter(trailing); + let trailing_compressed = + unrestricted_compressor().compress(&trailing_input.clone().into_array(), &mut ctx)?; + assert_eq!( + trailing_compressed + .as_::() + .values() + .dtype() + .as_ptype(), + PType::F32 + ); + assert_bit_exact_f64(&trailing_compressed, &trailing_input, &mut ctx)?; + + Ok(()) + } + + #[test] + fn skips_unnarrowable_and_ignores_null_garbage() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); - // Unnarrowable outliers (inexact decimal, signaling NaN, negative NaN) skip Widen. for outlier in [0.1_f64, f64::from_bits(0x7ff0_0000_2000_0000), -f64::NAN] { let mut values = pseudo_random_f32_in_f64(4096); values[77] = outlier; let input = PrimitiveArray::from_iter(values); - let compressed = unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; assert!(!compressed.is::()); - assert!( - compressed.nbytes() < input.nbytes(), - "expected fallback float scheme to compress, got {} vs {}", - compressed.nbytes(), - input.nbytes() - ); assert_bit_exact_f64(&compressed, &input, &mut ctx)?; } + let mut values = pseudo_random_f32_in_f64(4096); + let mut valid = vec![true; values.len()]; + for i in (0..values.len()).step_by(13) { + values[i] = 0.1_f64; + valid[i] = false; + } + let input = PrimitiveArray::new(Buffer::from(values), Validity::from_iter(valid)); + let compressed = + unrestricted_compressor().compress(&input.clone().into_array(), &mut ctx)?; + assert!(compressed.is::()); + assert_bit_exact_f64(&compressed, &input, &mut ctx)?; + Ok(()) } @@ -458,12 +422,7 @@ mod tests { let two_run = PrimitiveArray::from_iter(two_run_values); let compressed = unrestricted_compressor().compress(&two_run.clone().into_array(), &mut ctx)?; - assert!( - !compressed.is::(), - "expected RLE or Dict to beat Widen on two-run column, got {} ({} bytes)", - compressed.encoding_id(), - compressed.nbytes(), - ); + assert!(!compressed.is::()); assert_arrays_eq!(compressed, two_run, &mut ctx); let null_prefix = PrimitiveArray::from_option_iter( @@ -473,12 +432,7 @@ mod tests { ); let compressed = unrestricted_compressor().compress(&null_prefix.clone().into_array(), &mut ctx)?; - assert!( - !compressed.is::() && !compressed.is::(), - "expected Sparse/RLE/Dict to beat Widen when sampled chunks are all null, got {} ({} bytes)", - compressed.encoding_id(), - compressed.nbytes(), - ); + assert!(!compressed.is::() && !compressed.is::()); assert_arrays_eq!(compressed, null_prefix, &mut ctx); Ok(()) @@ -494,37 +448,10 @@ mod tests { } #[test] - fn wire_round_trip_and_child_policy() -> VortexResult<()> { + fn honors_child_policy() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); let input = PrimitiveArray::from_iter(pseudo_random_f32_in_f64(4096)); - // Wire serialization emits `vortex.widen` and round-trips bit-for-bit. - let compressed = BtrBlocksCompressorBuilder::empty() - .with_new_scheme(&FloatWidenScheme) - .build() - .compress(&input.clone().into_array(), &mut ctx)?; - assert!(compressed.is::()); - - let array_ctx = ArrayContext::empty(); - let mut blob = ByteBufferMut::empty(); - for buf in compressed.serialize(&array_ctx, &SESSION, &SerializeOptions::default())? { - blob.extend_from_slice(buf.as_ref()); - } - let ids = array_ctx.to_ids(); - assert!( - ids.contains(&Widen.id()), - "expected vortex.widen in {ids:?}" - ); - let serialized = SerializedArray::try_from(blob.freeze())?; - let decoded = serialized.decode( - compressed.dtype(), - compressed.len(), - &ReadContext::new(ids), - &SESSION, - )?; - assert_bit_exact_f64(&decoded, &input, &mut ctx)?; - - // Child policy controls whether the narrowed child cascades or stays canonical. for keep in [false, true] { let mut builder = BtrBlocksCompressorBuilder::empty() .with_new_scheme(&FloatWidenScheme) @@ -532,22 +459,10 @@ mod tests { if keep { builder = builder.with_child_policy(Arc::new(KeepAllChildren)); } - let compressed = builder .build() .compress(&input.clone().into_array(), &mut ctx)?; - assert!( - compressed.is::(), - "expected Widen at root, got {}", - compressed.encoding_id() - ); - let child = compressed.as_::().values(); - assert_eq!( - child.is_canonical(), - keep, - "expected child canonical={keep}, got {}", - child.encoding_id() - ); + assert_eq!(compressed.as_::().values().is_canonical(), keep); assert_bit_exact_f64(&compressed, &input, &mut ctx)?; } diff --git a/vortex-functions/src/between/widen.rs b/vortex-functions/src/between/widen.rs index 05b2a9e7f2d..825685e5762 100644 --- a/vortex-functions/src/between/widen.rs +++ b/vortex-functions/src/between/widen.rs @@ -77,7 +77,6 @@ mod tests { use vortex_array::dtype::DecimalDType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::dtype::half::f16; use vortex_array::scalar::DecimalValue; use vortex_array::scalar::Scalar; use vortex_array::scalar_fn::ScalarFnVTable; @@ -271,135 +270,85 @@ mod tests { #[test] fn test_float_between_pushdown_and_decline() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); - let f16_to_f64 = widen( + let array = widen( PrimitiveArray::from_option_iter([ - Some(-f16::NAN), - Some(f16::NEG_INFINITY), - Some(f16::from_f32(-1.5)), - Some(f16::NEG_ZERO), - Some(f16::ZERO), - Some(f16::from_f32(0.5)), - Some(f16::ONE), + Some(f32::NEG_INFINITY), + Some(-1.5_f32), + Some(-0.0_f32), + Some(0.0_f32), + Some(1.0_f32), None, - Some(f16::INFINITY), - Some(f16::NAN), + Some(f32::INFINITY), + Some(f32::NAN), ]), PType::F64, ); - let len = f16_to_f64.len(); + let len = array.len(); let f64_const = |v: f64| ConstantArray::new(v, len).into_array(); let non_strict = BetweenOptions { lower_strict: StrictComparison::NonStrict, upper_strict: StrictComparison::NonStrict, }; - // Exact non-NaN bounds push down to `values.between(...)` in one pass at `f16`. - for (lo, hi) in [ - (-0.0_f64, 0.0_f64), - (0.0_f64, 1.0_f64), - (f64::NEG_INFINITY, f64::INFINITY), - (f16::MIN.to_f64(), f16::MAX.to_f64()), - ] { - let lower = f64_const(lo); - let upper = f64_const(hi); - let reduced = Widen::between(f16_to_f64.as_view(), &lower, &upper, &non_strict)? - .expect("exact non-NaN float bounds must push down"); - let sfn = reduced.as_::(); - assert_eq!(sfn.scalar_fn().id(), Between.id()); - assert_eq!(sfn.get_child(0).dtype().as_ptype(), PType::F16); - } - - // A `Widen` bound paired with an exact constant uses `as_two_compares` without decoding. - let widen_lower = widen(PrimitiveArray::from_iter([-1.0_f32; 10]), PType::F64).into_array(); - let exact_upper = f64_const(1.0_f64); - assert!( - Widen::between( - f16_to_f64.as_view(), - &widen_lower, - &exact_upper, - &non_strict - )? - .is_some() - ); - - // Non-exact or NaN float constant bounds must decline so `Between` decodes once. + // Exact non-NaN bounds push down to `values.between(...)` in one pass at `f32`. + let reduced = Widen::between( + array.as_view(), + &f64_const(-0.0_f64), + &f64_const(1.0_f64), + &non_strict, + )? + .expect("exact non-NaN float bounds must push down"); + let sfn = reduced.as_::(); + assert_eq!(sfn.scalar_fn().id(), Between.id()); + assert_eq!(sfn.get_child(0).dtype().as_ptype(), PType::F32); + + // Non-exact or NaN bounds decline so `Between` decodes once. + let widen_lower = widen(PrimitiveArray::from_iter([-1.0_f32; 8]), PType::F64).into_array(); for (lower, upper) in [ - (f64_const(0.1_f64), f64_const(0.9_f64)), - (f64_const(0.0_f64), f64_const(0.9_f64)), (f64_const(0.1_f64), f64_const(1.0_f64)), + (f64_const(-0.0_f64), f64_const(0.9_f64)), (f64_const(f64::NAN), f64_const(1.0_f64)), - (f64_const(-f64::NAN), f64_const(1.0_f64)), - (f64_const(0.0_f64), f64_const(f64::NAN)), + (f64_const(-0.0_f64), f64_const(f64::NAN)), (widen_lower.clone(), f64_const(0.9_f64)), ] { - assert!( - Widen::between(f16_to_f64.as_view(), &lower, &upper, &non_strict)?.is_none(), - "non-exact or NaN float bound must decline" - ); + assert!(Widen::between(array.as_view(), &lower, &upper, &non_strict)?.is_none()); } - // Verify full execution parity against canonical across all strictness combinations, - // exact, non-exact, NaN, Widen, and nullable bounds on both f16->f64 and f16->f32. - let f16_to_f64_arr = f16_to_f64.into_array(); - let canonical_f64 = canonical(&f16_to_f64_arr, &mut ctx)?; + // Verify parity against canonical across exact, non-exact, NaN, Widen, and null bounds. + let array_ref = array.into_array(); + let canonical_f64 = canonical(&array_ref, &mut ctx)?; let null_f64 = ConstantArray::new( Scalar::null(DType::Primitive(PType::F64, Nullability::Nullable)), len, ) .into_array(); - let bound_pairs = [ - (f64_const(-0.0_f64), f64_const(0.0_f64)), - (f64_const(0.0_f64), f64_const(1.0_f64)), + for (lower, upper) in [ + (f64_const(-0.0_f64), f64_const(1.0_f64)), (f64_const(0.1_f64), f64_const(0.9_f64)), - (f64_const(0.0_f64), f64_const(0.9_f64)), (f64_const(f64::NAN), f64_const(1.0_f64)), - (f64_const(-0.0_f64), f64_const(f64::NAN)), (widen_lower, f64_const(1.0_f64)), - (null_f64.clone(), f64_const(0.5_f64)), - (f64_const(0.0_f64), null_f64), - ]; - for lower_strict in [StrictComparison::NonStrict, StrictComparison::Strict] { - for upper_strict in [StrictComparison::NonStrict, StrictComparison::Strict] { - let options = BetweenOptions { - lower_strict, - upper_strict, - }; - for (lower, upper) in &bound_pairs { - let actual = f16_to_f64_arr.clone().between( - lower.clone(), - upper.clone(), - options.clone(), - )?; - let expected = canonical_f64.clone().between( - canonical(lower, &mut ctx)?, - canonical(upper, &mut ctx)?, - options.clone(), - )?; - assert_arrays_eq!(actual, expected, &mut ctx); - } + (null_f64, f64_const(1.0_f64)), + ] { + for options in [ + non_strict.clone(), + BetweenOptions { + lower_strict: StrictComparison::Strict, + upper_strict: StrictComparison::Strict, + }, + ] { + let actual = + array_ref + .clone() + .between(lower.clone(), upper.clone(), options.clone())?; + let expected = canonical_f64.clone().between( + canonical(&lower, &mut ctx)?, + canonical(&upper, &mut ctx)?, + options, + )?; + assert_arrays_eq!(actual, expected, &mut ctx); } } - // Also cover f16->f32 and f32->f64 float Widens. - let f16_to_f32 = widen( - buffer![f16::NEG_ZERO, f16::ZERO, f16::ONE, f16::NAN], - PType::F32, - ) - .into_array(); - let canonical_f32 = canonical(&f16_to_f32, &mut ctx)?; - for (lo, hi) in [(-0.0_f32, 1.0_f32), (0.1_f32, 0.9_f32), (f32::NAN, 1.0_f32)] { - let lower = ConstantArray::new(lo, 4).into_array(); - let upper = ConstantArray::new(hi, 4).into_array(); - let actual = - f16_to_f32 - .clone() - .between(lower.clone(), upper.clone(), non_strict.clone())?; - let expected = canonical_f32 - .clone() - .between(lower, upper, non_strict.clone())?; - assert_arrays_eq!(actual, expected, &mut ctx); - } - Ok(()) } } From 38476e3568e360e773c820289f4d27f509515c29 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Mon, 30 Nov 2026 01:49:58 +0000 Subject: [PATCH 6/6] Restore f16 constant-decline and equal-width float Widen tests Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-array/src/arrays/widen/tests/float.rs | 50 ++++++++++++++++++++ vortex-array/src/arrays/widen/tests/serde.rs | 1 + 2 files changed, 51 insertions(+) diff --git a/vortex-array/src/arrays/widen/tests/float.rs b/vortex-array/src/arrays/widen/tests/float.rs index 974b2667b07..2e634cbea15 100644 --- a/vortex-array/src/arrays/widen/tests/float.rs +++ b/vortex-array/src/arrays/widen/tests/float.rs @@ -164,6 +164,7 @@ fn test_float_try_new_and_flatten() -> VortexResult<()> { ); for (values_dtype, logical, requirement) in [ + (PType::F64.into(), PType::F64.into(), "narrower"), (PType::F64.into(), PType::F32.into(), "narrower"), ( PType::F32.into(), @@ -497,6 +498,55 @@ fn test_float_compare_pushdown_and_decline() -> VortexResult<()> { } } + // f16 -> f64 and f16 -> f32 constant pushdown vs decline (guards `(F64, F16)` and `(F32, F16)` + // arms of `constant_fits_values`). + let f16_to_f64 = widen( + PrimitiveArray::from_option_iter([ + Some(f16::NEG_ZERO), + Some(f16::ZERO), + Some(f16::from_f32(0.1)), + None, + Some(f16::MAX), + Some(f16::NAN), + ]), + PType::F64, + ); + let f16_to_f64_arr = f16_to_f64.clone().into_array(); + for (constant, pushes_down) in [ + (-0.0_f64, true), + (0.0_f64, true), + (0.1_f64, false), + (f64::from(0.1_f32), false), + (f16::MAX.to_f64().next_up(), false), + (f64::NAN, false), + ] { + let rhs = ConstantArray::new(constant, f16_to_f64.len()).into_array(); + let pushed = Widen::compare(f16_to_f64.as_view(), &rhs, CompareOperator::Lt, &mut ctx)?; + assert_eq!(pushed.is_some(), pushes_down); + for op in ALL_COMPARE_OPERATORS { + assert_float_compare_matches_canonical(&f16_to_f64_arr, &rhs, op, &mut ctx)?; + } + } + + let f16_to_f32 = widen( + buffer![f16::NEG_ZERO, f16::from_f32(0.1), f16::MAX, f16::NAN], + PType::F32, + ); + let f16_to_f32_arr = f16_to_f32.clone().into_array(); + for (constant, pushes_down) in [ + (-0.0_f32, true), + (0.1_f32, false), + (f16::MAX.to_f32().next_up(), false), + (f32::NAN, false), + ] { + let rhs = ConstantArray::new(constant, f16_to_f32.len()).into_array(); + let pushed = Widen::compare(f16_to_f32.as_view(), &rhs, CompareOperator::Lt, &mut ctx)?; + assert_eq!(pushed.is_some(), pushes_down); + for op in ALL_COMPARE_OPERATORS { + assert_float_compare_matches_canonical(&f16_to_f32_arr, &rhs, op, &mut ctx)?; + } + } + // Two float Widens (f16 -> f64 vs f32 -> f64) compare at f32 across all CompareModes. let lhs = widen( PrimitiveArray::from_option_iter([ diff --git a/vortex-array/src/arrays/widen/tests/serde.rs b/vortex-array/src/arrays/widen/tests/serde.rs index cbe1587c88d..56fc8271c9f 100644 --- a/vortex-array/src/arrays/widen/tests/serde.rs +++ b/vortex-array/src/arrays/widen/tests/serde.rs @@ -307,6 +307,7 @@ fn test_widen_wire_id_requires_permission() -> VortexResult<()> { "scale", )] #[case::float_parent_int_child(PType::F64.into(), &[8, 6], "does not match the parent")] +#[case::float_same_width(PType::F64.into(), &[8, 10], "narrower")] #[case::float_wider_child(PType::F32.into(), &[8, 10], "narrower")] fn test_widen_wire_rejects_invalid_child_metadata( #[case] dtype: DType,