This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-12058-19c0e23d4e46389705b96d1b4d9fca67daa16e3a in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 1b42833a2105efdbb757108c7d15233aa35e9bf5 Author: Matt Butrovich <[email protected]> AuthorDate: Fri Nov 20 15:08:26 2026 +0000 perf(arrow-arith): vectorize checked integer `add`, `sub` and `mul` (#12058) # Which issue does this PR close? N/A. # Rationale for this change Checked `add`, `sub` and `mul` on integers [call `try_binary` or `try_unary`](https://github.com/apache/arrow-rs/blob/b231cf15efa5dbbbe4ae8503849aa6ab3cfc4e0c/arrow-arith/src/numeric.rs#L337-L343), which return at the first overflow, so LLVM doesn't vectorize them. DataFusion calls them when `fail_on_overflow` is set ([`binary.rs`](https://github.com/apache/datafusion/blob/32bd81fb226ccf1ae5df67ff340d77baa3e73668/datafusion/physical-expr/src/expressions/binary.rs#L641-L651)), and Comet calls them for Spark's ANSI mode ([`checked_arithmetic.rs`](https://github.com/apache/datafusion-comet/blob/79b5ddd50ba2e3f605399d641e4c0b3be84c20ef/native/spark-expr/src/math_funcs/checked_arithmetic.rs#L146-L148)). # What changes are included in this PR? - Integer `add`, `sub` and `mul` compute the wrapping result and an overflow flag for every slot in one pass. - If a slot overflowed and the result has nulls, they recompute the overflow of every row into a bitmap and mask it with the validity bits. They rerun the existing checked kernel only if a valid row overflowed, so errors don't change. An overflow in a null slot, such as unsigned `0 - 1` in a slot that a builder filled with 0, doesn't rerun the batch. - Signed `add` and `sub` test sign bits, because the signed `overflowing_add` and `overflowing_sub` don't vectorize. - Signed `i64` `mul` uses `overflowing_mul`, while the narrower signed types multiply in the next wider type. Widened to `i128`, the `i64` multiply stayed a scalar `imul` while LLVM packed each row's overflow flag into vector registers, and it measured 0.65x with `x86-64-v3`. - The pass writes into the `Vec`'s spare capacity and calls `set_len` with the number of slots it wrote. With `collect`, LLVM sometimes left the loop inside `collect` out of line, where it loaded and stored the overflow flag on every row. #12062 measured that at 0.83x for rescaled `Decimal128` add on Neoverse-V2. #12062 has the same helper. - The output is reserved with `Vec::try_reserve_exact`, so an allocation failure returns `ArrowError::MemoryError`. - Null slots of the result hold the wrapping result instead of zero, as they already do for `add_wrapping`. - 48ca288b6b adds the benchmark cases, so the benchmark bot can compare against it. # Are these changes tested? New tests in `arrow-arith/src/numeric.rs` compare the kernels with the scalar checked operations at the edge values of every integer type. They run as arrays with and without nulls, as one-row slices, and with a scalar on either side. Another test moves one overflowing row through a 300-row batch, so that each lane of the vector loop and the scalar remainder hold it once. <img width="1600" height="3700" alt="checked-arith-bot-6035cda" src="https://github.com/user-attachments/assets/e381c473-b6d2-4056-8dd0-92d976e4ac15" /> The overflow cases are expected to be slower, because they pay for the new pass, the null-slot check, and then the checked kernel. With `fail_on_overflow` or ANSI mode, an overflow fails the query, so that cost is paid at most once per partition. A batch that overflows only in null slots pays for the pass and the null-slot check, and still beats `main` in the default-layout runs: `int32_add_checked_null_slot_overflow` measured 2.67x on Neoverse-V2, 1.36x on Xeon 8581C, and 2.76x with `x86-64-v3`. The lowest is `uint64_add_checked_null_slot_overflow` on Xeon 8581C, at 1.03x default and 0.86x aligned. The extra pass also costs code size: 132 KiB for `integer_op` and the new helpers across the eight integer types, against 18.5 KiB before, in the thin-LTO bench binary on aarch64. The checked kernels that the fallback calls are unchanged. Bot runs: Neoverse-V2 [default](https://github.com/apache/arrow-rs/pull/12058#issuecomment-6863769659) and [aligned](https://github.com/apache/arrow-rs/pull/12058#issuecomment-6863779762), Xeon 8581C [default](https://github.com/apache/arrow-rs/pull/12058#issuecomment-6863835999) and [aligned](https://github.com/apache/arrow-rs/pull/12058#issuecomment-6863817201), and Xeon 8581C with `-C target-cpu=x86-64-v3` [default](https://github.com/apache/arrow-rs/pull/12058#issuecomment-6864013103) and [aligned](https://github.com/apache/arrow-rs/pull/12058#issuecomment-6864103757). Those runs measured 8aa275041e. 6035cda2f6 changes only the `i64` multiply, and its `Int64` runs are: Neoverse-V2 [default](https://github.com/apache/arrow-rs/pull/12058#issuecomment-6864850084) and [aligned](https://github.com/apache/arrow-rs/pull/12058#issuecomment-6864850474), Xeon 8581C [default](https://github.com/apache/arrow-rs/pull/12058#issuecomment-6864870951) and [aligned](https://github.com/apache/arrow-rs/pull/12058#issuecomment-6864846382), and `x86-64-v3` [default](https://github.com/apache/arrow-rs/pull/12058#issuecomment-6864872512) and [aligned](https://github.com/apache/arrow-rs/pull/12058#issuecomment-6864960581). # Are there any significant user-facing changes? No. ## AI Disclosure I wrote this PR with help from Claude but understand and support the core approach, implementation, and test coverage. --- arrow-arith/src/numeric.rs | 295 +++++++++++++++++++++++++++++++++++- arrow/benches/arithmetic_kernels.rs | 92 ++++++++++- 2 files changed, 380 insertions(+), 7 deletions(-) diff --git a/arrow-arith/src/numeric.rs b/arrow-arith/src/numeric.rs index a9e6a2edf5..b4c8ab86a8 100644 --- a/arrow-arith/src/numeric.rs +++ b/arrow-arith/src/numeric.rs @@ -735,22 +735,35 @@ divisor_op!( ); /// Perform an arithmetic operation on integers -fn integer_op<T: ArrowPrimitiveType>( +fn integer_op<T>( op: Op, l: &dyn Array, l_s: bool, r: &dyn Array, r_s: bool, -) -> Result<ArrayRef, ArrowError> { +) -> Result<ArrayRef, ArrowError> +where + T: ArrowPrimitiveType, + T::Native: OverflowingOp, +{ let l = l.as_primitive::<T>(); let r = r.as_primitive::<T>(); let array: PrimitiveArray<T> = match op { Op::AddWrapping => op!(l, l_s, r, r_s, l.add_wrapping(r)), - Op::Add => try_op!(l, l_s, r, r_s, l.add_checked(r)), + Op::Add => match overflowing_op(l, l_s, r, r_s, T::Native::add_overflowing)? { + Some(array) => array, + None => try_op!(l, l_s, r, r_s, l.add_checked(r)), + }, Op::SubWrapping => op!(l, l_s, r, r_s, l.sub_wrapping(r)), - Op::Sub => try_op!(l, l_s, r, r_s, l.sub_checked(r)), + Op::Sub => match overflowing_op(l, l_s, r, r_s, T::Native::sub_overflowing)? { + Some(array) => array, + None => try_op!(l, l_s, r, r_s, l.sub_checked(r)), + }, Op::MulWrapping => op!(l, l_s, r, r_s, l.mul_wrapping(r)), - Op::Mul => try_op!(l, l_s, r, r_s, l.mul_checked(r)), + Op::Mul => match overflowing_op(l, l_s, r, r_s, T::Native::mul_overflowing)? { + Some(array) => array, + None => try_op!(l, l_s, r, r_s, l.mul_checked(r)), + }, Op::Div => try_op!(l, l_s, r, r_s, l.div_checked(r)), Op::Rem => try_op!(l, l_s, r, r_s, { if r.is_zero() { @@ -2029,6 +2042,278 @@ mod tests { assert_eq!(err, "Divide by zero error"); } + /// Checks `add`, `sub` and `mul` against the scalar checked operations for + /// every pair of `edges`, with arrays on both sides and with a scalar on + /// either side. + fn test_checked_integer_ops<T: ArrowPrimitiveType>(edges: &[T::Native]) { + test_checked_integer_op::<T>(edges, add, |l, r| l.add_checked(r)); + test_checked_integer_op::<T>(edges, sub, |l, r| l.sub_checked(r)); + test_checked_integer_op::<T>(edges, mul, |l, r| l.mul_checked(r)); + } + + fn test_checked_integer_op<T: ArrowPrimitiveType>( + edges: &[T::Native], + kernel: Kernel, + checked: Checked<T::Native>, + ) { + let (l, r): (Vec<_>, Vec<_>) = edges + .iter() + .flat_map(|&x| edges.iter().map(move |&y| (x, y))) + .unzip(); + // With every third row null, null slots also hold values that overflow. + // Without nulls, every pair is checked, because when the number of + // edges is a multiple of 3 the null rows always pair with the same + // right-hand values. + let every_third = NullBuffer::from_iter((0..l.len()).map(|i| i % 3 != 2)); + for nulls in [Some(every_third), None] { + let valid = |i| nulls.as_ref().is_none_or(|n| n.is_valid(i)); + let l_array = PrimitiveArray::<T>::new(l.clone().into(), nulls.clone()); + let r_array = PrimitiveArray::<T>::from_iter_values(r.iter().copied()); + let context = if nulls.is_some() { "nulls" } else { "no nulls" }; + + // The kernels report the first valid row that overflows. + let expected = (0..l.len()) + .map(|i| valid(i).then(|| checked(l[i], r[i])).transpose()) + .collect(); + assert_kernel_result::<T>( + kernel(&l_array, &r_array), + expected, + &format!("{context}: array, array"), + ); + + // An overflow in one row sends the whole array to the checked kernel, + // which would hide a missed overflow in another row, so also check each + // row alone. + for i in 0..l.len() { + let expected = match valid(i) { + true => checked(l[i], r[i]).map(|v| vec![Some(v)]), + false => Ok(vec![None]), + }; + let actual = kernel(&l_array.slice(i, 1), &r_array.slice(i, 1)); + assert_kernel_result::<T>(actual, expected, &format!("{context}: row {i}")); + } + + for &x in edges { + let scalar = PrimitiveArray::<T>::new_scalar(x); + let expected = r.iter().map(|&y| checked(x, y).map(Some)).collect(); + assert_kernel_result::<T>( + kernel(&scalar, &r_array), + expected, + &format!("{context}: scalar {x:?}, array"), + ); + let expected = (0..l.len()) + .map(|i| valid(i).then(|| checked(l[i], x)).transpose()) + .collect(); + assert_kernel_result::<T>( + kernel(&l_array, &scalar), + expected, + &format!("{context}: array, scalar {x:?}"), + ); + } + } + } + + #[test] + fn test_checked_integer_edges() { + macro_rules! signed { + ($a:ty, $t:ty) => { + test_checked_integer_ops::<$a>(&[ + <$t>::MIN, + <$t>::MIN + 1, + <$t>::MIN / 2, + -3, + -1, + 0, + 1, + 3, + <$t>::MAX / 2, + <$t>::MAX / 2 + 1, + <$t>::MAX - 1, + <$t>::MAX, + ]) + }; + } + macro_rules! unsigned { + ($a:ty, $t:ty) => { + test_checked_integer_ops::<$a>(&[ + 0, + 1, + 3, + <$t>::MAX / 2, + <$t>::MAX / 2 + 1, + <$t>::MAX - 1, + <$t>::MAX, + ]) + }; + } + signed!(Int8Type, i8); + signed!(Int16Type, i16); + signed!(Int32Type, i32); + signed!(Int64Type, i64); + unsigned!(UInt8Type, u8); + unsigned!(UInt16Type, u16); + unsigned!(UInt32Type, u32); + unsigned!(UInt64Type, u64); + } + + /// Moves one row that overflows through a batch, so that each lane of the + /// vector loop and each row of the scalar remainder holds it once, with an + /// array and a scalar on either side. The same row is also checked as a + /// null slot, which is not an error. + fn test_checked_integer_overflow_position<T: ArrowPrimitiveType>() { + // Two iterations of the widest vector loop we build, 32 `i8` lanes of + // AVX2 unrolled four times, plus a remainder. + const LEN: usize = 300; + let one = T::Native::ONE; + // The kernel, its checked scalar operation, the value that overflows, + // and the other operand. + type Case<N> = (Kernel, Checked<N>, N, N); + let cases: [Case<T::Native>; 3] = [ + ( + add, + |l, r| l.add_checked(r), + T::Native::MAX_TOTAL_ORDER, + one, + ), + ( + sub, + |l, r| l.sub_checked(r), + T::Native::MIN_TOTAL_ORDER, + one, + ), + ( + mul, + |l, r| l.mul_checked(r), + T::Native::MAX_TOTAL_ORDER, + one.add_wrapping(one), + ), + ]; + for (kernel, checked, edge, other) in cases { + let other_array = PrimitiveArray::<T>::from_value(other, LEN); + let other_scalar = PrimitiveArray::<T>::new_scalar(other); + for i in 0..LEN { + let mut values = vec![one; LEN]; + values[i] = edge; + for null in [None, Some(i)] { + let nulls = null.map(|i| NullBuffer::from_iter((0..LEN).map(|j| j != i))); + let array = PrimitiveArray::<T>::new(values.clone().into(), nulls); + let expected = |f: &dyn Fn(T::Native) -> Result<T::Native, ArrowError>| { + (0..LEN) + .map(|j| match Some(j) == null { + true => Ok(None), + false => f(values[j]).map(Some), + }) + .collect() + }; + let context = format!("row {i}, null {null:?}"); + assert_kernel_result::<T>( + kernel(&array, &other_array), + expected(&|v| checked(v, other)), + &format!("{context}: array, array"), + ); + assert_kernel_result::<T>( + kernel(&other_array, &array), + expected(&|v| checked(other, v)), + &format!("{context}: other array, array"), + ); + assert_kernel_result::<T>( + kernel(&array, &other_scalar), + expected(&|v| checked(v, other)), + &format!("{context}: array, scalar"), + ); + assert_kernel_result::<T>( + kernel(&other_scalar, &array), + expected(&|v| checked(other, v)), + &format!("{context}: scalar, array"), + ); + } + } + } + } + + #[test] + fn test_checked_null_slot_overflow_sliced() { + // Sliced at 3, the validity bits start mid-byte and the 200 rows span + // three full 64-row chunks plus a remainder. Row 5 is null and always + // overflows, so every case checks the valid rows. + const LEN: usize = 203; + let nulls = NullBuffer::from_iter((0..LEN).map(|j| j % 5 != 0)); + let one = Int32Array::new_scalar(1); + for i in 3..LEN { + let mut values = vec![1; LEN]; + values[5] = i32::MAX; + values[i] = i32::MAX; + let array = Int32Array::new(values.into(), Some(nulls.clone())).slice(3, LEN - 3); + let result = add(&array, &one); + match nulls.is_valid(i) { + true => assert!(result.is_err(), "row {i}"), + false => { + let expected: Int32Array = + (3..LEN).map(|j| nulls.is_valid(j).then_some(2)).collect(); + assert_eq!( + result.unwrap().as_primitive::<Int32Type>(), + &expected, + "row {i}" + ); + } + } + } + } + + #[test] + #[cfg_attr(miri, ignore)] // Checks the lanes of vectorized loops, which Miri doesn't run + fn test_checked_integer_overflow_positions() { + test_checked_integer_overflow_position::<Int8Type>(); + test_checked_integer_overflow_position::<Int16Type>(); + test_checked_integer_overflow_position::<Int32Type>(); + test_checked_integer_overflow_position::<Int64Type>(); + test_checked_integer_overflow_position::<UInt8Type>(); + test_checked_integer_overflow_position::<UInt16Type>(); + test_checked_integer_overflow_position::<UInt32Type>(); + test_checked_integer_overflow_position::<UInt64Type>(); + } + + #[test] + fn test_checked_integer_slice_null_scalar_and_lengths() { + // Overflowing values outside the slice are not an error. + let array = Int64Array::from(vec![i64::MAX, 1, 2, i64::MAX]).slice(1, 2); + let one = Int64Array::new_scalar(1); + let result = add(&array, &one).unwrap(); + assert_eq!( + result.as_primitive::<Int64Type>(), + &Int64Array::from(vec![2, 3]) + ); + + // A null scalar gives an all-null result whatever the array holds. + let null = Scalar::new(Int64Array::new_null(1)); + let max = Int64Array::from(vec![i64::MAX; 3]); + assert_eq!(add(&max, &null).unwrap().null_count(), 3); + assert_eq!(mul(&null, &max).unwrap().null_count(), 3); + + // An all-null array that overflows in every slot is not an error. + let all_null = Int64Array::new(vec![i64::MAX; 3].into(), Some(NullBuffer::new_null(3))); + assert_eq!(add(&all_null, &one).unwrap().null_count(), 3); + + // The builder fills null slots with 0, which overflows `0 - 1`. + let array = UInt64Array::from(vec![Some(10), None, Some(20)]); + assert_eq!(array.values()[1], 0); + let result = sub(&array, &UInt64Array::new_scalar(1)).unwrap(); + assert_eq!( + result.as_primitive::<UInt64Type>(), + &UInt64Array::from(vec![Some(9), None, Some(19)]) + ); + + let empty = Int64Array::from(Vec::<i64>::new()); + assert!(add(&empty, &empty).unwrap().is_empty()); + assert!(sub(&empty, &one).unwrap().is_empty()); + + let err = add(&Int64Array::from(vec![1, 2]), &Int64Array::from(vec![1])).unwrap_err(); + assert_eq!( + err.to_string(), + "Compute error: Cannot perform a binary operation on arrays of different length" + ); + } + #[test] fn test_float() { let a = Float32Array::from(vec![1., f32::MAX, 6., -4., -1., 0.]); diff --git a/arrow/benches/arithmetic_kernels.rs b/arrow/benches/arithmetic_kernels.rs index 3397f019f7..87d78c8af0 100644 --- a/arrow/benches/arithmetic_kernels.rs +++ b/arrow/benches/arithmetic_kernels.rs @@ -7,9 +7,10 @@ use criterion::*; use arrow::compute::kernels::numeric::*; use arrow::datatypes::{ ArrowPrimitiveType, Decimal32Type, Decimal64Type, Decimal128Type, Decimal256Type, Float32Type, + Int32Type, Int64Type, UInt32Type, UInt64Type, }; use arrow::util::bench_util::*; -use arrow_array::{Array, Decimal128Array, PrimitiveArray, Scalar}; +use arrow_array::{Array, ArrowNativeTypeOp, Decimal128Array, PrimitiveArray, Scalar}; use arrow_buffer::i256; use rand::distr::uniform::SampleUniform; use rand::rngs::StdRng; @@ -85,6 +86,80 @@ where .collect() } +/// Checked and wrapping integer arithmetic at DataFusion's default batch size. +/// +/// The left operands come from `a_range` and the right ones from `b_range`, so +/// the checked cases never overflow in a valid row unless the case name says +/// so. Null slots hold 0, as a builder writes them, so with unsigned types +/// `subtract_checked_scalar` overflows in null slots. +fn integer_benchmark<T>( + c: &mut Criterion, + name: &str, + a_range: Range<T::Native>, + b_range: Range<T::Native>, +) where + T: ArrowPrimitiveType, + T::Native: SampleUniform, +{ + const BATCH_SIZE: usize = 8192; + let one = T::Native::ONE; + let max = T::Native::MAX_TOTAL_ORDER; + for null_density in [0., 0.1] { + let a = seeded_array::<T>(BATCH_SIZE, null_density, a_range.clone(), 1); + let b = seeded_array::<T>(BATCH_SIZE, null_density, b_range.clone(), 2); + let scalar = Scalar::new(seeded_array::<T>(1, 0., one..b_range.end, 3)); + + c.bench_function(&format!("{name}_add({null_density})"), |bench| { + bench.iter(|| hint::black_box(add_wrapping(&a, &b).unwrap())) + }); + c.bench_function(&format!("{name}_add_checked({null_density})"), |bench| { + bench.iter(|| hint::black_box(add(&a, &b).unwrap())) + }); + c.bench_function( + &format!("{name}_add_checked_scalar({null_density})"), + |bench| bench.iter(|| hint::black_box(add(&a, &scalar).unwrap())), + ); + c.bench_function(&format!("{name}_subtract({null_density})"), |bench| { + bench.iter(|| hint::black_box(sub_wrapping(&a, &b).unwrap())) + }); + c.bench_function( + &format!("{name}_subtract_checked({null_density})"), + |bench| bench.iter(|| hint::black_box(sub(&a, &b).unwrap())), + ); + c.bench_function( + &format!("{name}_subtract_checked_scalar({null_density})"), + |bench| bench.iter(|| hint::black_box(sub(&a, &scalar).unwrap())), + ); + c.bench_function(&format!("{name}_multiply({null_density})"), |bench| { + bench.iter(|| hint::black_box(mul_wrapping(&a, &b).unwrap())) + }); + c.bench_function( + &format!("{name}_multiply_checked({null_density})"), + |bench| bench.iter(|| hint::black_box(mul(&a, &b).unwrap())), + ); + } + + // Overflow in the last row, so the whole array is processed before the error. + let mut values = seeded_array::<T>(BATCH_SIZE, 0., a_range.clone(), 4) + .values() + .to_vec(); + values[BATCH_SIZE - 1] = max; + let overflow = PrimitiveArray::<T>::from_iter_values(values); + let one = PrimitiveArray::<T>::new_scalar(one); + c.bench_function(&format!("{name}_add_checked_overflow"), |bench| { + bench.iter(|| hint::black_box(add(&overflow, &one).unwrap_err())) + }); + + // Null slots hold `max`, which overflows, but no valid row does. + let a = seeded_array::<T>(BATCH_SIZE, 0.1, a_range, 5); + let b = seeded_array::<T>(BATCH_SIZE, 0., T::Native::ONE..b_range.end, 6); + let values = (0..BATCH_SIZE).map(|i| if a.is_null(i) { max } else { a.value(i) }); + let null_overflow = PrimitiveArray::<T>::new(values.collect(), a.nulls().cloned()); + c.bench_function(&format!("{name}_add_checked_null_slot_overflow"), |bench| { + bench.iter(|| hint::black_box(add(&null_overflow, &b).unwrap())) + }); +} + /// Decimal arithmetic at DataFusion's default batch size. /// /// Values stay within six digits, so the cases never overflow unless the case @@ -222,5 +297,18 @@ fn decimal_benchmark(c: &mut Criterion) { }); } -criterion_group!(benches, add_benchmark, decimal_benchmark); +fn integer_benchmarks(c: &mut Criterion) { + integer_benchmark::<Int32Type>(c, "int32", -1000..1000, -1000..1000); + integer_benchmark::<Int64Type>(c, "int64", -1000..1000, -1000..1000); + // The left operands are larger, so that subtraction doesn't overflow. + integer_benchmark::<UInt32Type>(c, "uint32", 1000..2000, 0..1000); + integer_benchmark::<UInt64Type>(c, "uint64", 1000..2000, 0..1000); +} + +criterion_group!( + benches, + add_benchmark, + integer_benchmarks, + decimal_benchmark +); criterion_main!(benches);
