1use super::KernelType;
7use crate::MobilePlatform;
8use trustformers_core::error::Result;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum SimdInstructions {
13 Neon,
15 Sve,
17 AdvSimd,
19 None,
21}
22
23#[derive(Debug, Clone)]
25pub struct VectorizationStrategy {
26 pub instruction_set: SimdInstructions,
28 pub vector_width: usize,
30 pub data_type: SimdDataType,
32 pub alignment: usize,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum SimdDataType {
39 Float32,
40 Float16,
41 Int8,
42 Int16,
43 Int32,
44}
45
46pub struct SimdOptimizer {
48 platform: MobilePlatform,
49 available_instructions: Vec<SimdInstructions>,
50 capabilities: SimdCapabilities,
51}
52
53#[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 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 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 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 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 fn detect_simd_support(platform: &MobilePlatform) -> Vec<SimdInstructions> {
126 let mut instructions = Vec::new();
127
128 match platform {
129 MobilePlatform::Ios => {
130 if cfg!(target_arch = "aarch64") {
138 instructions.push(SimdInstructions::Neon);
139 instructions.push(SimdInstructions::AdvSimd);
140 }
141 },
142 MobilePlatform::Android => {
143 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 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 let instruction_set =
199 self.available_instructions.first().copied().unwrap_or(SimdInstructions::None);
200
201 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 matches!(kernel, KernelType::Activation | KernelType::BatchNorm)
224 }
225
226 fn should_use_int8(&self, kernel: &KernelType) -> bool {
227 false }
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
259pub struct NeonOptimizations;
273
274impl NeonOptimizations {
275 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 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 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 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 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 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 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 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 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 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
438pub struct AdvSimdOptimizations;
457
458impl AdvSimdOptimizations {
459 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 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
480pub struct SimdPerformanceEstimator;
482
483impl SimdPerformanceEstimator {
484 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, (SimdInstructions::None, _) => 1.0,
499 _ => 2.0,
500 };
501
502 let operation_efficiency = match operation {
504 KernelType::Conv2d => 0.8, KernelType::Linear => 0.9, KernelType::Activation => 0.95, KernelType::BatchNorm => 0.85, KernelType::Pooling => 0.7, _ => 0.6,
510 };
511
512 vector_speedup * operation_efficiency
513 }
514}
515
516#[cfg(test)]
517mod tests {
518 use super::*;
519
520 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 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 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 mod neon_and_advsimd_really_compute {
601 use super::*;
602
603 #[test]
604 fn vadd_f32_matches_elementwise_addition() {
605 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}