Skip to content
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

Make unary and binary faster #6365

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 35 additions & 7 deletions arrow-arith/src/arity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use arrow_buffer::ArrowNativeType;
use arrow_buffer::{Buffer, MutableBuffer};
use arrow_data::ArrayData;
use arrow_schema::ArrowError;
use std::mem::MaybeUninit;
use std::sync::Arc;

/// See [`PrimitiveArray::unary`]
Expand Down Expand Up @@ -205,6 +206,9 @@ where
O: ArrowPrimitiveType,
F: Fn(A::Native, B::Native) -> O::Native,
{
// This is an arbitrary value
const CHUNK_SIZE: usize = 1024;

if a.len() != b.len() {
return Err(ArrowError::ComputeError(
"Cannot perform binary operation on arrays of different length".to_string(),
Expand All @@ -216,15 +220,39 @@ where
}

let nulls = NullBuffer::union(a.logical_nulls().as_ref(), b.logical_nulls().as_ref());
let mut output: Vec<MaybeUninit<O::Native>> = vec![MaybeUninit::uninit(); a.len()];
let a_chunks = a.values().as_ref().chunks_exact(CHUNK_SIZE);
let b_chunks = b.values().as_ref().chunks_exact(CHUNK_SIZE);
let output_chunks = output.as_mut_slice().chunks_exact(CHUNK_SIZE);

for (output, (a_chunk, b_chunk)) in output_chunks.zip(a_chunks.zip(b_chunks)) {
let a_values: [A::Native; CHUNK_SIZE] = a_chunk.try_into().unwrap();
let b_values: [B::Native; CHUNK_SIZE] = b_chunk.try_into().unwrap();
let mut output: [MaybeUninit<O::Native>; CHUNK_SIZE] = output.try_into().unwrap();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, shouldn't this be of type &mut [MaybeUnit<O::Native;> CHUNK_SIZE]? Otherwise this would be writing to a temporary and the compiler would probably optimize it away.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There was a reddit thread about the two different try_into implementations just a few days ago: https://old.reddit.com/r/rust/comments/1f9iyfz/question_if_i_have_a_vect_how_do_i_pass_a_part_of/lllxbo0/

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok that seems to be a key point here, changing that (and let output_chunks = output.as_mut_slice().chunks_exact_mut(CHUNK_SIZE);) seems to make performance worse than the current implementation on master. The thing I don't understand here is that if we write into a temporary value, how do the tests still pass?

Copy link
Contributor

@tustvold tustvold Sep 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you tried running the tests in release mode, it may be the optimiser doesn't "exploit" any UB when in debug mode

Edit: we may also not have any tests of arrays with more than 1024 elements

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah that's the issue, it just never hits that code path, I guess it was just too good to be true.


for (o, (a, b)) in output.iter_mut().zip(a_values.iter().zip(b_values.iter())) {
*o = MaybeUninit::new(op(*a, *b));
}
}

let reminder_len = a.len() % CHUNK_SIZE;
let reminder_range = (a.len() - reminder_len)..a.len();

for (o, (a, b)) in output[reminder_range.clone()].iter_mut().zip(
a.values()[reminder_range.clone()]
.iter()
.zip(b.values()[reminder_range].iter()),
) {
*o = MaybeUninit::new(op(*a, *b));
}

let values = a.values().iter().zip(b.values()).map(|(l, r)| op(*l, *r));
// JUSTIFICATION
// Benefit
// ~60% speedup
// Soundness
// `values` is an iterator with a known size from a PrimitiveArray
let buffer = unsafe { Buffer::from_trusted_len_iter(values) };
Ok(PrimitiveArray::new(buffer.into(), nulls))
// We filled the output array with initialized values up to `self.len()` AND `MaybeUninit<T>` has a transparent layout over `T`
let output = output
.into_iter()
.map(|o| unsafe { o.assume_init() })
.collect::<Vec<_>>();
Ok(PrimitiveArray::new(Buffer::from_vec(output).into(), nulls))
}

/// Applies a binary and infallible function to values in two arrays, replacing
Expand Down
41 changes: 33 additions & 8 deletions arrow-array/src/array/primitive_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ use arrow_schema::{ArrowError, DataType};
use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime};
use half::f16;
use std::any::Any;
use std::mem::MaybeUninit;
use std::sync::Arc;

/// A [`PrimitiveArray`] of `i8`
Expand Down Expand Up @@ -826,15 +827,39 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
O: ArrowPrimitiveType,
F: Fn(T::Native) -> O::Native,
{
let nulls = self.nulls().cloned();
let values = self.values().iter().map(|v| op(*v));
// JUSTIFICATION
// Benefit
// ~60% speedup
// This is an arbitrary value
const CHUNK_SIZE: usize = 1024;

let mut output: Vec<MaybeUninit<O::Native>> = vec![MaybeUninit::uninit(); self.len()];
let values_chunks = self.values().as_ref().chunks_exact(CHUNK_SIZE);
let output_chunks = output.as_mut_slice().chunks_exact(CHUNK_SIZE);

for (output, values) in output_chunks.zip(values_chunks) {
let values: [T::Native; CHUNK_SIZE] = values.try_into().unwrap();
let mut output: [MaybeUninit<O::Native>; CHUNK_SIZE] = output.try_into().unwrap();

for (o, v) in output.iter_mut().zip(values.iter()) {
*o = MaybeUninit::new(op(*v));
}
}

let reminder_len = self.len() % CHUNK_SIZE;
let reminder_range = (self.len() - reminder_len)..self.len();

for (o, v) in output[reminder_range.clone()]
.iter_mut()
.zip(&self.values()[reminder_range])
{
*o = MaybeUninit::new(op(*v));
}

// Soundness
// `values` is an iterator with a known size because arrays are sized.
let buffer = unsafe { Buffer::from_trusted_len_iter(values) };
PrimitiveArray::new(buffer.into(), nulls)
// We filled the output array with initialized values up to `self.len()` AND `MaybeUninit<T>` has a transparent layout over `T`
let output = output
.into_iter()
.map(|o| unsafe { o.assume_init() })
.collect::<Vec<_>>();
PrimitiveArray::new(Buffer::from_vec(output).into(), self.nulls().cloned())
}

/// Applies a unary and infallible function to the array in place if possible.
Expand Down
Loading