wickra-simd 1.0.7

Runtime SIMD dispatch for the Wickra technical indicators core: runs a kernel with AVX2 and FMA, or AVX-512, enabled when the CPU has them, with identical results either way.
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
//! Runtime SIMD dispatch for the Wickra technical indicators core.
//!
//! Release binaries are built for the baseline of their target — on `x86_64`
//! that is SSE2, with no AVX and no fused multiply-add instruction — so they
//! run on every CPU of the architecture. A batch kernel that would profit from
//! AVX2 lanes or a hardware FMA therefore cannot simply be compiled for them.
//! [`dispatch`] closes that gap: it checks the CPU once (the standard library
//! caches the answer) and runs a [`Kernel`] inside a function compiled with
//! AVX2 and FMA enabled when both are present, and in the baseline build
//! otherwise. A kernel that opts in ([`Kernel::WIDE`]) runs with AVX-512F
//! enabled as well where the CPU has it, and does its element-wise work in
//! eight-lane [`Simd::W`] values: one 512-bit register there, two four-lane
//! vectors everywhere else.
//!
//! # Same result on every path
//!
//! Dispatch changes how a kernel is compiled, never what it computes. Rust
//! evaluates floating-point code exactly as written — it never reassociates,
//! and never contracts `a * b + c` into a fused multiply-add — so the AVX2
//! build and the baseline build of one kernel perform the same IEEE-754
//! operations in the same order. `f64::mul_add` is correctly rounded whether it
//! becomes the FMA instruction or the C library's `fma`, and an eight-lane
//! operation is the same IEEE-754 operation on each lane whether the lanes sit
//! in one register or two. Every path therefore returns bit-identical values;
//! the crate's tests check exactly that, at every level the machine has.
//!
//! The AVX-512 level needs Rust 1.89 or later, where its target feature is
//! stable; built by an older compiler the crate has no such level, and a kernel
//! that opts in runs at the AVX2 one -- the same bits, at the AVX2 speed.
//!
//! On `aarch64`, NEON and FMA are part of the baseline, so kernels already get
//! them and [`dispatch`] runs them directly.
//!
//! # Writing a kernel
//!
//! Implement [`Kernel`] and mark [`Kernel::run`] `#[inline(always)]`, as well
//! as any helper it calls: code is only compiled with the enabled features if
//! it is inlined into the dispatching function.

use std::sync::atomic::{AtomicU8, Ordering};

mod avx2;
// Compiled only when `build.rs` found Rust 1.89 or later, where the AVX-512
// intrinsics are stable; the workspace MSRV builds the crate without it.
#[clippy::msrv = "1.89"]
mod avx512;
mod portable;

#[cfg(target_arch = "x86_64")]
pub use avx2::Avx2;
#[cfg(all(target_arch = "x86_64", wickra_avx512))]
pub use avx512::Avx512;
pub use portable::Portable;

/// Four `f64` lanes and the operations the Wickra kernels are built from.
///
/// An implementation is a *token*: a zero-sized value whose existence proves
/// the instruction set it stands for is available, so its methods are safe to
/// call. [`Portable`] is available everywhere; [`Avx2`] is only ever created by
/// [`dispatch`] after the CPU was checked.
///
/// Every operation is exact per lane in the IEEE-754 sense — add, subtract,
/// multiply, divide, square root and fused multiply-add are correctly rounded,
/// `max`/`min` follow the x86 `MAXPD`/`MINPD` rule (`a > b ? a : b`, so the
/// second operand wins on a tie or a `NaN`) and `abs` clears the sign bit — so
/// one kernel written against this trait returns the same bits under every
/// implementation.
pub trait Simd: Copy {
    /// Four `f64` lanes.
    type V: Copy;

    /// All lanes `x`.
    fn splat(self, x: f64) -> Self::V;
    /// Lanes from an array.
    fn load(self, a: &[f64; 4]) -> Self::V;
    /// Lanes into an array.
    fn store(self, v: Self::V, a: &mut [f64; 4]);
    /// Lanes as an array.
    fn to_array(self, v: Self::V) -> [f64; 4];
    /// Lane-wise `a + b`.
    fn add(self, a: Self::V, b: Self::V) -> Self::V;
    /// Lane-wise `a - b`.
    fn sub(self, a: Self::V, b: Self::V) -> Self::V;
    /// Lane-wise `a * b`.
    fn mul(self, a: Self::V, b: Self::V) -> Self::V;
    /// Lane-wise `a / b`.
    fn div(self, a: Self::V, b: Self::V) -> Self::V;
    /// Lane-wise square root.
    fn sqrt(self, a: Self::V) -> Self::V;
    /// Lane-wise `a * b + c` with a single rounding.
    fn mul_add(self, a: Self::V, b: Self::V, c: Self::V) -> Self::V;
    /// Lane-wise `if a > b { a } else { b }`.
    fn max(self, a: Self::V, b: Self::V) -> Self::V;
    /// Lane-wise `if a < b { a } else { b }`.
    fn min(self, a: Self::V, b: Self::V) -> Self::V;
    /// Lane-wise absolute value (sign bit cleared).
    fn abs(self, a: Self::V) -> Self::V;
    /// Lane-wise `if test > 0 { yes } else { no }` (`NaN` takes `no`).
    fn select_positive(self, test: Self::V, yes: Self::V, no: Self::V) -> Self::V;
    /// `[0, v0, v1, v2]`: lanes moved up by one, `+0.0` shifted in.
    fn shift1(self, v: Self::V) -> Self::V;
    /// `[0, 0, v0, v1]`: lanes moved up by two, `+0.0` shifted in.
    fn shift2(self, v: Self::V) -> Self::V;
    /// All lanes the last lane `v3`.
    fn broadcast_last(self, v: Self::V) -> Self::V;
    /// The last lane `v3` as a scalar.
    fn last_lane(self, v: Self::V) -> f64;
    /// The 4×4 transpose of the rows `a`, `b`, `c`, `d`: result `j` is
    /// `[a_j, b_j, c_j, d_j]`. Pure data movement, so no value changes.
    fn transpose4(self, a: Self::V, b: Self::V, c: Self::V, d: Self::V) -> [Self::V; 4];

    /// Eight `f64` lanes for element-wise work: one 512-bit register where the
    /// CPU has AVX-512 and the kernel opts in ([`Kernel::WIDE`]), two
    /// four-lane vectors otherwise. Every operation on them is exact per lane,
    /// so the width never changes a result.
    type W: Copy;

    /// Eight lanes from an array.
    fn load8(self, a: &[f64; 8]) -> Self::W;
    /// Eight lanes into an array.
    fn store8(self, v: Self::W, a: &mut [f64; 8]);
    /// All eight lanes `x`.
    fn splat8(self, x: f64) -> Self::W;
    /// Lane-wise `a + b` over eight lanes.
    fn add8(self, a: Self::W, b: Self::W) -> Self::W;
    /// Lane-wise `a - b` over eight lanes.
    fn sub8(self, a: Self::W, b: Self::W) -> Self::W;
    /// Lane-wise `a * b` over eight lanes.
    fn mul8(self, a: Self::W, b: Self::W) -> Self::W;
    /// Lane-wise `a / b` over eight lanes.
    fn div8(self, a: Self::W, b: Self::W) -> Self::W;
    /// Lane-wise square root over eight lanes.
    fn sqrt8(self, a: Self::W) -> Self::W;
    /// Lane-wise `if a > b { a } else { b }` over eight lanes.
    fn max8(self, a: Self::W, b: Self::W) -> Self::W;
    /// Lane-wise `if test > 0 { yes } else { no }` over eight lanes (`NaN`
    /// takes `no`).
    fn select_positive8(self, test: Self::W, yes: Self::W, no: Self::W) -> Self::W;
}

/// A unit of work [`dispatch`] can run with the best instruction set available.
///
/// `run` receives a [`Simd`] token: vector kernels compute through it, scalar
/// kernels ignore it and profit from the enabled instruction set through their
/// plain arithmetic (a `mul_add` becomes the FMA instruction). Implementors mark
/// [`run`](Kernel::run) `#[inline(always)]` so the body is compiled into the
/// feature-enabled function rather than called out of it.
pub trait Kernel {
    /// What the kernel returns.
    type Output;

    /// Whether the kernel runs at the AVX-512 level where the CPU has it. A
    /// kernel opts in when it does its element-wise work in eight lanes
    /// ([`Simd::W`]) or its plain loops gain from the compiler widening them;
    /// any other kernel runs at the AVX2 level on such a CPU, as code the
    /// compiler vectorizes for AVX-512 is not always faster.
    const WIDE: bool = false;

    /// Execute the kernel with the lanes `simd` provides.
    fn run<S: Simd>(self, simd: S) -> Self::Output;
}

/// The instruction set [`dispatch`] selects on this machine.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Level {
    /// Baseline instructions of the build target.
    Baseline,
    /// `x86_64` with AVX2 and FMA.
    Avx2Fma,
    /// `x86_64` with AVX2, FMA and AVX-512F: kernels that opt in
    /// ([`Kernel::WIDE`]) get their eight-lane work in one register. Detected
    /// only in a build by a Rust that supports AVX-512 (1.89 and later).
    Avx512,
    /// `aarch64`, whose baseline includes NEON and FMA.
    Neon,
}

impl Level {
    /// Stable lowercase name, for diagnostics and benchmark labels.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Baseline => "baseline",
            Self::Avx2Fma => "avx2+fma",
            Self::Avx512 => "avx512",
            Self::Neon => "neon",
        }
    }
}

/// Cached detection result: 0 = not yet detected, 1 = baseline, 2 = AVX2+FMA,
/// 3 = AVX-512.
static DETECTED: AtomicU8 = AtomicU8::new(0);

/// The instruction set [`dispatch`] runs kernels with on this machine.
pub fn level() -> Level {
    if cfg!(target_arch = "aarch64") {
        return Level::Neon;
    }
    match DETECTED.load(Ordering::Relaxed) {
        1 => Level::Baseline,
        2 => Level::Avx2Fma,
        3 => Level::Avx512,
        _ => {
            let level = detect();
            let code = match level {
                Level::Avx512 => 3,
                Level::Avx2Fma => 2,
                Level::Baseline | Level::Neon => 1,
            };
            DETECTED.store(code, Ordering::Relaxed);
            level
        }
    }
}

#[cfg(target_arch = "x86_64")]
fn detect() -> Level {
    if std::arch::is_x86_feature_detected!("avx2") && std::arch::is_x86_feature_detected!("fma") {
        if avx512() {
            Level::Avx512
        } else {
            Level::Avx2Fma
        }
    } else {
        Level::Baseline
    }
}

/// Whether the CPU has AVX-512F, in a build that can use it.
#[cfg(all(target_arch = "x86_64", wickra_avx512))]
fn avx512() -> bool {
    std::arch::is_x86_feature_detected!("avx512f")
}

#[cfg(all(target_arch = "x86_64", not(wickra_avx512)))]
fn avx512() -> bool {
    false
}

#[cfg(not(target_arch = "x86_64"))]
fn detect() -> Level {
    Level::Baseline
}

/// Run `kernel` with the best instruction set this CPU offers.
///
/// Returns bit-for-bit what [`run_baseline`] returns for the same kernel.
#[inline]
pub fn dispatch<K: Kernel>(kernel: K) -> K::Output {
    run_level(level(), kernel)
}

/// `kernel` at `level`, which the caller has checked this CPU supports.
#[inline]
fn run_level<K: Kernel>(level: Level, kernel: K) -> K::Output {
    match level {
        #[cfg(all(target_arch = "x86_64", wickra_avx512))]
        Level::Avx512 if K::WIDE => avx512::run(kernel),
        #[cfg(target_arch = "x86_64")]
        Level::Avx2Fma | Level::Avx512 => avx2::run(kernel),
        _ => kernel.run(Portable),
    }
}

/// Run `kernel` at `level` if this CPU supports it, `None` otherwise -- for
/// tests that prove a kernel returns the same bits at every level the machine
/// has, not only the one [`dispatch`] picks.
#[doc(hidden)]
pub fn run_at<K: Kernel>(level: Level, kernel: K) -> Option<K::Output> {
    let best = self::level();
    let available = match level {
        Level::Baseline => true,
        Level::Avx2Fma => matches!(best, Level::Avx2Fma | Level::Avx512),
        Level::Avx512 | Level::Neon => best == level,
    };
    available.then(|| run_level(level, kernel))
}

/// Run `kernel` in the baseline build with the [`Portable`] lanes, never
/// dispatching. Exists so tests (in this crate and in its users) can prove a
/// kernel returns the same bits on every path.
#[inline(never)]
pub fn run_baseline<K: Kernel>(kernel: K) -> K::Output {
    kernel.run(Portable)
}

#[cfg(test)]
// Kernels must inline into the dispatching function to be compiled with its
// features; `#[inline(always)]` on `run` is the documented contract.
#[allow(clippy::inline_always)]
mod tests {
    use super::*;

    /// Three interleaved EMA-style recurrences with `mul_add` plus a plain
    /// multiply-add the compiler must not fuse: the shape of the scalar kernels.
    struct Recurrences<'a> {
        xs: &'a [f64],
    }

    impl Kernel for Recurrences<'_> {
        type Output = Vec<f64>;

        #[inline(always)]
        fn run<S: Simd>(self, _simd: S) -> Vec<f64> {
            let (mut a, mut b, mut c) = (1.0_f64, 2.0_f64, 3.0_f64);
            let mut out = Vec::with_capacity(self.xs.len() * 3);
            for &x in self.xs {
                a = 0.1_f64.mul_add(x, 0.9 * a);
                b = 0.3_f64.mul_add(x, 0.7 * b);
                c = c * 0.95 + x * 0.05;
                out.extend_from_slice(&[a, b, c - a]);
            }
            out
        }
    }

    /// Every lane operation over one batch of inputs, the results concatenated.
    struct AllOps<'a> {
        a: &'a [f64],
        b: &'a [f64],
    }

    impl Kernel for AllOps<'_> {
        type Output = Vec<f64>;
        const WIDE: bool = true;

        #[inline(always)]
        fn run<S: Simd>(self, s: S) -> Vec<f64> {
            let mut out = Vec::new();
            for (ca, cb) in self.a.chunks_exact(4).zip(self.b.chunks_exact(4)) {
                let x = s.load(ca.try_into().unwrap());
                let y = s.load(cb.try_into().unwrap());
                let z = s.splat(ca[0]);
                let mut stored = [0.0; 4];
                s.store(s.add(x, y), &mut stored);
                out.extend_from_slice(&stored);
                for v in [
                    s.sub(x, y),
                    s.mul(x, y),
                    s.div(x, y),
                    s.sqrt(s.abs(x)),
                    s.mul_add(x, y, z),
                    s.max(x, y),
                    s.min(x, y),
                    s.abs(x),
                    s.select_positive(s.sub(x, y), x, y),
                    s.shift1(x),
                    s.shift2(x),
                    s.broadcast_last(x),
                    s.splat(s.last_lane(y)),
                    z,
                ] {
                    out.extend_from_slice(&s.to_array(v));
                }
                for v in s.transpose4(x, y, z, s.sub(x, y)) {
                    out.extend_from_slice(&s.to_array(v));
                }
            }
            for (ca, cb) in self.a.chunks_exact(8).zip(self.b.chunks_exact(8)) {
                let x = s.load8(ca.try_into().unwrap());
                let y = s.load8(cb.try_into().unwrap());
                let z = s.splat8(ca[0]);
                for v in [
                    s.add8(x, y),
                    s.sub8(x, y),
                    s.mul8(x, y),
                    s.div8(x, y),
                    s.sqrt8(s.max8(x, z)),
                    s.max8(x, y),
                    s.select_positive8(s.sub8(x, y), x, y),
                    z,
                ] {
                    let mut stored = [0.0; 8];
                    s.store8(v, &mut stored);
                    out.extend_from_slice(&stored);
                }
            }
            out
        }
    }

    fn bits(v: &[f64]) -> Vec<u64> {
        v.iter().map(|x| x.to_bits()).collect()
    }

    fn series() -> Vec<f64> {
        (0..4096)
            .map(|i| (f64::from(i) * 0.731).sin() * 1e3 + f64::from(i % 17))
            .collect()
    }

    #[test]
    fn dispatch_matches_the_baseline_bit_for_bit() {
        let xs = series();
        assert_eq!(
            bits(&dispatch(Recurrences { xs: &xs })),
            bits(&run_baseline(Recurrences { xs: &xs }))
        );
    }

    /// Each lane operation must give the same bits on every implementation,
    /// the awkward values included: signed zeros, infinities, `NaN` (where
    /// `max`/`min` must take the second operand), subnormals and a
    /// cancellation-heavy fused multiply-add.
    #[test]
    fn every_lane_operation_matches_the_portable_lanes() {
        let edge = [
            0.0,
            -0.0,
            f64::INFINITY,
            f64::NEG_INFINITY,
            f64::NAN,
            f64::MIN_POSITIVE / 8.0,
            1.0 + f64::EPSILON,
            -1.0,
        ];
        let mut a: Vec<f64> = series();
        let mut b: Vec<f64> = series().iter().rev().map(|x| x * 0.37 - 2.0).collect();
        for (i, &x) in edge.iter().enumerate() {
            for (j, &y) in edge.iter().enumerate() {
                a.extend_from_slice(&[x, y, 1.0 + f64::EPSILON, x]);
                b.extend_from_slice(&[
                    y,
                    x,
                    1.0 - f64::EPSILON,
                    f64::from(u8::try_from(i * 8 + j).unwrap()),
                ]);
            }
        }
        let fast = dispatch(AllOps { a: &a, b: &b });
        let base = run_baseline(AllOps { a: &a, b: &b });
        assert_eq!(fast.len(), base.len());
        for (k, (x, y)) in fast.iter().zip(&base).enumerate() {
            assert!(
                x.to_bits() == y.to_bits() || (x.is_nan() && y.is_nan()),
                "lane {k}: {x:e} vs {y:e}"
            );
        }
    }

    #[test]
    fn portable_lanes_follow_the_documented_rules() {
        let s = Portable;
        let x = [1.0, f64::NAN, -0.0, 3.0];
        let y = [2.0, 5.0, 0.0, f64::NAN];
        assert_eq!(bits(&s.max(x, y)), bits(&[2.0, 5.0, 0.0, f64::NAN]));
        assert_eq!(bits(&s.min(x, y)), bits(&[1.0, 5.0, 0.0, f64::NAN]));
        assert_eq!(s.shift1([1.0, 2.0, 3.0, 4.0]), [0.0, 1.0, 2.0, 3.0]);
        assert_eq!(s.shift2([1.0, 2.0, 3.0, 4.0]), [0.0, 0.0, 1.0, 2.0]);
        assert_eq!(s.broadcast_last([1.0, 2.0, 3.0, 4.0]), [4.0; 4]);
        assert_eq!(
            bits(&s.abs([-0.0, -2.0, 2.0, -f64::INFINITY])),
            bits(&[0.0, 2.0, 2.0, f64::INFINITY])
        );
        assert_eq!(
            s.transpose4(
                [1.0, 2.0, 3.0, 4.0],
                [5.0, 6.0, 7.0, 8.0],
                [9.0, 10.0, 11.0, 12.0],
                [13.0, 14.0, 15.0, 16.0]
            ),
            [
                [1.0, 5.0, 9.0, 13.0],
                [2.0, 6.0, 10.0, 14.0],
                [3.0, 7.0, 11.0, 15.0],
                [4.0, 8.0, 12.0, 16.0]
            ]
        );
    }

    #[test]
    fn level_is_stable_and_named() {
        let first = level();
        assert_eq!(level(), first);
        assert!(["baseline", "avx2+fma", "avx512", "neon"].contains(&first.name()));
        assert_eq!(Level::Baseline.name(), "baseline");
        assert_eq!(Level::Avx2Fma.name(), "avx2+fma");
        assert_eq!(Level::Avx512.name(), "avx512");
        assert_eq!(Level::Neon.name(), "neon");
    }

    #[cfg(target_arch = "x86_64")]
    #[test]
    fn detection_agrees_with_the_standard_library() {
        let both = std::arch::is_x86_feature_detected!("avx2")
            && std::arch::is_x86_feature_detected!("fma");
        assert_eq!(matches!(level(), Level::Avx2Fma | Level::Avx512), both);
        let wide = cfg!(wickra_avx512) && both && avx512();
        assert_eq!(level() == Level::Avx512, wide);
    }

    /// Every level the machine has, and only those, runs a kernel -- with the
    /// bits of the baseline build.
    #[test]
    fn every_available_level_matches_the_baseline() {
        let a: Vec<f64> = series();
        let b: Vec<f64> = series().iter().map(|x| x * 0.5 + 1.0).collect();
        let base = run_baseline(AllOps { a: &a, b: &b });
        let best = level();
        for at in [Level::Baseline, Level::Avx2Fma, Level::Avx512, Level::Neon] {
            let ran = run_at(at, AllOps { a: &a, b: &b });
            let expected = match at {
                Level::Baseline => true,
                Level::Avx2Fma => matches!(best, Level::Avx2Fma | Level::Avx512),
                Level::Avx512 | Level::Neon => best == at,
            };
            assert_eq!(ran.is_some(), expected, "{}", at.name());
            if let Some(out) = ran {
                assert!(out
                    .iter()
                    .zip(&base)
                    .all(|(x, y)| x.to_bits() == y.to_bits() || (x.is_nan() && y.is_nan())));
            }
        }
    }
}