Repository navigation
perf: Fix performance regression in unary math UDFs #26062
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
d8a5898
c9a5496
fecc357
6617622
72cfc29
3f3f9e1
92e1f62
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one | ||
| // or more contributor license agreements. See the NOTICE file | ||
| // distributed with this work for additional information | ||
| // regarding copyright ownership. The ASF licenses this file | ||
| // to you under the Apache License, Version 2.0 (the | ||
| // "License"); you may not use this file except in compliance | ||
| // with the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| use std::hint::black_box; | ||
| use std::sync::Arc; | ||
|
|
||
| use arrow::array::ArrayRef; | ||
| use arrow::datatypes::{Field, Float32Type, Float64Type}; | ||
| use arrow::util::bench_util::create_primitive_array; | ||
| use criterion::{Criterion, criterion_group}; | ||
| use datafusion_common::config::ConfigOptions; | ||
| use datafusion_expr::{ColumnarValue, ScalarFunctionArgs}; | ||
| use datafusion_functions::math::{degrees, sqrt}; | ||
|
|
||
| const BATCH_SIZE: usize = 8192; | ||
|
|
||
| fn criterion_benchmark(c: &mut Criterion) { | ||
| let config_options = Arc::new(ConfigOptions::default()); | ||
|
|
||
| // Both functions are cheap enough that overhead in the code they share | ||
| // shows up: `sqrt` returns an error for invalid inputs, `degrees` doesn't. | ||
| for function in [sqrt(), degrees()] { | ||
| let mut group = c.benchmark_group(function.name().to_string()); | ||
|
|
||
| for (nulls, null_density) in [("", 0.0), (" with nulls", 0.1)] { | ||
| let arrays: [(&str, ArrayRef); 2] = [ | ||
| ( | ||
| "f64", | ||
| Arc::new(create_primitive_array::<Float64Type>( | ||
| BATCH_SIZE, | ||
| null_density, | ||
| )), | ||
| ), | ||
| ( | ||
| "f32", | ||
| Arc::new(create_primitive_array::<Float32Type>( | ||
| BATCH_SIZE, | ||
| null_density, | ||
| )), | ||
| ), | ||
| ]; | ||
|
|
||
| for (type_name, array) in arrays { | ||
| let field = Arc::new(Field::new("a", array.data_type().clone(), true)); | ||
| let args = vec![ColumnarValue::Array(array)]; | ||
|
|
||
| group.bench_function(format!("{type_name}{nulls}"), |b| { | ||
| b.iter(|| { | ||
| black_box( | ||
| function | ||
| .invoke_with_args(ScalarFunctionArgs { | ||
| args: args.clone(), | ||
| arg_fields: vec![Arc::clone(&field)], | ||
| number_rows: BATCH_SIZE, | ||
| return_field: Arc::clone(&field), | ||
| config_options: Arc::clone(&config_options), | ||
| }) | ||
| .unwrap(), | ||
| ) | ||
| }) | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| group.finish(); | ||
| } | ||
| } | ||
|
|
||
| criterion_group!(benches, criterion_benchmark); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,8 +15,10 @@ | |
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| use arrow::array::ArrowNativeTypeOp; | ||
| use arrow::array::{Array, ArrowNativeTypeOp, ArrowPrimitiveType, PrimitiveArray}; | ||
| use arrow::buffer::BooleanBuffer; | ||
| use arrow::error::ArrowError; | ||
| use datafusion_common::{Result, exec_err}; | ||
| use num_traits::{CheckedMul, CheckedNeg, Signed}; | ||
| use std::fmt::Display; | ||
| use std::mem::swap; | ||
|
|
@@ -150,10 +152,60 @@ pub(crate) fn lcm_signed_int(x: i64, y: i64) -> Result<i64, ArrowError> { | |
| }) | ||
| } | ||
|
|
||
| /// An alternative to `try_unary` that lets the compiler vectorize both the | ||
| /// input check and `op`, for functions that return an error for some argument | ||
| /// values, such as `sqrt`, which returns an error for negative numbers. | ||
| /// | ||
| /// `try_unary` can return early on any value, which keeps the compiler from | ||
| /// vectorizing its loop. Instead, this applies `op` to every value in `array`, | ||
| /// like `unary`, and calls `input_error` on every value, including those in | ||
| /// null slots, in the same loop. Only if some value fails is the array searched | ||
| /// again, ignoring null slots, for an error to report. `input_error` should | ||
| /// therefore be a cheap check, such as a comparison. | ||
| /// | ||
| /// For cheap functions like `sqrt`, this is several times faster than | ||
| /// `try_unary`. But because it also does work for null slots, `try_unary` can | ||
| /// be faster on arrays with many nulls, especially when `op` is expensive and | ||
| /// can't be vectorized anyway. | ||
| pub(crate) fn unary_with_input_check<T: ArrowPrimitiveType>( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this seems like it might be a good one to propose porting upstream to arrows rs (or as an example on
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah, I've been thinking about that. Adding something to Arrow definitely makes sense, although because making the right choice depends on a bunch of factors (e.g., how expensive the op is, whether it is vectorizable, null density, CPU architecture / version of SIMD), we'd want to make sure that users have a clear decision process for which primitive to use. |
||
| array: &PrimitiveArray<T>, | ||
| op: impl Fn(T::Native) -> T::Native, | ||
| input_error: impl Fn(T::Native) -> Option<&'static str>, | ||
| ) -> Result<PrimitiveArray<T>> { | ||
| let mut any_invalid = false; | ||
| let values: Vec<T::Native> = array | ||
| .values() | ||
| .iter() | ||
| .map(|&x| { | ||
| any_invalid |= input_error(x).is_some(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. it is interesting this is mre vectorizable -- I was sot of expecting two loops |
||
| op(x) | ||
| }) | ||
| .collect(); | ||
|
|
||
| // The check above also ran on null slots, which can hold any value, so the | ||
| // failure may be spurious. Re-check every value into a bitmap and mask out | ||
| // the null slots, which is faster than checking only the non-null values one | ||
| // at a time. | ||
| if any_invalid { | ||
| let input = array.values(); | ||
| let mut failed = | ||
| BooleanBuffer::collect_bool(input.len(), |i| input_error(input[i]).is_some()); | ||
| if let Some(nulls) = array.nulls() { | ||
| failed = &failed & nulls.inner(); | ||
| } | ||
| if let Some(message) = failed.set_indices().find_map(|i| input_error(input[i])) { | ||
| return exec_err!("{message}"); | ||
| } | ||
| } | ||
|
|
||
| Ok(PrimitiveArray::new(values.into(), array.nulls().cloned())) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use arrow_buffer::i256; | ||
| use arrow::array::Float64Array; | ||
| use arrow_buffer::{NullBuffer, i256}; | ||
|
|
||
| const GCD_COMMON_TEST_CASES: [(i64, i64, i64); 18] = [ | ||
| // Basic cases | ||
|
|
@@ -317,4 +369,21 @@ mod tests { | |
| ); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_unary_with_input_check() { | ||
| let input_error = |x: f64| (x < 0.0).then_some("negative input"); | ||
|
|
||
| // -1.0 is in a null slot, so it is not an error. | ||
| let array = Float64Array::new( | ||
| vec![4.0, -1.0, 9.0].into(), | ||
| Some(NullBuffer::from(vec![true, false, true])), | ||
| ); | ||
| let result = unary_with_input_check(&array, f64::sqrt, input_error).unwrap(); | ||
| assert_eq!(result, Float64Array::from(vec![Some(2.0), None, Some(3.0)])); | ||
|
|
||
| let array = Float64Array::from(vec![Some(4.0), None, Some(-1.0)]); | ||
| let error = unary_with_input_check(&array, f64::sqrt, input_error).unwrap_err(); | ||
| assert_eq!(error.strip_backtrace(), "Execution error: negative input"); | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.