andygrove commented on code in PR #12419:
URL: https://github.com/apache/arrow-rs/pull/12419#discussion_r4775428312


##########
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:
   The `rem_rescaled` half null cases on the Xeon are at 0.68x to 0.92x for 
`Decimal128` and 0.71x to 0.77x for `Decimal256`, and your description explains 
why. The wide divisor gains only about 1.3x per value there, so dividing every 
slot loses to dividing the valid half. Since the gain depends on whether the 
narrow or wide divisor is chosen, could `max_nulls` be picked per path instead 
of per type? For example, `len / 2` when the narrow divisor applies and 
something like `len / 4` (as `Decimal64` does) for the wide one. It would be 
good to see the bot numbers for that before merge.



##########
arrow-arith/src/numeric.rs:
##########
@@ -3176,6 +3339,99 @@ mod tests {
         check::<Decimal256Type>();
     }
 
+    /// Checks that `div` and `rem` of `a` by `divisor` at scale `s2` give the 
same results and
+    /// errors as by an array that repeats it, which takes `try_binary`
+    fn check_div_rem_by_scalar<T: DecimalType>(a: &PrimitiveArray<T>, divisor: 
T::Native, s2: i8) {
+        let repeat = |len| {
+            PrimitiveArray::<T>::from_iter_values(vec![divisor; len])
+                .with_precision_and_scale(T::MAX_PRECISION, s2)
+                .unwrap()
+        };
+        let scalar = Scalar::new(repeat(1));
+        let b = repeat(a.len());
+        for kernel in [div, rem] {
+            let msg = format!("{a:?} by {divisor:?} at scale {s2}");
+            match (kernel(a, &scalar), kernel(a, &b)) {
+                (Ok(s), Ok(b)) => assert_eq!(s.to_data(), b.to_data(), 
"{msg}"),
+                (Err(s), Err(b)) => assert_eq!(s.to_string(), b.to_string(), 
"{msg}"),
+                (s, b) => panic!("{msg}: {s:?} != {b:?}"),
+            }
+        }
+    }
+
+    #[test]
+    fn test_decimal_div_rem_by_scalar_bounds() {

Review Comment:
   Could you add a sliced case, for example `a.slice(1, a.len() - 1)` with the 
large value kept in range? The bound is computed from `values()`, so a test 
with a non-zero offset would guard against a future change that reads the 
unsliced buffer.



##########
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]);

Review Comment:
   On the Xeon at the default target, `Decimal32` `rem` at half null is 0.82x 
to 0.83x, while `x86-64-v3` gains 2.44x. Most downstream users build for the 
default target, so would it make sense to tune this threshold on those numbers, 
as you did for `Decimal64`? If the `x86-64-v3` gain is worth keeping, maybe 
`cfg(target_feature = "avx2")` could choose between the two thresholds.



-- 
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]

Reply via email to