elem-simd-math 0.1.3

Vectorized elementwise math kernels for f32/f64 over stable-Rust SIMD (port of SLEEF via sleef-rs, on fearless_simd).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! ULP-accuracy tests for the `f64` kernels, against MPFR.
//!
//! The bounds asserted here are the ones `sleef-rs` rev `3671d46` asserts for the same functions.
//! Every test drives the public slice entry points, i.e. the path production uses (runtime
//! dispatch, lane loop, padded tail), over lengths below, at and above the SIMD lane width.

#![cfg(feature = "simd")]

mod common;

use core::mem::MaybeUninit;

use common::{assert_close, check_binary, check_pair, check_unary, read, LENS, PREC};
use elem_simd_math::{f64 as ops, ElementwiseMath, LengthMismatch};
use rug::ops::Pow;
use rug::Float;

/// `sqrt(f64::MAX)`, the upper bound upstream uses for the inverse hyperbolic ranges.
const SQRT_DBL_MAX: f64 = 1.340_780_792_994_259_7e+154;

/// Working precision for the `*pi` oracles.
///
/// `sin(x * pi)` is only as accurate as the fractional part of the product, and near a zero the
/// product loses one bit per bit of `|x|`: at the default 128 bits a half-integer `x` around `2^21`
/// leaves the answer about `x * 2^-128` away from the true zero, which is far outside the asserted
/// sub-ULP bound. The inputs themselves are exact in every precision, so raising the working
/// precision is enough.
const PI_PREC: u32 = 512;

fn sinpi_oracle(x: Float) -> Float {
    (Float::with_val(PI_PREC, &x) * Float::with_val(PI_PREC, rug::float::Constant::Pi)).sin()
}

fn cospi_oracle(x: Float) -> Float {
    (Float::with_val(PI_PREC, &x) * Float::with_val(PI_PREC, rug::float::Constant::Pi)).cos()
}

// ---------------------------------------------------------------- unary ----------

#[test]
fn exp_ulp() {
    check_unary("exp", ops::exp, Float::exp, -1000.0, 710.0, 1.0);
}

#[test]
fn exp2_ulp() {
    check_unary("exp2", ops::exp2, Float::exp2, -2000.0, 1024.0, 1.0);
}

#[test]
fn exp10_ulp() {
    check_unary("exp10", ops::exp10, Float::exp10, -350.0, 308.26, 1.09);
}

#[test]
fn expm1_ulp() {
    check_unary("expm1", ops::expm1, Float::exp_m1, -37.0, 710.0, 1.0);
}

#[test]
fn log_ulp() {
    check_unary("log", ops::log, Float::ln, 0.0, f64::MAX, 1.0);
}

#[test]
fn log2_ulp() {
    check_unary("log2", ops::log2, Float::log2, 0.0, f64::MAX, 1.0);
}

#[test]
fn log10_ulp() {
    check_unary("log10", ops::log10, Float::log10, 0.0, f64::MAX, 1.0);
}

#[test]
fn log1p_ulp() {
    check_unary("log1p", ops::log1p, Float::ln_1p, -1.0, 1e307, 1.0);
}

/// `log1p` is finite at the top of the range: `d + 1` overflows there, but the logarithm does not.
/// The uniform sampler never lands on `f64::MAX`, so the tail is checked explicitly.
#[test]
fn log1p_large_arguments() {
    // Tail and ordinary arguments share vectors at every width, and the length leaves a remainder,
    // so a lane-mixed vector takes the tail branch and the ordinary lanes must still be right.
    let mixed: [f64; 9] = [
        0.5,
        1e307,
        -0.25,
        1e308,
        3.0,
        f64::MAX,
        1e-10,
        f64::INFINITY,
        7.5,
    ];
    let src: Vec<f64> = mixed.iter().copied().cycle().take(37).collect();
    let mut out: Vec<MaybeUninit<f64>> = vec![MaybeUninit::uninit(); src.len()];
    ops::log1p(&src, &mut out).expect("length check");
    for (lane, (got, &x)) in read(out).iter().zip(src.iter()).enumerate() {
        assert_close(
            "log1p large",
            0,
            lane,
            x,
            *got,
            &Float::with_val(PREC, x).ln_1p(),
            1.0,
        );
    }
}

#[test]
fn sin_ulp() {
    check_unary("sin", ops::sin, Float::sin, f64::MIN, f64::MAX, 1.0);
}

#[test]
fn cos_ulp() {
    check_unary("cos", ops::cos, Float::cos, f64::MIN, f64::MAX, 1.0);
}

#[test]
fn tan_ulp() {
    check_unary("tan", ops::tan, Float::tan, f64::MIN, f64::MAX, 1.0);
}

#[test]
fn sin_u35_ulp() {
    check_unary("sin_u35", ops::sin_u35, Float::sin, f64::MIN, f64::MAX, 3.5);
}

#[test]
fn cos_u35_ulp() {
    check_unary("cos_u35", ops::cos_u35, Float::cos, f64::MIN, f64::MAX, 3.5);
}

#[test]
fn tan_u35_ulp() {
    check_unary("tan_u35", ops::tan_u35, Float::tan, f64::MIN, f64::MAX, 3.5);
}

#[test]
fn log_u35_ulp() {
    check_unary("log_u35", ops::log_u35, Float::ln, 0.0, f64::MAX, 3.5);
}

#[test]
fn tanh_u35_ulp() {
    check_unary("tanh_u35", ops::tanh_u35, Float::tanh, -19.0, 19.0, 3.5);
}

#[test]
fn asin_ulp() {
    check_unary("asin", ops::asin, Float::asin, -1.0, 1.0, 1.0);
}

#[test]
fn acos_ulp() {
    check_unary("acos", ops::acos, Float::acos, -1.0, 1.0, 1.0);
}

#[test]
fn atan_ulp() {
    check_unary("atan", ops::atan, Float::atan, f64::MIN, f64::MAX, 1.0);
}

#[test]
fn sinh_ulp() {
    check_unary("sinh", ops::sinh, Float::sinh, -709.0, 709.0, 1.0);
}

#[test]
fn cosh_ulp() {
    check_unary("cosh", ops::cosh, Float::cosh, -709.0, 709.0, 1.0);
}

#[test]
fn tanh_ulp() {
    check_unary("tanh", ops::tanh, Float::tanh, -19.0, 19.0, 1.0);
}

#[test]
fn asinh_ulp() {
    check_unary(
        "asinh",
        ops::asinh,
        Float::asinh,
        -SQRT_DBL_MAX,
        SQRT_DBL_MAX,
        1.0,
    );
}

#[test]
fn acosh_ulp() {
    check_unary("acosh", ops::acosh, Float::acosh, 1.0, SQRT_DBL_MAX, 1.0);
}

#[test]
fn atanh_ulp() {
    check_unary("atanh", ops::atanh, Float::atanh, f64::MIN, f64::MAX, 1.0);
}

#[test]
fn cbrt_ulp() {
    check_unary("cbrt", ops::cbrt, Float::cbrt, f64::MIN, f64::MAX, 1.0);
}

#[test]
fn erf_ulp() {
    check_unary("erf", ops::erf, Float::erf, f64::MIN, f64::MAX, 0.75);
}

#[test]
fn erfc_ulp() {
    check_unary("erfc", ops::erfc, Float::erfc, f64::MIN, 26.2, 1.5);
    check_unary("erfc", ops::erfc, Float::erfc, 26.2, f64::MAX, 2.5);
}

#[test]
fn tgamma_ulp() {
    check_unary("tgamma", ops::tgamma, Float::gamma, f64::MIN, f64::MAX, 1.0);
}

#[test]
fn lgamma_ulp() {
    check_unary("lgamma", ops::lgamma, Float::ln_gamma, 0.0, 2e305, 1.0);
}

#[test]
fn sinpi_ulp() {
    let max = 1e9 / 4.;
    check_unary("sinpi", ops::sinpi, sinpi_oracle, -max, max, 0.506);
}

#[test]
fn cospi_ulp() {
    let max = 1e9 / 4.;
    check_unary("cospi", ops::cospi, cospi_oracle, -max, max, 0.506);
}

#[test]
fn sqrt_ulp() {
    check_unary("sqrt", ops::sqrt, Float::sqrt, 0.0, f64::MAX, 0.50001);
}

/// `sqrt` is the hardware instruction, so the slice path has to reproduce `f64::sqrt` bit for bit,
/// including the values `sqrt_ulp` never samples: `-0.0`, negatives, subnormals, the extremes and
/// the non-finite values.
#[test]
fn sqrt_bit_identical_to_scalar() {
    const SPECIALS: [f64; 14] = [
        -0.0,
        0.0,
        -1.0,
        f64::NEG_INFINITY,
        f64::INFINITY,
        f64::NAN,
        f64::from_bits(0x7ff8_0000_0000_0001),
        1.0,
        2.0,
        f64::EPSILON,
        f64::MIN_POSITIVE,
        f64::MIN_POSITIVE / 2.0,
        f64::from_bits(1),
        f64::MAX,
    ];
    for len in LENS {
        let src: Vec<f64> = (0..len).map(|i| SPECIALS[i % SPECIALS.len()]).collect();
        let mut out: Vec<MaybeUninit<f64>> = vec![MaybeUninit::uninit(); len];
        ops::sqrt(&src, &mut out).expect("length check");
        for (lane, (got, &x)) in read(out).iter().zip(src.iter()).enumerate() {
            let want = x.sqrt();
            assert!(
                got.to_bits() == want.to_bits() || (got.is_nan() && want.is_nan()),
                "sqrt: len {len}, lane {lane}, x={x:e}, got {}, want {want}",
                got.to_bits()
            );
        }
    }
}

// --------------------------------------------------------------- binary ----------

fn atan2_oracle(y: Float, x: &Float) -> Float {
    y.atan2(x)
}

fn pow_oracle(x: Float, y: &Float) -> Float {
    x.pow(y)
}

#[test]
fn atan2_ulp() {
    check_binary(
        "atan2",
        ops::atan2,
        atan2_oracle,
        f64::MIN,
        f64::MAX,
        f64::MIN,
        f64::MAX,
        1.0,
    );
}

#[test]
fn pow_ulp() {
    check_binary(
        "pow",
        ops::pow,
        pow_oracle,
        f64::MIN,
        f64::MAX,
        f64::MIN,
        f64::MAX,
        1.0,
    );
}

#[test]
fn hypot_ulp() {
    check_binary(
        "hypot",
        ops::hypot,
        |x: Float, y: &Float| x.hypot(y),
        f64::MIN,
        f64::MAX,
        f64::MIN,
        f64::MAX,
        0.5,
    );
}

// ----------------------------------------------------------------- pairs ----------

#[test]
fn sincos_ulp() {
    check_pair(
        "sincos",
        ops::sincos,
        |x: Float| {
            let p = x.prec();
            x.sin_cos(Float::new(p))
        },
        f64::MIN,
        f64::MAX,
        1.0,
    );
}

#[test]
fn sincospi_ulp() {
    let max = 1e9 / 4.;
    check_pair(
        "sincospi",
        ops::sincospi,
        |x: Float| {
            (Float::with_val(PI_PREC, &x) * Float::with_val(PI_PREC, rug::float::Constant::Pi))
                .sin_cos(Float::new(PI_PREC))
        },
        -max,
        max,
        0.506,
    );
}

// --------------------------------------------------------- interface checks -------

#[test]
fn trait_methods_dispatch() {
    let src = [0.25f64, 1.5, -2.0, 3.0];
    let mut out = vec![MaybeUninit::uninit(); src.len()];
    <f64 as ElementwiseMath>::exp(&src, &mut out).unwrap();
    assert!((read(out)[1] - 1.5f64.exp()).abs() < 1e-12);

    let mut out = vec![MaybeUninit::uninit(); src.len()];
    <f64 as ElementwiseMath>::pow(&src, &src, &mut out).unwrap();
    assert!((read(out)[3] - 27.0).abs() < 1e-12);

    let mut s = vec![MaybeUninit::uninit(); src.len()];
    let mut c = vec![MaybeUninit::uninit(); src.len()];
    <f64 as ElementwiseMath>::sincos(&src, &mut s, &mut c).unwrap();
    let (s, c) = (read(s), read(c));
    assert!((s[1] - 1.5f64.sin()).abs() < 1e-12);
    assert!((c[1] - 1.5f64.cos()).abs() < 1e-12);
}

#[test]
fn length_mismatch_is_reported() {
    let src = [1.0f64, 2.0];
    let mut out = vec![MaybeUninit::uninit(); 3];
    assert_eq!(
        ops::exp(&src, &mut out),
        Err(LengthMismatch { src: 2, dst: 3 })
    );
    assert_eq!(
        ops::pow(&src, &src[..1], &mut out[..2]),
        Err(LengthMismatch { src: 1, dst: 2 })
    );
}

/// Every length from 0 to `4 * lanes + 3` must be handled, so the vector body, the tail and the
/// empty case are all reached.
#[test]
fn all_lengths_are_covered() {
    for len in 0..=(4 * 8 + 3) {
        let src: Vec<f64> = (0..len).map(|i| i as f64 * 0.125 - 1.0).collect();
        let mut out: Vec<MaybeUninit<f64>> = vec![MaybeUninit::uninit(); len];
        ops::sin(&src, &mut out).unwrap();
        let got = read(out);
        for (i, &x) in src.iter().enumerate() {
            assert!((got[i] - x.sin()).abs() < 1e-12, "len {len}, lane {i}");
        }
    }
}

/// Special values must match the oracle exactly: NaN stays NaN, signed zero keeps its sign, and
/// overflow saturates the way the platform does.
#[test]
fn special_values() {
    let cases: [f64; 12] = [
        0.0,
        -0.0,
        1.0,
        -1.0,
        f64::INFINITY,
        f64::NEG_INFINITY,
        f64::NAN,
        f64::MIN_POSITIVE,
        -f64::MIN_POSITIVE,
        f64::from_bits(1),
        1.0e308,
        -1.0e308,
    ];

    let mut out = vec![MaybeUninit::uninit(); cases.len()];
    ops::exp(&cases, &mut out).unwrap();
    let got = read(out);
    for (i, &x) in cases.iter().enumerate() {
        let want = Float::with_val(PREC, x).exp();
        assert_close("exp special", 0, i, x, got[i], &want, 1.0);
    }

    let mut out = vec![MaybeUninit::uninit(); cases.len()];
    ops::log(&cases, &mut out).unwrap();
    let got = read(out);
    for (i, &x) in cases.iter().enumerate() {
        let want = Float::with_val(PREC, x).ln();
        if want.is_nan() {
            assert!(got[i].is_nan(), "log({x:e}) = {}", got[i]);
        } else {
            assert_close("log special", 0, i, x, got[i], &want, 3.5);
        }
    }

    // Signed zero must survive where the C library preserves it.
    let zeros = [-0.0f64, 0.0];
    let mut out = vec![MaybeUninit::uninit(); zeros.len()];
    ops::sin(&zeros, &mut out).unwrap();
    let got = read(out);
    assert!(got[0].is_sign_negative(), "sin(-0.0) lost its sign");
    assert!(got[1].is_sign_positive(), "sin(+0.0) lost its sign");

    let mut out = vec![MaybeUninit::uninit(); zeros.len()];
    ops::expm1(&zeros, &mut out).unwrap();
    let got = read(out);
    assert!(got[0].is_sign_negative(), "expm1(-0.0) lost its sign");
    assert!(got[1].is_sign_positive(), "expm1(+0.0) lost its sign");
}

// ------------------------------------------------------------ activations ----------

fn sigmoid_oracle(x: Float) -> Float {
    let one = Float::with_val(PREC, 1);
    one.clone() / (one + (-x).exp())
}

fn silu_oracle(x: Float) -> Float {
    x.clone() * sigmoid_oracle(x)
}

fn softplus_oracle(x: Float) -> Float {
    x.exp().ln_1p()
}

fn gelu_oracle(x: Float) -> Float {
    let half = Float::with_val(PREC, 0.5);
    let z = x.clone() / Float::with_val(PREC, 2).sqrt();
    half * x * (Float::with_val(PREC, 1) + z.erf())
}

fn gelu_tanh_oracle(x: Float) -> Float {
    let half = Float::with_val(PREC, 0.5);
    let scale = (Float::with_val(PREC, 2) / Float::with_val(PREC, rug::float::Constant::Pi)).sqrt();
    let cubic = Float::with_val(PREC, 0.044715) * x.clone() * x.clone() * x.clone();
    half * x.clone() * (Float::with_val(PREC, 1) + (scale * (x + cubic)).tanh())
}

#[test]
fn sigmoid_ulp() {
    check_unary("sigmoid", ops::sigmoid, sigmoid_oracle, -700.0, 700.0, 2.5);
}

#[test]
fn silu_ulp() {
    check_unary("silu", ops::silu, silu_oracle, -700.0, 700.0, 3.5);
}

#[test]
fn softplus_ulp() {
    check_unary(
        "softplus",
        ops::softplus,
        softplus_oracle,
        -700.0,
        700.0,
        3.0,
    );
}

/// Away from the `1 + tanh` cancellation (`x >= 0`) the bound is a few ULP.
#[test]
fn gelu_tanh_ulp() {
    check_unary(
        "gelu_tanh",
        ops::gelu_tanh,
        gelu_tanh_oracle,
        0.0,
        10.0,
        3.0,
    );
}

/// The `f64` `gelu` uses the 1.0 ULP `erf`; away from the cancellation the
/// bound is a few ULP.
#[test]
fn gelu_ulp() {
    check_unary("gelu", ops::gelu, gelu_oracle, 0.0, 10.0, 3.0);
}

/// The far negative tail stays subnormal instead of flushing to zero; the check
/// is in units of the smallest subnormal step.
#[test]
fn sigmoid_and_softplus_keep_their_subnormal_tail() {
    let src = [-740.0f64, -730.0, -720.0];
    for (name, op) in [
        ("sigmoid", ops::sigmoid as UnaryOp64),
        ("softplus", ops::softplus),
    ] {
        let mut out: Vec<MaybeUninit<f64>> = vec![MaybeUninit::uninit(); src.len()];
        op(&src, &mut out).expect("length check");
        for (got, &x) in read(out).iter().zip(src.iter()) {
            let want = Float::with_val(PREC, x).exp().to_f64();
            assert!(*got > 0.0, "{name}({x}) flushed to zero");
            let steps = (*got - want).abs() / f64::from_bits(1);
            assert!(
                steps <= 2.0,
                "{name}({x}): got {got}, want {want}, {steps} subnormal steps"
            );
        }
    }
}

type UnaryOp64 = fn(&[f64], &mut [MaybeUninit<f64>]) -> Result<(), LengthMismatch>;