Skip to main content

elem_simd_math/
dispatch.rs

1//! Slice entry points: elementwise application over contiguous buffers.
2//!
3//! Every function writes `dst[i] = f(src[i])` for all `i`, using the best SIMD level the CPU
4//! supports at runtime. `dst` may be uninitialized storage: each element is written exactly once
5//! on success, so callers do not have to zero-fill a buffer that is fully overwritten.
6//!
7//! Without the (default) `simd` feature the implementations fall back to the platform's scalar
8//! transcendental functions. Functions with no scalar equivalent in the standard library
9//! (`erf`, `erfc`, `tgamma`, `lgamma`, `sinpi`, `cospi`, `sincospi`) are only available with
10//! `simd`; they would otherwise need a second scalar implementation of SLEEF to stay honest
11//! about their error bounds.
12
13use core::mem::MaybeUninit;
14
15/// The source and destination lengths differ.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub struct LengthMismatch {
18    /// Number of elements in the first input slice.
19    pub src: usize,
20    /// Number of elements in the destination slice.
21    pub dst: usize,
22}
23
24impl core::fmt::Display for LengthMismatch {
25    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
26        write!(
27            f,
28            "input has {} elements but the destination has {}",
29            self.src, self.dst
30        )
31    }
32}
33
34impl std::error::Error for LengthMismatch {}
35
36/// Elementwise math over contiguous slices.
37///
38/// Implemented for `f64`. The accuracy tier and error bound of each function are
39/// documented on the kernels in [`crate::f64x`]; each method selects the most
40/// accurate tier available for that function. The tier-specific entry points are the `*_u35`
41/// free functions in [`crate::f64`].
42pub trait ElementwiseMath: Copy + 'static {
43    /// Natural exponential function; 1.0 ULP.
44    fn exp(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
45    /// Base-2 exponential function; 1.0 ULP.
46    fn exp2(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
47    /// Base-10 exponential function; 1.09 ULP.
48    fn exp10(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
49    /// Natural exponential function minus one; 1.0 ULP.
50    fn expm1(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
51    /// Natural logarithm; 1.0 ULP.
52    fn log(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
53    /// Base-2 logarithm; 1.0 ULP.
54    fn log2(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
55    /// Base-10 logarithm; 1.0 ULP.
56    fn log10(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
57    /// Logarithm of one plus the argument; 1.0 ULP.
58    fn log1p(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
59    /// Sine function; 1.0 ULP.
60    fn sin(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
61    /// Cosine function; 1.0 ULP.
62    fn cos(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
63    /// Tangent function; 1.0 ULP.
64    fn tan(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
65    /// Arc sine function; 1.0 ULP.
66    fn asin(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
67    /// Arc cosine function; 1.0 ULP.
68    fn acos(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
69    /// Arc tangent function; 1.0 ULP.
70    fn atan(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
71    /// Hyperbolic sine function; 1.0 ULP.
72    fn sinh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
73    /// Hyperbolic cosine function; 1.0 ULP.
74    fn cosh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
75    /// Hyperbolic tangent function; 1.0 ULP.
76    fn tanh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
77    /// Inverse hyperbolic sine function; 1.0 ULP.
78    fn asinh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
79    /// Inverse hyperbolic cosine function; 1.0 ULP.
80    fn acosh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
81    /// Inverse hyperbolic tangent function; 1.0 ULP.
82    fn atanh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
83    /// Cube root function; 1.0 ULP.
84    fn cbrt(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
85    /// Square root function; `0.5001 ULP`.
86    fn sqrt(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch>;
87    /// Argument raised to an argument power; 1.0 ULP.
88    fn pow(lhs: &[Self], rhs: &[Self], dst: &mut [MaybeUninit<Self>])
89        -> Result<(), LengthMismatch>;
90    /// Arc tangent of two arguments; 1.0 ULP.
91    fn atan2(
92        lhs: &[Self],
93        rhs: &[Self],
94        dst: &mut [MaybeUninit<Self>],
95    ) -> Result<(), LengthMismatch>;
96    /// Euclidean distance in two dimensions; `0.5001 ULP`.
97    fn hypot(
98        lhs: &[Self],
99        rhs: &[Self],
100        dst: &mut [MaybeUninit<Self>],
101    ) -> Result<(), LengthMismatch>;
102    /// Sine and cosine together; 1.0 ULP.
103    fn sincos(
104        src: &[Self],
105        sin: &mut [MaybeUninit<Self>],
106        cos: &mut [MaybeUninit<Self>],
107    ) -> Result<(), LengthMismatch>;
108}
109
110/// Writes `f(src[i])` into every slot of `dst`.
111#[cfg_attr(feature = "simd", allow(dead_code))]
112pub(crate) fn scalar_apply<T: Copy>(src: &[T], dst: &mut [MaybeUninit<T>], f: impl Fn(T) -> T) {
113    for (slot, &value) in dst.iter_mut().zip(src.iter()) {
114        slot.write(f(value));
115    }
116}
117
118/// Writes `f(src[i])` into every slot of the two destinations.
119#[cfg_attr(feature = "simd", allow(dead_code))]
120pub(crate) fn scalar_apply_ff<T: Copy>(
121    src: &[T],
122    first: &mut [MaybeUninit<T>],
123    second: &mut [MaybeUninit<T>],
124    f: impl Fn(T) -> (T, T),
125) {
126    for ((slot_a, slot_b), &value) in first.iter_mut().zip(second.iter_mut()).zip(src.iter()) {
127        let (a, b) = f(value);
128        slot_a.write(a);
129        slot_b.write(b);
130    }
131}
132
133/// Writes `f(lhs[i], rhs[i])` into every slot of `dst`.
134#[cfg_attr(feature = "simd", allow(dead_code))]
135pub(crate) fn scalar_apply2<T: Copy>(
136    lhs: &[T],
137    rhs: &[T],
138    dst: &mut [MaybeUninit<T>],
139    f: impl Fn(T, T) -> T,
140) {
141    for ((slot, &a), &b) in dst.iter_mut().zip(lhs.iter()).zip(rhs.iter()) {
142        slot.write(f(a, b));
143    }
144}
145
146macro_rules! binary {
147        ($($name:ident, $kernel:path, $scalar:expr, $doc:literal;)*) => {
148            $(
149                #[doc = $doc]
150                #[inline]
151                pub fn $name(
152                    lhs: &[Scalar],
153                    rhs: &[Scalar],
154                    dst: &mut [MaybeUninit<Scalar>],
155                ) -> Result<(), LengthMismatch> {
156                    lengths2(lhs.len(), rhs.len(), dst.len())?;
157                    #[cfg(feature = "simd")]
158                    {
159                        let level = fearless_simd::Level::new();
160                        fearless_simd::dispatch!(level, simd => run2(simd, $kernel, lhs, rhs, dst));
161                    }
162                    #[cfg(not(feature = "simd"))]
163                    {
164                        scalar_apply2(lhs, rhs, dst, $scalar);
165                    }
166                    Ok(())
167                }
168            )*
169        };
170    }
171
172macro_rules! unary {
173        ($($name:ident, $kernel:path, $scalar:expr, $doc:literal;)*) => {
174            $(
175                #[doc = $doc]
176                #[inline]
177                pub fn $name(
178                    src: &[Scalar],
179                    dst: &mut [MaybeUninit<Scalar>],
180                ) -> Result<(), LengthMismatch> {
181                    lengths(src.len(), dst.len())?;
182                    #[cfg(feature = "simd")]
183                    {
184                        let level = fearless_simd::Level::new();
185                        fearless_simd::dispatch!(level, simd => run(simd, $kernel, src, dst));
186                    }
187                    #[cfg(not(feature = "simd"))]
188                    {
189                        scalar_apply(src, dst, $scalar);
190                    }
191                    Ok(())
192                }
193            )*
194        };
195    }
196
197macro_rules! pair {
198        ($($name:ident, $kernel:path, $scalar:expr, $doc:literal;)*) => {
199            $(
200                #[doc = $doc]
201                #[inline]
202                pub fn $name(
203                    src: &[Scalar],
204                    first: &mut [MaybeUninit<Scalar>],
205                    second: &mut [MaybeUninit<Scalar>],
206                ) -> Result<(), LengthMismatch> {
207                    lengths(src.len(), first.len())?;
208                    lengths(src.len(), second.len())?;
209                    #[cfg(feature = "simd")]
210                    {
211                        let level = fearless_simd::Level::new();
212                        fearless_simd::dispatch!(level, simd => run_ff(simd, $kernel, src, first, second));
213                    }
214                    #[cfg(not(feature = "simd"))]
215                    {
216                        scalar_apply_ff(src, first, second, $scalar);
217                    }
218                    Ok(())
219                }
220            )*
221        };
222    }
223
224/// Generates the flat-slice entry points for one scalar type.
225///
226/// `$modname` is the module to create, `$ty` the scalar, `$vec` the matching
227/// [`fearless_simd`] vector type and `$kernels` the module holding the vector kernels. Both
228/// instantiations must expose the same function names, so the tier modules drop the `f` suffix
229/// that upstream `sleef-rs` uses for `f32`.
230macro_rules! slice_api {
231    ($modname:ident, $ty:ty, $vec:ident, $kernels:ident) => {
232pub mod $modname {
233    //! Slice entry points for a scalar type.
234
235    use super::LengthMismatch;
236    #[cfg(not(feature = "simd"))]
237    use super::{scalar_apply, scalar_apply2, scalar_apply_ff};
238    #[cfg(feature = "simd")]
239    use crate::common::$vec;
240    use core::mem::MaybeUninit;
241
242    /// The scalar this instantiation works on; the tier macros below name it by alias so that a
243    /// single definition can serve both dtypes.
244    type Scalar = $ty;
245
246    /// The module holding the vector kernels for `Scalar`.
247    #[cfg(feature = "simd")]
248    use crate::$kernels as xkernels;
249
250    #[cfg(feature = "simd")]
251    use fearless_simd::prelude::*;
252    #[cfg(feature = "simd")]
253    use fearless_simd::Simd;
254
255    fn lengths(src: usize, dst: usize) -> Result<(), LengthMismatch> {
256        if src == dst {
257            Ok(())
258        } else {
259            Err(LengthMismatch { src, dst })
260        }
261    }
262
263    fn lengths2(lhs: usize, rhs: usize, dst: usize) -> Result<(), LengthMismatch> {
264        if lhs == rhs && lhs == dst {
265            Ok(())
266        } else {
267            Err(LengthMismatch {
268                src: lhs.min(rhs),
269                dst,
270            })
271        }
272    }
273
274    /// A unary kernel over native-width vectors.
275    #[cfg(feature = "simd")]
276    type UnaryKernel<S> = fn(S, crate::common::$vec<S>) -> crate::common::$vec<S>;
277
278    /// Applies a unary `kernel` lane-wise over `src`, writing `dst`.
279    ///
280    /// The elements past the last whole vector are handled by running the same kernel over a
281    /// padded copy, so every element goes through the kernel and the documented error bound
282    /// applies to the whole result — including the short inputs where the platform's scalar
283    /// functions are measurably worse than the kernel.
284    // `#[inline(always)]` is required by `fearless_simd`: the code called from a `dispatch!`
285    // closure is only compiled with the selected level's target features if it is inlined into
286    // that closure.
287    #[cfg(feature = "simd")]
288    #[inline(always)]
289    fn run<S: Simd>(simd: S, kernel: UnaryKernel<S>, src: &[$ty], dst: &mut [MaybeUninit<$ty>]) {
290        let n = crate::common::$vec::<S>::LEN;
291        let mut chunks = src.chunks_exact(n);
292        let mut out_chunks = dst.chunks_exact_mut(n);
293        for (chunk, out) in (&mut chunks).zip(&mut out_chunks) {
294            let v = crate::common::$vec::<S>::from_slice(simd, chunk);
295            let r = kernel(simd, v);
296            let arr = r.to_array();
297            for (slot, &value) in out.iter_mut().zip(arr.as_ref().iter()) {
298                slot.write(value);
299            }
300        }
301        let tail = chunks.remainder();
302        let out_tail = out_chunks.into_remainder();
303        if tail.is_empty() {
304            return;
305        }
306        let mut padded = $vec::<S>::splat(simd, 0.0).to_array();
307        for (slot, &value) in padded.as_mut().iter_mut().zip(tail.iter()) {
308            *slot = value;
309        }
310        let v = $vec::<S>::load_array(simd, padded);
311        let arr = kernel(simd, v).to_array();
312        for (slot, &value) in out_tail.iter_mut().zip(arr.as_ref().iter()) {
313            slot.write(value);
314        }
315    }
316
317    /// Applies a binary `kernel` lane-wise over `lhs` and `rhs`, writing `dst`.
318    #[cfg(feature = "simd")]
319    #[inline(always)]
320    fn run2<S: Simd>(
321        simd: S,
322        kernel: fn(S, crate::common::$vec<S>, crate::common::$vec<S>) -> crate::common::$vec<S>,
323        lhs: &[$ty],
324        rhs: &[$ty],
325        dst: &mut [MaybeUninit<$ty>],
326    ) {
327        let n = crate::common::$vec::<S>::LEN;
328        let mut lhs_chunks = lhs.chunks_exact(n);
329        let mut rhs_chunks = rhs.chunks_exact(n);
330        let mut out_chunks = dst.chunks_exact_mut(n);
331        for ((a, b), out) in (&mut lhs_chunks).zip(&mut rhs_chunks).zip(&mut out_chunks) {
332            let va = crate::common::$vec::<S>::from_slice(simd, a);
333            let vb = crate::common::$vec::<S>::from_slice(simd, b);
334            let r = kernel(simd, va, vb);
335            let arr = r.to_array();
336            for (slot, &value) in out.iter_mut().zip(arr.as_ref().iter()) {
337                slot.write(value);
338            }
339        }
340        let (ta, tb) = (lhs_chunks.remainder(), rhs_chunks.remainder());
341        let out_tail = out_chunks.into_remainder();
342        if ta.is_empty() {
343            return;
344        }
345        let mut pa = $vec::<S>::splat(simd, 0.0).to_array();
346        let mut pb = $vec::<S>::splat(simd, 0.0).to_array();
347        for (slot, &value) in pa.as_mut().iter_mut().zip(ta.iter()) {
348            *slot = value;
349        }
350        for (slot, &value) in pb.as_mut().iter_mut().zip(tb.iter()) {
351            *slot = value;
352        }
353        let arr = kernel(
354            simd,
355            $vec::<S>::load_array(simd, pa),
356            $vec::<S>::load_array(simd, pb),
357        )
358        .to_array();
359        for (slot, &value) in out_tail.iter_mut().zip(arr.as_ref().iter()) {
360            slot.write(value);
361        }
362    }
363
364    /// A kernel that produces two vectors from one.
365    #[cfg(feature = "simd")]
366    type FfKernel<S> =
367        fn(S, crate::common::$vec<S>) -> (crate::common::$vec<S>, crate::common::$vec<S>);
368
369    /// Applies a `kernel` returning two vectors, writing `sin` and `cos`.
370    ///
371    /// The tail is handled the same way as in [`run`]: by `scalar` when one is given, otherwise by
372    /// running the same vector kernel over a padded copy.
373    #[cfg(feature = "simd")]
374    #[inline(always)]
375    fn run_ff<S: Simd>(
376        simd: S,
377        kernel: FfKernel<S>,
378        src: &[$ty],
379        first: &mut [MaybeUninit<$ty>],
380        second: &mut [MaybeUninit<$ty>],
381    ) {
382        let n = crate::common::$vec::<S>::LEN;
383        let mut chunks = src.chunks_exact(n);
384        let mut first_chunks = first.chunks_exact_mut(n);
385        let mut second_chunks = second.chunks_exact_mut(n);
386        for ((chunk, out_a), out_b) in (&mut chunks).zip(&mut first_chunks).zip(&mut second_chunks)
387        {
388            let v = crate::common::$vec::<S>::from_slice(simd, chunk);
389            let (a, b) = kernel(simd, v);
390            let arr_a = a.to_array();
391            let arr_b = b.to_array();
392            for (slot, &value) in out_a.iter_mut().zip(arr_a.as_ref().iter()) {
393                slot.write(value);
394            }
395            for (slot, &value) in out_b.iter_mut().zip(arr_b.as_ref().iter()) {
396                slot.write(value);
397            }
398        }
399        let tail = chunks.remainder();
400        let first_tail = first_chunks.into_remainder();
401        let second_tail = second_chunks.into_remainder();
402        if tail.is_empty() {
403            return;
404        }
405        let mut padded = $vec::<S>::splat(simd, 0.0).to_array();
406        for (slot, &value) in padded.as_mut().iter_mut().zip(tail.iter()) {
407            *slot = value;
408        }
409        let (a, b) = kernel(simd, $vec::<S>::load_array(simd, padded));
410        let (arr_a, arr_b) = (a.to_array(), b.to_array());
411        for ((slot_a, slot_b), (&va, &vb)) in first_tail
412            .iter_mut()
413            .zip(second_tail.iter_mut())
414            .zip(arr_a.as_ref().iter().zip(arr_b.as_ref().iter()))
415        {
416            slot_a.write(va);
417            slot_b.write(vb);
418        }
419    }
420
421
422
423    unary! {
424        exp,        xkernels::u10::exp,        <$ty>::exp,      "Natural exponential function; 1.0 ULP.";
425        exp2,       xkernels::u10::exp2,       <$ty>::exp2,     "Base-2 exponential function; 1.0 ULP.";
426        exp10,      xkernels::u10::exp10,      |v: $ty| <$ty>::powf(10.0, v),    "Base-10 exponential function; 1.09 ULP.";
427        expm1,      xkernels::u10::expm1,      <$ty>::exp_m1,   "Natural exponential function minus one; 1.0 ULP.";
428        log,        xkernels::u10::log,        <$ty>::ln,       "Natural logarithm; 1.0 ULP.";
429        log2,       xkernels::u10::log2,       <$ty>::log2,     "Base-2 logarithm; 1.0 ULP.";
430        log10,      xkernels::u10::log10,      <$ty>::log10,    "Base-10 logarithm; 1.0 ULP.";
431        log1p,      xkernels::u10::log1p,      <$ty>::ln_1p,    "Logarithm of one plus the argument; 1.0 ULP.";
432        sin,        xkernels::u10::sin,        <$ty>::sin,      "Sine function; 1.0 ULP.";
433        cos,        xkernels::u10::cos,        <$ty>::cos,      "Cosine function; 1.0 ULP.";
434        tan,        xkernels::u10::tan,        <$ty>::tan,      "Tangent function; 1.0 ULP.";
435        asin,       xkernels::u10::asin,       <$ty>::asin,     "Arc sine function; 1.0 ULP.";
436        acos,       xkernels::u10::acos,       <$ty>::acos,     "Arc cosine function; 1.0 ULP.";
437        atan,       xkernels::u10::atan,       <$ty>::atan,     "Arc tangent function; 1.0 ULP.";
438        sinh,       xkernels::u10::sinh,       <$ty>::sinh,     "Hyperbolic sine function; 1.0 ULP.";
439        cosh,       xkernels::u10::cosh,       <$ty>::cosh,     "Hyperbolic cosine function; 1.0 ULP.";
440        tanh,       xkernels::u10::tanh,       <$ty>::tanh,     "Hyperbolic tangent function; 1.0 ULP.";
441        asinh,      xkernels::u10::asinh,      <$ty>::asinh,    "Inverse hyperbolic sine function; 1.0 ULP.";
442        acosh,      xkernels::u10::acosh,      <$ty>::acosh,    "Inverse hyperbolic cosine function; 1.0 ULP.";
443        atanh,      xkernels::u10::atanh,      <$ty>::atanh,    "Inverse hyperbolic tangent function; 1.0 ULP.";
444        cbrt,       xkernels::u10::cbrt,       <$ty>::cbrt,     "Cube root function; 1.0 ULP.";
445        sin_deterministic, xkernels::u10::sin_deterministic, <$ty>::sin,
446            "Sine, bitwise identical across lanes and platforms; 1.0 ULP.";
447        cos_deterministic, xkernels::u10::cos_deterministic, <$ty>::cos,
448            "Cosine, bitwise identical across lanes and platforms; 1.0 ULP.";
449        tan_deterministic, xkernels::u10::tan_deterministic, <$ty>::tan,
450            "Tangent, bitwise identical across lanes and platforms; 1.0 ULP.";
451        sqrt,       crate::common::hw_sqrt,    <$ty>::sqrt,    "Square root; 0.5 ULP.";
452    }
453
454
455
456    unary! {
457        sin_u35,   xkernels::u35::sin,   <$ty>::sin,    "Sine function, 3.5 ULP tier.";
458        cos_u35,   xkernels::u35::cos,   <$ty>::cos,    "Cosine function, 3.5 ULP tier.";
459        tan_u35,   xkernels::u35::tan,   <$ty>::tan,    "Tangent function, 3.5 ULP tier.";
460        asin_u35,  xkernels::u35::asin,  <$ty>::asin,   "Arc sine function, 3.5 ULP tier.";
461        acos_u35,  xkernels::u35::acos,  <$ty>::acos,   "Arc cosine function, 3.5 ULP tier.";
462        atan_u35,  xkernels::u35::atan,  <$ty>::atan,   "Arc tangent function, 3.5 ULP tier.";
463        sinh_u35,  xkernels::u35::sinh,  <$ty>::sinh,   "Hyperbolic sine, 3.5 ULP tier.";
464        cosh_u35,  xkernels::u35::cosh,  <$ty>::cosh,   "Hyperbolic cosine, 3.5 ULP tier.";
465        tanh_u35,  xkernels::u35::tanh,  <$ty>::tanh,   "Hyperbolic tangent, 3.5 ULP tier.";
466        log_u35,   xkernels::u35::log,   <$ty>::ln,     "Natural logarithm, 3.5 ULP tier.";
467        log2_u35,  xkernels::u35::log2,  <$ty>::log2,   "Base-2 logarithm, 3.5 ULP tier.";
468        exp2_u35,  xkernels::u35::exp2,  <$ty>::exp2,   "Base-2 exponential, 3.5 ULP tier.";
469        exp10_u35, xkernels::u35::exp10, |v: $ty| <$ty>::powf(10.0, v), "Base-10 exponential, 3.5 ULP tier.";
470        cbrt_u35,  xkernels::u35::cbrt,  <$ty>::cbrt,   "Cube root, 3.5 ULP tier.";
471        sin_deterministic_u35, xkernels::u35::sin_deterministic, <$ty>::sin,
472            "Sine, lane-order independent, 3.5 ULP tier.";
473        cos_deterministic_u35, xkernels::u35::cos_deterministic, <$ty>::cos,
474            "Cosine, lane-order independent, 3.5 ULP tier.";
475        tan_deterministic_u35, xkernels::u35::tan_deterministic, <$ty>::tan,
476            "Tangent, lane-order independent, 3.5 ULP tier.";
477    }
478
479    pair! {
480        sincos, xkernels::u10::sincos, |v: $ty| (v.sin(), v.cos()),
481            "Sine and cosine evaluated together; 1.0 ULP.";
482        sincos_deterministic, xkernels::u10::sincos_deterministic, |v: $ty| (v.sin(), v.cos()),
483            "Sine and cosine together, lane-order independent; 1.0 ULP.";
484        sincos_u35, xkernels::u35::sincos, |v: $ty| (v.sin(), v.cos()),
485            "Sine and cosine evaluated together, 3.5 ULP tier.";
486        sincos_deterministic_u35, xkernels::u35::sincos_deterministic, |v: $ty| (v.sin(), v.cos()),
487            "Sine and cosine together, lane-order independent, 3.5 ULP tier.";
488    }
489
490    /// Sine and cosine of `pi * x` together; `0.506 ULP`.
491    ///
492    /// There is no scalar implementation in the standard library that is accurate enough for
493    /// large arguments, so the tail uses the vector kernel over a padded copy.
494    #[cfg(feature = "simd")]
495    #[inline]
496    pub fn sincospi(
497        src: &[$ty],
498        first: &mut [MaybeUninit<$ty>],
499        second: &mut [MaybeUninit<$ty>],
500    ) -> Result<(), LengthMismatch> {
501        lengths(src.len(), first.len())?;
502        lengths(src.len(), second.len())?;
503        let level = fearless_simd::Level::new();
504        fearless_simd::dispatch!(level, simd => run_ff(simd, xkernels::u05::sincospi, src, first, second));
505        Ok(())
506    }
507
508    /// Sine and cosine of `pi * x` together, 3.5 ULP tier.
509    #[cfg(feature = "simd")]
510    #[inline]
511    pub fn sincospi_u35(
512        src: &[$ty],
513        first: &mut [MaybeUninit<$ty>],
514        second: &mut [MaybeUninit<$ty>],
515    ) -> Result<(), LengthMismatch> {
516        lengths(src.len(), first.len())?;
517        lengths(src.len(), second.len())?;
518        let level = fearless_simd::Level::new();
519        fearless_simd::dispatch!(level, simd => run_ff(simd, xkernels::u35::sincospi, src, first, second));
520        Ok(())
521    }
522
523
524
525    binary! {
526        pow,    xkernels::u10::pow,    |a: $ty, b: $ty| <$ty>::powf(a, b),  "Argument raised to an argument power; 1.0 ULP.";
527        atan2,  xkernels::u10::atan2,  |a: $ty, b: $ty| <$ty>::atan2(a, b), "Arc tangent of two arguments; 1.0 ULP.";
528    }
529
530    /// Euclidean distance in two dimensions; `0.5001 ULP`.
531    #[cfg(feature = "simd")]
532    #[inline]
533    pub fn hypot(
534        lhs: &[$ty],
535        rhs: &[$ty],
536        dst: &mut [MaybeUninit<$ty>],
537    ) -> Result<(), LengthMismatch> {
538        lengths2(lhs.len(), rhs.len(), dst.len())?;
539        let level = fearless_simd::Level::new();
540        fearless_simd::dispatch!(level, simd => run2(simd, xkernels::u05::hypot, lhs, rhs, dst));
541        Ok(())
542    }
543
544    /// Euclidean distance in two dimensions; scalar implementation.
545    #[cfg(not(feature = "simd"))]
546    #[inline]
547    pub fn hypot(
548        lhs: &[$ty],
549        rhs: &[$ty],
550        dst: &mut [MaybeUninit<$ty>],
551    ) -> Result<(), LengthMismatch> {
552        lengths2(lhs.len(), rhs.len(), dst.len())?;
553        scalar_apply2(lhs, rhs, dst, <$ty>::hypot);
554        Ok(())
555    }
556
557    unary! {
558        sigmoid, xkernels::activation::sigmoid,
559            |v: $ty| { let e = (-v.abs()).exp(); if v > 0.0 { 1.0 / (1.0 + e) } else { e / (1.0 + e) } },
560            "Logistic sigmoid `1 / (1 + exp(-x))` in one pass, overflow-free; 2.5 ULP.";
561        silu, xkernels::activation::silu,
562            |v: $ty| { let e = (-v.abs()).exp(); v * if v > 0.0 { 1.0 / (1.0 + e) } else { e / (1.0 + e) } },
563            "SiLU / swish `x * sigmoid(x)` in one pass; 3.5 ULP wherever `exp(-|x|)` is normal (see the kernel for the subnormal tail).";
564        softplus, xkernels::activation::softplus, |v: $ty| v.max(0.0) + (-v.abs()).exp().ln_1p(),
565            "Softplus `log(1 + exp(x))` in one pass, overflow-free; 3.0 ULP.";
566        gelu_tanh, xkernels::activation::gelu_tanh,
567            |v: $ty| 0.5 * v * (1.0 + ((0.797_884_560_802_865_4 as $ty) * (v + (0.044_715 as $ty) * v * v * v)).tanh()),
568            "GELU tanh approximation `x/2 * (1 + tanh(sqrt(2/pi) * (x + 0.044715 x^3)))` in one pass; 3.0 ULP for `x >= 0`, see the kernel for `x < 0`.";
569    }
570
571    /// Exact-form GELU `x/2 * (1 + erf(x / sqrt(2)))` in one pass. See the kernel
572    /// ([`crate::f32x::activation::gelu`] / [`crate::f64x::activation::gelu`]) for
573    /// the error bound: the `f32` kernel evaluates `erf` as PyTorch's CPU GELU does
574    /// (absolute error about `5e-7` on `erf` after rounding, so `3.0e-7 * |x|` plus
575    /// 3 ULP on the result), the `f64` kernel uses the 1.0 ULP `erf`.
576    #[cfg(feature = "simd")]
577    #[inline]
578    pub fn gelu(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
579        lengths(src.len(), dst.len())?;
580        let level = fearless_simd::Level::new();
581        fearless_simd::dispatch!(level, simd => run(simd, xkernels::activation::gelu, src, dst));
582        Ok(())
583    }
584
585    /// Error function; 1.0 ULP.
586    #[cfg(feature = "simd")]
587    #[inline]
588    pub fn erf(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
589        lengths(src.len(), dst.len())?;
590        let level = fearless_simd::Level::new();
591        fearless_simd::dispatch!(level, simd => run(simd, xkernels::u10::erf, src, dst));
592        Ok(())
593    }
594
595    /// Complementary error function; `max(1.5, 2.5) ULP`.
596    #[cfg(feature = "simd")]
597    #[inline]
598    pub fn erfc(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
599        lengths(src.len(), dst.len())?;
600        let level = fearless_simd::Level::new();
601        fearless_simd::dispatch!(level, simd => run(simd, xkernels::u15::erfc, src, dst));
602        Ok(())
603    }
604
605    /// Gamma function; 1.0 ULP.
606    #[cfg(feature = "simd")]
607    #[inline]
608    pub fn tgamma(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
609        lengths(src.len(), dst.len())?;
610        let level = fearless_simd::Level::new();
611        fearless_simd::dispatch!(level, simd => run(simd, xkernels::u10::tgamma, src, dst));
612        Ok(())
613    }
614
615    /// Logarithm of the absolute gamma function; 1.0 ULP.
616    #[cfg(feature = "simd")]
617    #[inline]
618    pub fn lgamma(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
619        lengths(src.len(), dst.len())?;
620        let level = fearless_simd::Level::new();
621        fearless_simd::dispatch!(level, simd => run(simd, xkernels::u10::lgamma, src, dst));
622        Ok(())
623    }
624
625    /// Sine of `pi * x`; `0.506 ULP`.
626    #[cfg(feature = "simd")]
627    #[inline]
628    pub fn sinpi(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
629        lengths(src.len(), dst.len())?;
630        let level = fearless_simd::Level::new();
631        fearless_simd::dispatch!(level, simd => run(simd, xkernels::u05::sinpi, src, dst));
632        Ok(())
633    }
634
635    /// Cosine of `pi * x`; `0.506 ULP`.
636    #[cfg(feature = "simd")]
637    #[inline]
638    pub fn cospi(src: &[$ty], dst: &mut [MaybeUninit<$ty>]) -> Result<(), LengthMismatch> {
639        lengths(src.len(), dst.len())?;
640        let level = fearless_simd::Level::new();
641        fearless_simd::dispatch!(level, simd => run(simd, xkernels::u05::cospi, src, dst));
642        Ok(())
643    }
644}
645
646impl ElementwiseMath for $ty {
647    fn exp(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
648        self::$modname::exp(src, dst)
649    }
650    fn exp2(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
651        self::$modname::exp2(src, dst)
652    }
653    fn exp10(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
654        self::$modname::exp10(src, dst)
655    }
656    fn expm1(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
657        self::$modname::expm1(src, dst)
658    }
659    fn log(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
660        self::$modname::log(src, dst)
661    }
662    fn log2(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
663        self::$modname::log2(src, dst)
664    }
665    fn log10(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
666        self::$modname::log10(src, dst)
667    }
668    fn log1p(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
669        self::$modname::log1p(src, dst)
670    }
671    fn sin(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
672        self::$modname::sin(src, dst)
673    }
674    fn cos(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
675        self::$modname::cos(src, dst)
676    }
677    fn tan(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
678        self::$modname::tan(src, dst)
679    }
680    fn asin(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
681        self::$modname::asin(src, dst)
682    }
683    fn acos(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
684        self::$modname::acos(src, dst)
685    }
686    fn atan(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
687        self::$modname::atan(src, dst)
688    }
689    fn sinh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
690        self::$modname::sinh(src, dst)
691    }
692    fn cosh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
693        self::$modname::cosh(src, dst)
694    }
695    fn tanh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
696        self::$modname::tanh(src, dst)
697    }
698    fn asinh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
699        self::$modname::asinh(src, dst)
700    }
701    fn acosh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
702        self::$modname::acosh(src, dst)
703    }
704    fn atanh(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
705        self::$modname::atanh(src, dst)
706    }
707    fn cbrt(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
708        self::$modname::cbrt(src, dst)
709    }
710    fn sqrt(src: &[Self], dst: &mut [MaybeUninit<Self>]) -> Result<(), LengthMismatch> {
711        self::$modname::sqrt(src, dst)
712    }
713    fn pow(
714        lhs: &[Self],
715        rhs: &[Self],
716        dst: &mut [MaybeUninit<Self>],
717    ) -> Result<(), LengthMismatch> {
718        self::$modname::pow(lhs, rhs, dst)
719    }
720    fn atan2(
721        lhs: &[Self],
722        rhs: &[Self],
723        dst: &mut [MaybeUninit<Self>],
724    ) -> Result<(), LengthMismatch> {
725        self::$modname::atan2(lhs, rhs, dst)
726    }
727    fn hypot(
728        lhs: &[Self],
729        rhs: &[Self],
730        dst: &mut [MaybeUninit<Self>],
731    ) -> Result<(), LengthMismatch> {
732        self::$modname::hypot(lhs, rhs, dst)
733    }
734    fn sincos(
735        src: &[Self],
736        sin_dst: &mut [MaybeUninit<Self>],
737        cos_dst: &mut [MaybeUninit<Self>],
738    ) -> Result<(), LengthMismatch> {
739        self::$modname::sincos(src, sin_dst, cos_dst)
740    }
741}
742    };
743}
744
745slice_api!(f64, f64, F64s, f64x);
746slice_api!(f32, f32, F32s, f32x);