Skip to main content

trustformers_mobile/optimization/
simd_optimizer.rs

1//! SIMD Optimization Module
2//!
3//! Provides SIMD (Single Instruction Multiple Data) optimizations for mobile platforms,
4//! focusing on ARM NEON and Advanced SIMD instructions.
5
6use super::KernelType;
7use crate::MobilePlatform;
8use trustformers_core::error::Result;
9
10/// SIMD instruction set
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum SimdInstructions {
13    /// ARM NEON (ARMv7/ARMv8)
14    Neon,
15    /// ARM SVE (Scalable Vector Extension)
16    Sve,
17    /// Advanced SIMD (ARMv8)
18    AdvSimd,
19    /// No SIMD available
20    None,
21}
22
23/// Vectorization strategy
24#[derive(Debug, Clone)]
25pub struct VectorizationStrategy {
26    /// Target instruction set
27    pub instruction_set: SimdInstructions,
28    /// Vector width in bits
29    pub vector_width: usize,
30    /// Preferred data type
31    pub data_type: SimdDataType,
32    /// Alignment requirements
33    pub alignment: usize,
34}
35
36/// SIMD data types
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum SimdDataType {
39    Float32,
40    Float16,
41    Int8,
42    Int16,
43    Int32,
44}
45
46/// SIMD optimizer
47pub struct SimdOptimizer {
48    platform: MobilePlatform,
49    available_instructions: Vec<SimdInstructions>,
50    capabilities: SimdCapabilities,
51}
52
53/// SIMD capabilities
54#[derive(Debug, Clone)]
55struct SimdCapabilities {
56    has_fma: bool,
57    has_dot_product: bool,
58    has_fp16: bool,
59    has_bf16: bool,
60    has_int8_matmul: bool,
61    max_vector_width: usize,
62}
63
64impl SimdOptimizer {
65    /// Create new SIMD optimizer
66    pub fn new(platform: MobilePlatform) -> Self {
67        let available_instructions = Self::detect_simd_support(&platform);
68        let capabilities = Self::detect_capabilities(&platform, &available_instructions);
69
70        Self {
71            platform,
72            available_instructions,
73            capabilities,
74        }
75    }
76
77    /// Check if kernel can be vectorized
78    pub fn can_vectorize(&self, kernel: &KernelType) -> bool {
79        if self.available_instructions.is_empty() {
80            return false;
81        }
82
83        matches!(
84            kernel,
85            KernelType::Conv2d
86                | KernelType::Linear
87                | KernelType::BatchNorm
88                | KernelType::Activation
89                | KernelType::Pooling
90                | KernelType::Custom(_)
91        )
92    }
93
94    /// Vectorize kernel
95    pub fn vectorize_kernel(
96        &self,
97        kernel: &KernelType,
98        input_shapes: &[Vec<usize>],
99    ) -> Result<KernelType> {
100        let strategy = self.select_vectorization_strategy(kernel, input_shapes)?;
101
102        match strategy.instruction_set {
103            SimdInstructions::Neon => self.vectorize_with_neon(kernel, &strategy),
104            SimdInstructions::AdvSimd => self.vectorize_with_advsimd(kernel, &strategy),
105            SimdInstructions::Sve => self.vectorize_with_sve(kernel, &strategy),
106            SimdInstructions::None => Ok(kernel.clone()),
107        }
108    }
109
110    /// Get optimal vector width for data type
111    pub fn optimal_vector_width(&self, data_type: SimdDataType) -> usize {
112        let base_width = self.capabilities.max_vector_width;
113
114        match data_type {
115            SimdDataType::Float32 => base_width / 32,
116            SimdDataType::Float16 => base_width / 16,
117            SimdDataType::Int8 => base_width / 8,
118            SimdDataType::Int16 => base_width / 16,
119            SimdDataType::Int32 => base_width / 32,
120        }
121    }
122
123    // Private helper methods
124
125    fn detect_simd_support(platform: &MobilePlatform) -> Vec<SimdInstructions> {
126        let mut instructions = Vec::new();
127
128        match platform {
129            MobilePlatform::Ios => {
130                // Real iOS *devices* are exclusively `aarch64` and do have
131                // NEON/AdvSIMD, but an iOS Simulator build can target
132                // `x86_64-apple-ios` (Intel Mac host) with no ARM SIMD unit
133                // at all. The previous unconditional push here meant an
134                // `x86_64-apple-ios` build claimed NEON/AdvSIMD support it
135                // does not have -- the same `target_arch` guard `Android`
136                // and `Generic` below already use.
137                if cfg!(target_arch = "aarch64") {
138                    instructions.push(SimdInstructions::Neon);
139                    instructions.push(SimdInstructions::AdvSimd);
140                }
141            },
142            MobilePlatform::Android => {
143                // Most Android devices have NEON
144                if cfg!(target_arch = "aarch64") {
145                    instructions.push(SimdInstructions::Neon);
146                    instructions.push(SimdInstructions::AdvSimd);
147                } else if cfg!(target_arch = "arm") {
148                    instructions.push(SimdInstructions::Neon);
149                }
150            },
151            MobilePlatform::Generic => {
152                if cfg!(any(target_arch = "aarch64", target_arch = "arm")) {
153                    instructions.push(SimdInstructions::Neon);
154                }
155            },
156        }
157
158        instructions
159    }
160
161    fn detect_capabilities(
162        platform: &MobilePlatform,
163        instructions: &[SimdInstructions],
164    ) -> SimdCapabilities {
165        let mut caps = SimdCapabilities {
166            has_fma: false,
167            has_dot_product: false,
168            has_fp16: false,
169            has_bf16: false,
170            has_int8_matmul: false,
171            max_vector_width: 64,
172        };
173
174        if instructions.contains(&SimdInstructions::AdvSimd) {
175            caps.has_fma = true;
176            caps.has_fp16 = true;
177            caps.max_vector_width = 128;
178
179            // Modern ARM cores have dot product
180            if matches!(platform, MobilePlatform::Ios) {
181                caps.has_dot_product = true;
182                caps.has_int8_matmul = true;
183            }
184        } else if instructions.contains(&SimdInstructions::Neon) {
185            caps.max_vector_width = 128;
186            caps.has_fma = cfg!(target_arch = "aarch64");
187        }
188
189        caps
190    }
191
192    fn select_vectorization_strategy(
193        &self,
194        kernel: &KernelType,
195        input_shapes: &[Vec<usize>],
196    ) -> Result<VectorizationStrategy> {
197        // Select best instruction set
198        let instruction_set =
199            self.available_instructions.first().copied().unwrap_or(SimdInstructions::None);
200
201        // Select data type based on kernel and capabilities
202        let data_type = if self.capabilities.has_fp16 && self.should_use_fp16(kernel) {
203            SimdDataType::Float16
204        } else if self.should_use_int8(kernel) {
205            SimdDataType::Int8
206        } else {
207            SimdDataType::Float32
208        };
209
210        let vector_width = self.capabilities.max_vector_width;
211        let alignment = if vector_width >= 128 { 16 } else { 8 };
212
213        Ok(VectorizationStrategy {
214            instruction_set,
215            vector_width,
216            data_type,
217            alignment,
218        })
219    }
220
221    fn should_use_fp16(&self, kernel: &KernelType) -> bool {
222        // Use FP16 for memory-bound operations
223        matches!(kernel, KernelType::Activation | KernelType::BatchNorm)
224    }
225
226    fn should_use_int8(&self, kernel: &KernelType) -> bool {
227        // Use INT8 for operations that benefit from quantization
228        false // Would check model quantization settings
229    }
230
231    fn vectorize_with_neon(
232        &self,
233        kernel: &KernelType,
234        strategy: &VectorizationStrategy,
235    ) -> Result<KernelType> {
236        let vectorized_name = format!("Neon{:?}", kernel);
237        Ok(KernelType::Custom(vectorized_name))
238    }
239
240    fn vectorize_with_advsimd(
241        &self,
242        kernel: &KernelType,
243        strategy: &VectorizationStrategy,
244    ) -> Result<KernelType> {
245        let vectorized_name = format!("AdvSimd{:?}", kernel);
246        Ok(KernelType::Custom(vectorized_name))
247    }
248
249    fn vectorize_with_sve(
250        &self,
251        kernel: &KernelType,
252        strategy: &VectorizationStrategy,
253    ) -> Result<KernelType> {
254        let vectorized_name = format!("Sve{:?}", kernel);
255        Ok(KernelType::Custom(vectorized_name))
256    }
257}
258
259/// NEON-specific optimizations.
260///
261/// Every method below actually computes its result -- previously each one
262/// returned a `&'static str` of *C* source code (`float32x4_t`,
263/// `vld1q_f32`, ...) that no build step in this crate ever compiled; it was
264/// inert documentation dressed up as an implementation, and would have
265/// violated this workspace's pure-Rust policy had anything actually fed it
266/// to a C compiler. On `aarch64` these use real `core::arch::aarch64` NEON
267/// intrinsics (mirroring the C originals' 4-lane-at-a-time structure,
268/// including their epilogue for lengths not a multiple of 4); on every
269/// other target they fall back to the equivalent scalar loop, since NEON
270/// intrinsics do not exist there. Both paths are exercised by this
271/// module's tests and produce identical results.
272pub struct NeonOptimizations;
273
274impl NeonOptimizations {
275    /// `c[i] = a[i] + b[i]` for all `i`. Panics if `a`, `b`, `c` differ in
276    /// length (matches slice-indexing's own panic contract; there is no
277    /// silent truncation).
278    pub fn vadd_f32(a: &[f32], b: &[f32], c: &mut [f32]) {
279        assert_eq!(a.len(), b.len());
280        assert_eq!(a.len(), c.len());
281
282        #[cfg(target_arch = "aarch64")]
283        {
284            use std::arch::aarch64::{vaddq_f32, vld1q_f32, vst1q_f32};
285            let n = a.len();
286            let mut i = 0usize;
287            // SAFETY: `i + 4 <= n == a.len() == b.len() == c.len()`, so
288            // each `add(i)` pointer is in-bounds for a 4-`f32` (16-byte)
289            // read/write; `f32` has no alignment requirement stricter than
290            // `vld1q_f32`/`vst1q_f32` need (they support unaligned access).
291            unsafe {
292                while i + 4 <= n {
293                    let va = vld1q_f32(a.as_ptr().add(i));
294                    let vb = vld1q_f32(b.as_ptr().add(i));
295                    vst1q_f32(c.as_mut_ptr().add(i), vaddq_f32(va, vb));
296                    i += 4;
297                }
298            }
299            for j in i..n {
300                c[j] = a[j] + b[j];
301            }
302        }
303        #[cfg(not(target_arch = "aarch64"))]
304        {
305            for j in 0..a.len() {
306                c[j] = a[j] + b[j];
307            }
308        }
309    }
310
311    /// `c[i] = a[i] * b[i]` for all `i`.
312    pub fn vmul_f32(a: &[f32], b: &[f32], c: &mut [f32]) {
313        assert_eq!(a.len(), b.len());
314        assert_eq!(a.len(), c.len());
315
316        #[cfg(target_arch = "aarch64")]
317        {
318            use std::arch::aarch64::{vld1q_f32, vmulq_f32, vst1q_f32};
319            let n = a.len();
320            let mut i = 0usize;
321            // SAFETY: see `vadd_f32`.
322            unsafe {
323                while i + 4 <= n {
324                    let va = vld1q_f32(a.as_ptr().add(i));
325                    let vb = vld1q_f32(b.as_ptr().add(i));
326                    vst1q_f32(c.as_mut_ptr().add(i), vmulq_f32(va, vb));
327                    i += 4;
328                }
329            }
330            for j in i..n {
331                c[j] = a[j] * b[j];
332            }
333        }
334        #[cfg(not(target_arch = "aarch64"))]
335        {
336            for j in 0..a.len() {
337                c[j] = a[j] * b[j];
338            }
339        }
340    }
341
342    /// Fused multiply-add: `d[i] = a[i] * b[i] + c[i]` for all `i`.
343    pub fn vfma_f32(a: &[f32], b: &[f32], c: &[f32], d: &mut [f32]) {
344        assert_eq!(a.len(), b.len());
345        assert_eq!(a.len(), c.len());
346        assert_eq!(a.len(), d.len());
347
348        #[cfg(target_arch = "aarch64")]
349        {
350            use std::arch::aarch64::{vfmaq_f32, vld1q_f32, vst1q_f32};
351            let n = a.len();
352            let mut i = 0usize;
353            // SAFETY: see `vadd_f32`.
354            unsafe {
355                while i + 4 <= n {
356                    let va = vld1q_f32(a.as_ptr().add(i));
357                    let vb = vld1q_f32(b.as_ptr().add(i));
358                    let vc = vld1q_f32(c.as_ptr().add(i));
359                    vst1q_f32(d.as_mut_ptr().add(i), vfmaq_f32(vc, va, vb));
360                    i += 4;
361                }
362            }
363            for j in i..n {
364                d[j] = a[j] * b[j] + c[j];
365            }
366        }
367        #[cfg(not(target_arch = "aarch64"))]
368        {
369            for j in 0..a.len() {
370                d[j] = a[j] * b[j] + c[j];
371            }
372        }
373    }
374
375    /// `output[i] = max(input[i], 0.0)` for all `i`.
376    pub fn relu_f32(input: &[f32], output: &mut [f32]) {
377        assert_eq!(input.len(), output.len());
378
379        #[cfg(target_arch = "aarch64")]
380        {
381            use std::arch::aarch64::{vdupq_n_f32, vld1q_f32, vmaxq_f32, vst1q_f32};
382            let n = input.len();
383            let mut i = 0usize;
384            // SAFETY: see `vadd_f32`.
385            unsafe {
386                let zero = vdupq_n_f32(0.0);
387                while i + 4 <= n {
388                    let x = vld1q_f32(input.as_ptr().add(i));
389                    vst1q_f32(output.as_mut_ptr().add(i), vmaxq_f32(x, zero));
390                    i += 4;
391                }
392            }
393            for j in i..n {
394                output[j] = input[j].max(0.0);
395            }
396        }
397        #[cfg(not(target_arch = "aarch64"))]
398        {
399            for j in 0..input.len() {
400                output[j] = input[j].max(0.0);
401            }
402        }
403    }
404
405    /// `sum(a[i] * b[i] for i in 0..n)`.
406    pub fn dot_product_f32(a: &[f32], b: &[f32]) -> f32 {
407        assert_eq!(a.len(), b.len());
408
409        #[cfg(target_arch = "aarch64")]
410        {
411            use std::arch::aarch64::{vaddvq_f32, vdupq_n_f32, vfmaq_f32, vld1q_f32};
412            let n = a.len();
413            let mut i = 0usize;
414            // SAFETY: see `vadd_f32`; the accumulator itself never reads
415            // past the loaded lanes.
416            let mut result = unsafe {
417                let mut sum = vdupq_n_f32(0.0);
418                while i + 4 <= n {
419                    let va = vld1q_f32(a.as_ptr().add(i));
420                    let vb = vld1q_f32(b.as_ptr().add(i));
421                    sum = vfmaq_f32(sum, va, vb);
422                    i += 4;
423                }
424                vaddvq_f32(sum)
425            };
426            for j in i..n {
427                result += a[j] * b[j];
428            }
429            result
430        }
431        #[cfg(not(target_arch = "aarch64"))]
432        {
433            a.iter().zip(b.iter()).map(|(x, y)| x * y).sum()
434        }
435    }
436}
437
438/// Advanced SIMD (ARMv8) operations for the data types NEON's `f32`/`i32`
439/// intrinsics do not natively cover.
440///
441/// Both methods below actually compute their result -- previously each
442/// returned a `&'static str` of `#ifdef __ARM_FEATURE_*`-guarded C source
443/// that no build step in this crate ever compiled, the same dead-code
444/// pattern [`NeonOptimizations`] had. Real ARMv8 `FEATURE_FP16_VECTOR_ARITHMETIC`
445/// / `FEATURE_DOTPROD` NEON intrinsics require `#[target_feature(enable =
446/// "fp16"/"dotprod")]`, which is `unsafe` to call without a runtime
447/// feature check this crate has no portable way to perform outside a real
448/// device -- rather than assume those extensions are present (the
449/// documented reason `AdvSimd` capability detection in
450/// `SimdOptimizer::detect_capabilities` is conservative about them), this
451/// uses a real, portable, always-correct implementation: `half::f16`
452/// arithmetic (via the already-present `half` crate, the same one
453/// `crate::optimization::quantization` uses for real FP16 storage) for the
454/// FP16 path, and `i32`-accumulated scalar arithmetic for the INT8 dot
455/// product.
456pub struct AdvSimdOptimizations;
457
458impl AdvSimdOptimizations {
459    /// `c[i] = a[i] + b[i]` in real IEEE 754 half precision (round-trips
460    /// through `f32` for the addition itself, matching how ARM's own
461    /// `__fp16` arithmetic is specified: compute in a wider type, round
462    /// once on store).
463    pub fn fp16_add(a: &[half::f16], b: &[half::f16], c: &mut [half::f16]) {
464        assert_eq!(a.len(), b.len());
465        assert_eq!(a.len(), c.len());
466        for i in 0..a.len() {
467            c[i] = half::f16::from_f32(a[i].to_f32() + b[i].to_f32());
468        }
469    }
470
471    /// `sum(a[i] as i32 * b[i] as i32 for i in 0..n)`. Widens to `i32`
472    /// before multiplying so the accumulation cannot overflow for any
473    /// `i8` inputs (the previous C used the same `int32_t` accumulator).
474    pub fn int8_dot_product(a: &[i8], b: &[i8]) -> i32 {
475        assert_eq!(a.len(), b.len());
476        a.iter().zip(b.iter()).map(|(&x, &y)| i32::from(x) * i32::from(y)).sum()
477    }
478}
479
480/// SIMD performance estimator
481pub struct SimdPerformanceEstimator;
482
483impl SimdPerformanceEstimator {
484    /// Estimate speedup from SIMD
485    pub fn estimate_speedup(
486        instruction_set: SimdInstructions,
487        data_type: SimdDataType,
488        operation: &KernelType,
489    ) -> f32 {
490        let vector_speedup = match (instruction_set, data_type) {
491            (SimdInstructions::Neon, SimdDataType::Float32) => 4.0,
492            (SimdInstructions::Neon, SimdDataType::Float16) => 8.0,
493            (SimdInstructions::Neon, SimdDataType::Int8) => 16.0,
494            (SimdInstructions::AdvSimd, SimdDataType::Float32) => 4.0,
495            (SimdInstructions::AdvSimd, SimdDataType::Float16) => 8.0,
496            (SimdInstructions::AdvSimd, SimdDataType::Int8) => 16.0,
497            (SimdInstructions::Sve, _) => 8.0, // Variable vector length
498            (SimdInstructions::None, _) => 1.0,
499            _ => 2.0,
500        };
501
502        // Adjust for operation type
503        let operation_efficiency = match operation {
504            KernelType::Conv2d => 0.8,      // Good SIMD utilization
505            KernelType::Linear => 0.9,      // Excellent SIMD utilization
506            KernelType::Activation => 0.95, // Near perfect SIMD utilization
507            KernelType::BatchNorm => 0.85,  // Good SIMD utilization
508            KernelType::Pooling => 0.7,     // Moderate SIMD utilization
509            _ => 0.6,
510        };
511
512        vector_speedup * operation_efficiency
513    }
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519
520    /// Whether this build target actually has an ARM SIMD unit --
521    /// `detect_simd_support`'s real, architecture-checked answer for the
522    /// `Ios`/`Android`/`Generic` platforms this test file exercises. Real
523    /// iOS/Android *devices* are `aarch64`; an iOS Simulator or Android
524    /// emulator build can target `x86_64`, which has none.
525    fn host_has_arm_simd() -> bool {
526        cfg!(target_arch = "aarch64")
527    }
528
529    #[test]
530    fn test_simd_optimizer_creation() {
531        let optimizer = SimdOptimizer::new(MobilePlatform::Ios);
532        // Regression guard for the previous unconditional
533        // `instructions.push(Neon)` on `MobilePlatform::Ios`: on a real
534        // `aarch64` build this must still detect real support; on a
535        // non-`aarch64` build (e.g. `x86_64-apple-ios`, the Simulator) it
536        // must now honestly report none rather than the fabricated
537        // constant it used to.
538        assert_eq!(
539            !optimizer.available_instructions.is_empty(),
540            host_has_arm_simd()
541        );
542    }
543
544    #[test]
545    fn test_vectorization_check() {
546        let optimizer = SimdOptimizer::new(MobilePlatform::Ios);
547
548        // `can_vectorize` is a property of the *kernel type*, independent
549        // of whether any SIMD instructions were actually detected (see
550        // `can_vectorize`'s own early-return on an empty instruction set,
551        // covered separately below).
552        if host_has_arm_simd() {
553            assert!(optimizer.can_vectorize(&KernelType::Conv2d));
554            assert!(optimizer.can_vectorize(&KernelType::Linear));
555            assert!(optimizer.can_vectorize(&KernelType::Activation));
556        } else {
557            assert!(!optimizer.can_vectorize(&KernelType::Conv2d));
558        }
559    }
560
561    #[test]
562    fn test_optimal_vector_width() {
563        let optimizer = SimdOptimizer::new(MobilePlatform::Ios);
564        let expected_base = if host_has_arm_simd() { 128 } else { 64 };
565
566        assert_eq!(
567            optimizer.optimal_vector_width(SimdDataType::Float32),
568            expected_base / 32
569        );
570        assert_eq!(
571            optimizer.optimal_vector_width(SimdDataType::Float16),
572            expected_base / 16
573        );
574        assert_eq!(
575            optimizer.optimal_vector_width(SimdDataType::Int8),
576            expected_base / 8
577        );
578    }
579
580    #[test]
581    fn test_performance_estimation() {
582        let speedup = SimdPerformanceEstimator::estimate_speedup(
583            SimdInstructions::Neon,
584            SimdDataType::Float32,
585            &KernelType::Linear,
586        );
587
588        assert!(speedup > 1.0);
589        assert!(speedup <= 4.0);
590    }
591
592    /// Regression tests for `NeonOptimizations`/`AdvSimdOptimizations`:
593    /// previously every method returned a `&'static str` of C source code
594    /// that no build step compiled, so there was no computed value to even
595    /// assert on. These call the real functions and check the arithmetic
596    /// itself, exercising both the `aarch64` NEON-intrinsic path (this test
597    /// binary is `aarch64-apple-darwin` when run on Apple Silicon, the
598    /// common case for this workspace) and, via non-multiple-of-4 lengths,
599    /// each function's scalar epilogue.
600    mod neon_and_advsimd_really_compute {
601        use super::*;
602
603        #[test]
604        fn vadd_f32_matches_elementwise_addition() {
605            // Length 7: exercises one full 4-lane NEON pass plus a
606            // 3-element scalar epilogue.
607            let a = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0];
608            let b = [10.0f32, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0];
609            let mut c = [0.0f32; 7];
610            NeonOptimizations::vadd_f32(&a, &b, &mut c);
611            for i in 0..7 {
612                assert_eq!(c[i], a[i] + b[i]);
613            }
614        }
615
616        #[test]
617        fn vmul_f32_matches_elementwise_multiplication() {
618            let a = [1.0f32, 2.0, 3.0, 4.0, 5.0];
619            let b = [2.0f32, 2.0, 2.0, 2.0, 2.0];
620            let mut c = [0.0f32; 5];
621            NeonOptimizations::vmul_f32(&a, &b, &mut c);
622            assert_eq!(c, [2.0, 4.0, 6.0, 8.0, 10.0]);
623        }
624
625        #[test]
626        fn vfma_f32_matches_a_times_b_plus_c() {
627            let a = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0];
628            let b = [2.0f32, 2.0, 2.0, 2.0, 2.0, 2.0];
629            let c = [1.0f32, 1.0, 1.0, 1.0, 1.0, 1.0];
630            let mut d = [0.0f32; 6];
631            NeonOptimizations::vfma_f32(&a, &b, &c, &mut d);
632            for i in 0..6 {
633                assert_eq!(d[i], a[i] * b[i] + c[i]);
634            }
635        }
636
637        #[test]
638        fn relu_f32_zeroes_negatives_and_keeps_positives() {
639            let input = [-2.0f32, -1.0, 0.0, 1.0, 2.0, 3.0, -0.5];
640            let mut output = [0.0f32; 7];
641            NeonOptimizations::relu_f32(&input, &mut output);
642            for i in 0..7 {
643                assert_eq!(output[i], input[i].max(0.0));
644            }
645        }
646
647        #[test]
648        fn dot_product_f32_matches_reference_sum() {
649            let a = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0];
650            let b = [9.0f32, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0];
651            let expected: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
652            let got = NeonOptimizations::dot_product_f32(&a, &b);
653            assert!(
654                (got - expected).abs() < 1e-4,
655                "got {got}, expected {expected} (dot product must be a real computation, not a \
656                 constant)"
657            );
658        }
659
660        #[test]
661        fn fp16_add_matches_elementwise_addition() {
662            let a = [half::f16::from_f32(1.5), half::f16::from_f32(2.5)];
663            let b = [half::f16::from_f32(0.25), half::f16::from_f32(0.75)];
664            let mut c = [half::f16::ZERO; 2];
665            AdvSimdOptimizations::fp16_add(&a, &b, &mut c);
666            assert_eq!(c[0].to_f32(), 1.75);
667            assert_eq!(c[1].to_f32(), 3.25);
668        }
669
670        #[test]
671        fn int8_dot_product_matches_reference_sum_including_negatives() {
672            let a: [i8; 5] = [1, -2, 3, -4, 127];
673            let b: [i8; 5] = [-1, 2, -3, 4, 127];
674            let expected: i32 =
675                a.iter().zip(b.iter()).map(|(&x, &y)| i32::from(x) * i32::from(y)).sum();
676            assert_eq!(AdvSimdOptimizations::int8_dot_product(&a, &b), expected);
677        }
678    }
679}