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


##########
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:
   > If the `x86-64-v3` gain is worth keeping, maybe `cfg(target_feature = 
"avx2")` could choose between the two thresholds.
   
   Done in 0b45c07346, following the `cfg!` in 
[union_array.rs](https://github.com/apache/arrow-rs/blob/0b45c073467988a783dce2a0928c0127e329b052/arrow-array/src/array/union_array.rs#L852-L858):
 `Decimal32` switches at a quarter null on x86 without AVX2 and at half 
everywhere else 
([numeric.rs](https://github.com/apache/arrow-rs/blob/0b45c073467988a783dce2a0928c0127e329b052/arrow-arith/src/numeric.rs#L1574-L1591)).
 AVX2 is the feature that matters, not SSE4.1. The `AddIndicator` loops take 42 
(`/`) and 48 (`%`) instructions per 4 values at `x86-64`, building each signed 
high product from `pmuludq`. At `x86-64-v2` they still take 34 and 35 per 4. At 
`x86-64-v3` they take 16 per 8 with `vpmuldq`. The gain is worth keeping 
because Comet builds its amd64 library at `x86-64-v3` 
([Makefile](https://github.com/apache/datafusion-comet/blob/785e961704d7559cf0cc8a2e1a8d3ec600a5e302/Makefile#L80-L81)).
   
   At the default target, half null is now 1.09x and 1.28x for `/`, 1.21x and 
1.36x for `%`, and 1.11x and 1.28x for `rem_rescaled`, up from 1.01x, 0.82x, 
and 0.83x. `x86-64-v3` keeps 2.69x to 2.97x, and Neoverse-V2 keeps 3.13x to 
4.02x.



##########
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?
   
   Added in 0b45c07346. Every array in the test is also checked after `slice(1, 
len - 1)`, which keeps the boundary value last 
([numeric.rs](https://github.com/apache/arrow-rs/blob/0b45c073467988a783dce2a0928c0127e329b052/arrow-arith/src/numeric.rs#L3446-L3452)).



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