Skip to content
25 changes: 18 additions & 7 deletions vortex-array/src/arrays/widen/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self> {
// NB: Check `values` before the flatten. The values of a `Widen` child are narrower than
Expand Down Expand Up @@ -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() =>
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
{
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(),
Expand All @@ -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}"
),
}

Expand Down
22 changes: 19 additions & 3 deletions vortex-array/src/arrays/widen/compute/aggregate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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<Option<Scalar>> {
if !(aggregate_fn.is::<MinMax>()
|| aggregate_fn.is::<Min>()
|| aggregate_fn.is::<Max>()
Expand Down
11 changes: 11 additions & 0 deletions vortex-array/src/arrays/widen/compute/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions vortex-array/src/arrays/widen/compute/compare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,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);
};
Expand Down Expand Up @@ -100,6 +103,26 @@ fn compare_narrow_values(
.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<Option<ArrayRef>> {
let values = lhs.values();
if constant_fits_values(constant, values.dtype()) != Some(true) {
return Ok(None);
}

let constant = constant_in_values_dtype(constant, values, lhs.len())?;
values
.compare(constant, operator, CompareMode::TOTAL_ORDER)
.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
Expand Down
69 changes: 54 additions & 15 deletions vortex-array/src/arrays/widen/compute/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ use crate::arrays::ConstantArray;
use crate::arrays::Widen;
use crate::arrays::WidenArray;
use crate::arrays::widen::WidenArraySlotsExt;
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::arrays::widen::encode::smallest_float_ptype_for_value;
use crate::arrays::widen::encode::smallest_integer_ptype;
use crate::builtins::ArrayBuiltins;
use crate::dtype::DType;
Expand All @@ -60,10 +64,11 @@ pub fn wrap_values(values: ArrayRef, dtype: DType) -> VortexResult<ArrayRef> {
}

/// 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,
Expand All @@ -80,12 +85,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)
Expand All @@ -94,15 +105,16 @@ 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<ArrayRef> {
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, decimals must have the same scale, and floats must be
/// non-NaN values that round-trip bit-for-bit in the values dtype. Returns `None` for null
/// constants, NaN floats, unsupported dtypes, or incompatible constants.
pub fn constant_fits_values(constant: &Scalar, values: &DType) -> Option<bool> {
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
match (values, constant.dtype()) {
(DType::Decimal(values_dtype, _), DType::Decimal(constant_dtype, _))
Expand All @@ -125,15 +137,34 @@ pub fn constant_fits_values(constant: &Scalar, values: &DType) -> Option<bool> {
&& value <= PValue::max_value(*values_ptype),
)
}
(DType::Primitive(values_ptype, _), DType::Primitive(constant_ptype, _))
if values_ptype.is_float() && constant_ptype.is_float() =>
{
let value = constant.as_primitive().pvalue()?;
if value.is_nan() {
return None;
}
let fits = match (value, *values_ptype) {
(PValue::F64(c), PType::F32) => f64_fits_in_f32(c),
(PValue::F64(c), PType::F16) => f64_fits_in_f16(c),
(PValue::F32(c), PType::F16) => f32_fits_in_f16(c),
(PValue::F16(_), PType::F16)
| (PValue::F32(_), PType::F32)
| (PValue::F64(_), PType::F64) => true,
_ => return None,
};
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved

Some(fits)
}
_ => None,
}
}

/// 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>,
Expand All @@ -144,10 +175,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
}
}

Expand Down
3 changes: 3 additions & 0 deletions vortex-array/src/arrays/widen/compute/numeric.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ impl ExecuteParentKernel<Widen> 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::<ScalarFn>()
Expand Down
7 changes: 7 additions & 0 deletions vortex-array/src/arrays/widen/compute/take.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ impl TakeExecute for Widen {
indices: &ArrayRef,
ctx: &mut ExecutionCtx,
) -> VortexResult<Option<ArrayRef>> {
// 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);
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
}

// 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
Expand Down
Loading
Loading