mbutrovich commented on code in PR #12419:
URL: https://github.com/apache/arrow-rs/pull/12419#discussion_r4779025935
##########
arrow-arith/src/numeric.rs:
##########
@@ -1417,6 +1417,177 @@ where
(!divisor.is_zero() && !divisor.is_eq(minus_one)).then_some(divisor)
}
+/// Divides the scaled values of a decimal array by a scalar with a
precomputed divisor
+trait ScalarDivisor: Sized {
+ /// Returns `l * mul / divisor` for [`Op::Div`] or `l * mul % divisor` for
[`Op::Rem`] for
+ /// every valid slot of `l`. Returns `None` for another op, or when it
can't rule out that
+ /// `l * mul` overflows for a slot it divides. `mul` is positive, and
`divisor` is neither 0
+ /// nor -1
+ fn div_rem_scaled<T: ArrowPrimitiveType<Native = Self>>(
+ op: Op,
+ l: &PrimitiveArray<T>,
+ mul: Self,
+ divisor: Self,
+ ) -> Option<PrimitiveArray<T>>;
+}
+
+/// Divides `$l` by `$d`, a `$divisor`, as `divisor_op!` does, and evaluates
to the result.
+/// `$scaled` is the dividend computed from the slot `$n`, and `$out` the
result computed from
+/// the quotient or remainder `$q`
+macro_rules! div_rem_unary {
+ (
+ $op:expr,
+ $l:expr,
+ $max_nulls:expr,
+ $d:expr,
+ $divisor:ident,
+ [$($variant:ident),+],
+ |$n:ident| $scaled:expr,
+ |$q:ident| $out:expr
+ ) => {{
+ let divisor = $d;
+ if $l.null_count() > $max_nulls {
+ // Calling the enum's `wrapping_div_rem`, which matches on the
variant, keeps this to
+ // one `try_unary` per op
+ let Ok(array) = match $op {
+ Op::Div => $l.try_unary::<_, _, Infallible>(move |$n| {
+ let $q = divisor.wrapping_div_rem($scaled).0;
+ Ok($out)
+ }),
+ Op::Rem => $l.try_unary::<_, _, Infallible>(move |$n| {
+ let $q = divisor.wrapping_div_rem($scaled).1;
+ Ok($out)
+ }),
+ _ => return None,
+ };
+ return Some(array);
+ }
+ // Match on the variant once, outside the loop, and move it into the
closure, so the loop
+ // doesn't branch on the variant. The `Op::Div` and `Op::Rem` arms
after the variants
+ // cover variants that arrow-buffer may add later
+ let array = match ($op, divisor) {
+ $(
+ (Op::Div, $divisor::$variant(d)) => $l.unary(move |$n| {
+ let $q = d.wrapping_div_rem($scaled).0;
+ $out
+ }),
+ (Op::Rem, $divisor::$variant(d)) => $l.unary(move |$n| {
+ let $q = d.wrapping_div_rem($scaled).1;
+ $out
+ }),
+ )+
+ (Op::Div, d) => $l.unary(move |$n| {
+ let $q = d.wrapping_div_rem($scaled).0;
+ $out
+ }),
+ (Op::Rem, d) => $l.unary(move |$n| {
+ let $q = d.wrapping_div_rem($scaled).1;
+ $out
+ }),
+ _ => return None,
+ };
+ Some(array)
+ }};
+}
+
+/// Implements [`ScalarDivisor`] for `$t` with `$divisor`, dividing every slot
with `unary`
+/// unless the array has more than `$max_nulls` nulls, as `divisor_op!` does.
+///
+/// With `narrow`, a batch whose scaled values fit in `$narrow` divides in it
with
+/// `$narrow_divisor`, which is faster. `$as_narrow` converts a value of `$t`
that fits
+macro_rules! impl_scalar_divisor {
+ (
+ $t:ty,
+ $divisor:ident,
+ |$len:ident| $max_nulls:expr,
+ [$($variant:ident),+]
+ $(, narrow: $narrow_divisor:ident($narrow:ty),
[$($narrow_variant:ident),+], $as_narrow:expr)?
+ ) => {
+ impl ScalarDivisor for $t {
+ fn div_rem_scaled<T: ArrowPrimitiveType<Native = Self>>(
+ op: Op,
+ l: &PrimitiveArray<T>,
+ mul: Self,
+ divisor: Self,
+ ) -> Option<PrimitiveArray<T>> {
+ let $len = l.len();
+ let max_nulls = $max_nulls;
+ // ORs `v ^ (v >> sign)` over every slot, null or not, because
`unary` divides
+ // null slots as well. Every `v` is then between `-magnitude -
1` and `magnitude`,
+ // so `magnitude < bound` puts every `v` between `-bound` and
`bound`, and
+ // `bound * mul` doesn't overflow for `bound = MAX / mul`. An
OR needs no
+ // comparison per value, but can exceed the largest value by
up to 2x, so an
+ // array close to the bound takes the slower route
+ let sign = (size_of::<$t>() * 8 - 1) as u8;
+ let magnitude = l
+ .values()
+ .iter()
+ .fold(Self::ZERO, |acc, &v| acc | (v ^ (v >> sign)));
+ $(
+ // When `divisor`, `mul` and every scaled value fit in
`$narrow`, so do the
+ // quotient and remainder. They are the same as in `$t`,
because `divisor`
+ // isn't -1
+ let (min, max) = (<$t>::from(<$narrow>::MIN),
<$t>::from(<$narrow>::MAX));
+ let fits = |v: $t| min <= v && v <= max;
+ let bound = max.wrapping_div(mul);
+ if fits(divisor) && fits(mul) && magnitude < bound {
+ // The checks above make `$as_narrow` exact
+ let m = $as_narrow(mul);
+ return div_rem_unary!(
+ op,
+ l,
+ max_nulls,
+ $narrow_divisor::new($as_narrow(divisor))?,
+ $narrow_divisor,
+ [$($narrow_variant),+],
+ |n| $as_narrow(n).wrapping_mul(m),
+ |q| <$t>::from(q)
+ );
+ }
+ )?
+ // A multiplier of 1 can't overflow
+ let bound = <$t>::MAX.wrapping_div(mul);
+ if !mul.is_eq(Self::ONE) && magnitude >= bound {
+ return None;
+ }
+ div_rem_unary!(
+ op,
+ l,
+ max_nulls,
+ $divisor::new(divisor)?,
+ $divisor,
+ [$($variant),+],
+ |n| n.wrapping_mul(mul),
+ |q| q
+ )
+ }
+ }
+ };
+}
+
+// On x86, `Decimal64`'s `unary` loop over every slot costs more than
`try_unary` over the valid
+// values of a half null array, so it switches at a quarter null
+impl_scalar_divisor!(i32, DivisorI32, |len| len / 2, [PowerOfTwo,
AddIndicator]);
+impl_scalar_divisor!(i64, DivisorI64, |len| len / 4, [PowerOfTwo,
AddIndicator]);
+impl_scalar_divisor!(
+ i128,
+ DivisorI128,
+ |len| len / 2,
Review Comment:
> Since the gain depends on whether the narrow or wide divisor is chosen,
could `max_nulls` be picked per path instead of per type?
Yes. In 0b45c07346 the full-width `DivisorI128` and `DivisorI256` switch to
`try_unary` above a quarter null, and the narrow divisors keep half
([numeric.rs](https://github.com/apache/arrow-rs/blob/0b45c073467988a783dce2a0928c0127e329b052/arrow-arith/src/numeric.rs#L1593-L1612)).
Half null `rem_rescaled` against e3c67be20c, without and with alignment:
| Case | Neoverse-V2 | Xeon | Xeon, `x86-64-v3` |
|---|--:|--:|--:|
| `Decimal128`, before | 1.26x, 1.26x | 0.68x, 0.90x | 0.90x, 0.92x |
| `Decimal128`, now | 1.95x, 1.89x | 1.33x, 1.45x | 1.33x, 1.41x |
| `Decimal256`, before | 0.96x, 0.96x | 0.71x, 0.77x | 0.76x, 0.76x |
| `Decimal256`, now | 1.51x, 1.50x | 1.18x, 1.14x | 1.17x, 1.18x |
The new runs are
[Neoverse-V2](https://github.com/apache/arrow-rs/pull/12419#issuecomment-7359778838)
([aligned](https://github.com/apache/arrow-rs/pull/12419#issuecomment-7360454420)),
[Xeon](https://github.com/apache/arrow-rs/pull/12419#issuecomment-7359796143)
([aligned](https://github.com/apache/arrow-rs/pull/12419#issuecomment-7359799139)),
and [Xeon at
`x86-64-v3`](https://github.com/apache/arrow-rs/pull/12419#issuecomment-7359802079)
([aligned](https://github.com/apache/arrow-rs/pull/12419#issuecomment-7359807371)).
A fifth null stays on `unary`, at 1.10x to 2.05x. No case divides full-width
values by `/` with nulls, so `rem_rescaled` stands in for both ops.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]