sklears-simd 0.1.1

High-performance SIMD acceleration primitives for the Sklears machine learning ecosystem
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
//! External SIMD library integration framework
//!
//! This module provides integration capabilities with external high-performance
//! SIMD libraries such as Intel MKL, OpenBLAS, BLIS, and others.

use crate::traits::SimdError;

#[cfg(feature = "no-std")]
use alloc::{
    collections::BTreeMap as HashMap,
    format,
    string::{String, ToString},
    sync::Arc,
    vec,
    vec::Vec,
};
#[cfg(not(feature = "no-std"))]
use std::collections::HashMap;
#[cfg(not(feature = "no-std"))]
use std::string::ToString;
#[cfg(not(feature = "no-std"))]
use std::sync::Arc;

#[cfg(feature = "no-std")]
use spin::Mutex;
#[cfg(not(feature = "no-std"))]
use std::sync::Mutex;

/// Result type for external library operations
pub type ExternalResult<T> = Result<T, SimdError>;

/// Trait for external library adapters
pub trait ExternalLibrary: Send + Sync {
    /// Get the library name
    fn name(&self) -> &str;

    /// Get the library version
    fn version(&self) -> &str;

    /// Check if the library is available on the system
    fn is_available(&self) -> bool;

    /// Initialize the library (if needed)
    fn initialize(&mut self) -> ExternalResult<()>;

    /// Get supported operations
    fn supported_operations(&self) -> Vec<String>;

    /// Check if a specific operation is supported
    fn supports_operation(&self, operation: &str) -> bool {
        self.supported_operations().contains(&operation.to_string())
    }
}

/// Trait for BLAS-like operations from external libraries
pub trait ExternalBlas: ExternalLibrary {
    /// Vector dot product (SDOT)
    fn dot(&self, x: &[f32], y: &[f32]) -> ExternalResult<f32>;

    /// Vector-scalar multiplication (SSCAL)
    fn scal(&self, alpha: f32, x: &mut [f32]) -> ExternalResult<()>;

    /// Vector addition (SAXPY): y = alpha * x + y
    fn axpy(&self, alpha: f32, x: &[f32], y: &mut [f32]) -> ExternalResult<()>;

    /// Matrix-vector multiplication (SGEMV)
    #[allow(clippy::too_many_arguments)] // BLAS SGEMV signature
    fn gemv(
        &self,
        alpha: f32,
        a: &[f32],
        m: usize,
        n: usize,
        x: &[f32],
        beta: f32,
        y: &mut [f32],
    ) -> ExternalResult<()>;

    /// Matrix-matrix multiplication (SGEMM)
    #[allow(clippy::too_many_arguments)] // BLAS SGEMM signature
    fn gemm(
        &self,
        alpha: f32,
        a: &[f32],
        m: usize,
        k: usize,
        b: &[f32],
        n: usize,
        beta: f32,
        c: &mut [f32],
    ) -> ExternalResult<()>;
}

/// Trait for LAPACK-like operations from external libraries
pub trait ExternalLapack: ExternalLibrary {
    /// LU decomposition
    fn lu_decomposition(&self, a: &mut [f32], m: usize, n: usize) -> ExternalResult<Vec<i32>>;

    /// QR decomposition
    fn qr_decomposition(&self, a: &mut [f32], m: usize, n: usize) -> ExternalResult<Vec<f32>>;

    /// Singular Value Decomposition
    fn svd(
        &self,
        a: &mut [f32],
        m: usize,
        n: usize,
    ) -> ExternalResult<(Vec<f32>, Vec<f32>, Vec<f32>)>;

    /// Eigenvalue decomposition
    fn eigenvalues(&self, a: &mut [f32], n: usize) -> ExternalResult<Vec<f32>>;
}

/// Trait for FFT operations from external libraries
pub trait ExternalFft: ExternalLibrary {
    /// Real-to-complex FFT
    fn rfft(&self, input: &[f32]) -> ExternalResult<Vec<f32>>;

    /// Complex-to-real inverse FFT
    fn irfft(&self, input: &[f32]) -> ExternalResult<Vec<f32>>;

    /// Complex-to-complex FFT
    fn cfft(&self, real: &[f32], imag: &[f32]) -> ExternalResult<(Vec<f32>, Vec<f32>)>;

    /// Complex-to-complex inverse FFT
    fn icfft(&self, real: &[f32], imag: &[f32]) -> ExternalResult<(Vec<f32>, Vec<f32>)>;
}

/// Mock implementation for Intel MKL adapter (demonstration)
#[derive(Debug, Clone)]
pub struct MklAdapter {
    initialized: bool,
}

impl MklAdapter {
    pub fn new() -> Self {
        Self { initialized: false }
    }
}

impl Default for MklAdapter {
    fn default() -> Self {
        Self::new()
    }
}

impl ExternalLibrary for MklAdapter {
    fn name(&self) -> &str {
        "Intel MKL"
    }

    fn version(&self) -> &str {
        "2024.0"
    }

    fn is_available(&self) -> bool {
        // In a real implementation, this would check for MKL libraries
        false // Mock: not available in test environment
    }

    fn initialize(&mut self) -> ExternalResult<()> {
        if !self.is_available() {
            return Err(SimdError::ExternalLibraryError(
                "MKL not available".to_string(),
            ));
        }
        self.initialized = true;
        Ok(())
    }

    fn supported_operations(&self) -> Vec<String> {
        vec![
            "dot".to_string(),
            "scal".to_string(),
            "axpy".to_string(),
            "gemv".to_string(),
            "gemm".to_string(),
            "lu".to_string(),
            "qr".to_string(),
            "svd".to_string(),
            "fft".to_string(),
        ]
    }
}

impl ExternalBlas for MklAdapter {
    fn dot(&self, x: &[f32], y: &[f32]) -> ExternalResult<f32> {
        if !self.initialized {
            return Err(SimdError::ExternalLibraryError(
                "MKL not initialized".to_string(),
            ));
        }

        if x.len() != y.len() {
            return Err(SimdError::InvalidInput(
                "Vector lengths must match".to_string(),
            ));
        }

        // Mock implementation - in reality would call cblas_sdot
        Ok(x.iter().zip(y.iter()).map(|(a, b)| a * b).sum())
    }

    fn scal(&self, alpha: f32, x: &mut [f32]) -> ExternalResult<()> {
        if !self.initialized {
            return Err(SimdError::ExternalLibraryError(
                "MKL not initialized".to_string(),
            ));
        }

        // Mock implementation - in reality would call cblas_sscal
        x.iter_mut().for_each(|v| *v *= alpha);
        Ok(())
    }

    fn axpy(&self, alpha: f32, x: &[f32], y: &mut [f32]) -> ExternalResult<()> {
        if !self.initialized {
            return Err(SimdError::ExternalLibraryError(
                "MKL not initialized".to_string(),
            ));
        }

        if x.len() != y.len() {
            return Err(SimdError::InvalidInput(
                "Vector lengths must match".to_string(),
            ));
        }

        // Mock implementation - in reality would call cblas_saxpy
        for (yi, &xi) in y.iter_mut().zip(x.iter()) {
            *yi += alpha * xi;
        }
        Ok(())
    }

    fn gemv(
        &self,
        alpha: f32,
        a: &[f32],
        m: usize,
        n: usize,
        x: &[f32],
        beta: f32,
        y: &mut [f32],
    ) -> ExternalResult<()> {
        if !self.initialized {
            return Err(SimdError::ExternalLibraryError(
                "MKL not initialized".to_string(),
            ));
        }

        if a.len() != m * n || x.len() != n || y.len() != m {
            return Err(SimdError::InvalidInput(
                "Matrix/vector dimension mismatch".to_string(),
            ));
        }

        // Mock implementation - in reality would call cblas_sgemv
        for i in 0..m {
            let mut sum = 0.0;
            for j in 0..n {
                sum += a[i * n + j] * x[j];
            }
            y[i] = alpha * sum + beta * y[i];
        }
        Ok(())
    }

    fn gemm(
        &self,
        alpha: f32,
        a: &[f32],
        m: usize,
        k: usize,
        b: &[f32],
        n: usize,
        beta: f32,
        c: &mut [f32],
    ) -> ExternalResult<()> {
        if !self.initialized {
            return Err(SimdError::ExternalLibraryError(
                "MKL not initialized".to_string(),
            ));
        }

        if a.len() != m * k || b.len() != k * n || c.len() != m * n {
            return Err(SimdError::InvalidInput(
                "Matrix dimension mismatch".to_string(),
            ));
        }

        // Mock implementation - in reality would call cblas_sgemm
        for i in 0..m {
            for j in 0..n {
                let mut sum = 0.0;
                for l in 0..k {
                    sum += a[i * k + l] * b[l * n + j];
                }
                c[i * n + j] = alpha * sum + beta * c[i * n + j];
            }
        }
        Ok(())
    }
}

/// Mock implementation for OpenBLAS adapter
#[derive(Debug, Clone)]
pub struct OpenBlasAdapter {
    initialized: bool,
}

impl OpenBlasAdapter {
    pub fn new() -> Self {
        Self { initialized: false }
    }
}

impl Default for OpenBlasAdapter {
    fn default() -> Self {
        Self::new()
    }
}

impl ExternalLibrary for OpenBlasAdapter {
    fn name(&self) -> &str {
        "OpenBLAS"
    }

    fn version(&self) -> &str {
        "0.3.21"
    }

    fn is_available(&self) -> bool {
        // Mock: assume available for demonstration
        true
    }

    fn initialize(&mut self) -> ExternalResult<()> {
        self.initialized = true;
        Ok(())
    }

    fn supported_operations(&self) -> Vec<String> {
        vec![
            "dot".to_string(),
            "scal".to_string(),
            "axpy".to_string(),
            "gemv".to_string(),
            "gemm".to_string(),
        ]
    }
}

impl ExternalBlas for OpenBlasAdapter {
    fn dot(&self, x: &[f32], y: &[f32]) -> ExternalResult<f32> {
        if !self.initialized {
            return Err(SimdError::ExternalLibraryError(
                "OpenBLAS not initialized".to_string(),
            ));
        }

        if x.len() != y.len() {
            return Err(SimdError::InvalidInput(
                "Vector lengths must match".to_string(),
            ));
        }

        // Mock implementation using our internal SIMD dot product
        Ok(crate::vector::dot_product(x, y))
    }

    fn scal(&self, alpha: f32, x: &mut [f32]) -> ExternalResult<()> {
        if !self.initialized {
            return Err(SimdError::ExternalLibraryError(
                "OpenBLAS not initialized".to_string(),
            ));
        }

        // Mock implementation using our internal SIMD scale
        crate::vector::scale(x, alpha);
        Ok(())
    }

    fn axpy(&self, alpha: f32, x: &[f32], y: &mut [f32]) -> ExternalResult<()> {
        if !self.initialized {
            return Err(SimdError::ExternalLibraryError(
                "OpenBLAS not initialized".to_string(),
            ));
        }

        if x.len() != y.len() {
            return Err(SimdError::InvalidInput(
                "Vector lengths must match".to_string(),
            ));
        }

        // Mock implementation
        for (yi, &xi) in y.iter_mut().zip(x.iter()) {
            *yi += alpha * xi;
        }
        Ok(())
    }

    fn gemv(
        &self,
        alpha: f32,
        a: &[f32],
        m: usize,
        n: usize,
        x: &[f32],
        beta: f32,
        y: &mut [f32],
    ) -> ExternalResult<()> {
        if !self.initialized {
            return Err(SimdError::ExternalLibraryError(
                "OpenBLAS not initialized".to_string(),
            ));
        }

        if a.len() != m * n || x.len() != n || y.len() != m {
            return Err(SimdError::InvalidInput(
                "Matrix/vector dimension mismatch".to_string(),
            ));
        }

        // Mock implementation using our internal matrix operations
        use scirs2_autograd::ndarray::{Array1, Array2};
        let a_matrix = Array2::from_shape_vec((m, n), a.to_vec())
            .map_err(|_| SimdError::ExternalLibraryError("Invalid matrix shape".to_string()))?;
        let x_vector = Array1::from_vec(x.to_vec());
        let result = crate::matrix::matrix_vector_multiply_f32(&a_matrix, &x_vector);

        for (yi, &ri) in y.iter_mut().zip(result.iter()) {
            *yi = alpha * ri + beta * (*yi);
        }
        Ok(())
    }

    fn gemm(
        &self,
        alpha: f32,
        a: &[f32],
        m: usize,
        k: usize,
        b: &[f32],
        n: usize,
        beta: f32,
        c: &mut [f32],
    ) -> ExternalResult<()> {
        if !self.initialized {
            return Err(SimdError::ExternalLibraryError(
                "OpenBLAS not initialized".to_string(),
            ));
        }

        if a.len() != m * k || b.len() != k * n || c.len() != m * n {
            return Err(SimdError::InvalidInput(
                "Matrix dimension mismatch".to_string(),
            ));
        }

        // Mock implementation using our internal matrix operations
        use scirs2_autograd::ndarray::Array2;
        let a_matrix = Array2::from_shape_vec((m, k), a.to_vec())
            .map_err(|_| SimdError::ExternalLibraryError("Invalid matrix A shape".to_string()))?;
        let b_matrix = Array2::from_shape_vec((k, n), b.to_vec())
            .map_err(|_| SimdError::ExternalLibraryError("Invalid matrix B shape".to_string()))?;
        let result = crate::matrix::matrix_multiply_f32_simd(&a_matrix, &b_matrix);

        for (ci, &ri) in c.iter_mut().zip(result.iter()) {
            *ci = alpha * ri + beta * (*ci);
        }
        Ok(())
    }
}

/// External library registry and management
pub struct ExternalLibraryRegistry {
    /// Registered BLAS libraries
    blas_libraries: HashMap<String, Arc<Mutex<dyn ExternalBlas>>>,
    /// Registered LAPACK libraries
    lapack_libraries: HashMap<String, Arc<Mutex<dyn ExternalLapack>>>,
    /// Registered FFT libraries
    fft_libraries: HashMap<String, Arc<Mutex<dyn ExternalFft>>>,
    /// Preferred library for each operation type
    preferences: HashMap<String, String>,
}

impl ExternalLibraryRegistry {
    /// Create a new registry
    pub fn new() -> Self {
        Self {
            blas_libraries: HashMap::new(),
            lapack_libraries: HashMap::new(),
            fft_libraries: HashMap::new(),
            preferences: HashMap::new(),
        }
    }

    /// Register a BLAS library
    pub fn register_blas<T: ExternalBlas + 'static>(&mut self, library: T) {
        let name = library.name().to_string();
        self.blas_libraries
            .insert(name.clone(), Arc::new(Mutex::new(library)));

        // Set as default if none set
        if !self.preferences.contains_key("blas") {
            self.preferences.insert("blas".to_string(), name);
        }
    }

    /// Register a LAPACK library
    pub fn register_lapack<T: ExternalLapack + 'static>(&mut self, library: T) {
        let name = library.name().to_string();
        self.lapack_libraries
            .insert(name.clone(), Arc::new(Mutex::new(library)));

        // Set as default if none set
        if !self.preferences.contains_key("lapack") {
            self.preferences.insert("lapack".to_string(), name);
        }
    }

    /// Register an FFT library
    pub fn register_fft<T: ExternalFft + 'static>(&mut self, library: T) {
        let name = library.name().to_string();
        self.fft_libraries
            .insert(name.clone(), Arc::new(Mutex::new(library)));

        // Set as default if none set
        if !self.preferences.contains_key("fft") {
            self.preferences.insert("fft".to_string(), name);
        }
    }

    /// Set preferred library for operation type
    pub fn set_preference(
        &mut self,
        operation_type: &str,
        library_name: &str,
    ) -> ExternalResult<()> {
        match operation_type {
            "blas" => {
                if !self.blas_libraries.contains_key(library_name) {
                    return Err(SimdError::ExternalLibraryError(format!(
                        "BLAS library '{}' not registered",
                        library_name
                    )));
                }
            }
            "lapack" => {
                if !self.lapack_libraries.contains_key(library_name) {
                    return Err(SimdError::ExternalLibraryError(format!(
                        "LAPACK library '{}' not registered",
                        library_name
                    )));
                }
            }
            "fft" => {
                if !self.fft_libraries.contains_key(library_name) {
                    return Err(SimdError::ExternalLibraryError(format!(
                        "FFT library '{}' not registered",
                        library_name
                    )));
                }
            }
            _ => {
                return Err(SimdError::InvalidInput(format!(
                    "Unknown operation type: {}",
                    operation_type
                )));
            }
        }

        self.preferences
            .insert(operation_type.to_string(), library_name.to_string());
        Ok(())
    }

    /// Get preferred BLAS library
    pub fn get_blas(&self) -> Option<Arc<Mutex<dyn ExternalBlas>>> {
        self.preferences
            .get("blas")
            .and_then(|name| self.blas_libraries.get(name))
            .cloned()
    }

    /// Get preferred LAPACK library
    pub fn get_lapack(&self) -> Option<Arc<Mutex<dyn ExternalLapack>>> {
        self.preferences
            .get("lapack")
            .and_then(|name| self.lapack_libraries.get(name))
            .cloned()
    }

    /// Get preferred FFT library
    pub fn get_fft(&self) -> Option<Arc<Mutex<dyn ExternalFft>>> {
        self.preferences
            .get("fft")
            .and_then(|name| self.fft_libraries.get(name))
            .cloned()
    }

    /// List all registered libraries
    pub fn list_libraries(&self) -> Vec<String> {
        let mut libraries = Vec::new();
        libraries.extend(self.blas_libraries.keys().cloned());
        libraries.extend(self.lapack_libraries.keys().cloned());
        libraries.extend(self.fft_libraries.keys().cloned());
        libraries.sort();
        libraries.dedup();
        libraries
    }

    /// Check library availability
    pub fn check_availability(&self) -> HashMap<String, bool> {
        let mut availability = HashMap::new();

        #[cfg(not(feature = "no-std"))]
        {
            for (name, library) in &self.blas_libraries {
                availability.insert(
                    name.clone(),
                    library
                        .lock()
                        .expect("lock should not be poisoned")
                        .is_available(),
                );
            }

            for (name, library) in &self.lapack_libraries {
                availability.insert(
                    name.clone(),
                    library
                        .lock()
                        .expect("lock should not be poisoned")
                        .is_available(),
                );
            }

            for (name, library) in &self.fft_libraries {
                availability.insert(
                    name.clone(),
                    library
                        .lock()
                        .expect("lock should not be poisoned")
                        .is_available(),
                );
            }
        }

        #[cfg(feature = "no-std")]
        {
            for (name, library) in &self.blas_libraries {
                availability.insert(name.clone(), library.lock().is_available());
            }

            for (name, library) in &self.lapack_libraries {
                availability.insert(name.clone(), library.lock().is_available());
            }

            for (name, library) in &self.fft_libraries {
                availability.insert(name.clone(), library.lock().is_available());
            }
        }

        availability
    }
}

impl Default for ExternalLibraryRegistry {
    fn default() -> Self {
        let mut registry = Self::new();

        // Register default adapters
        registry.register_blas(OpenBlasAdapter::new());
        registry.register_blas(MklAdapter::new());

        registry
    }
}

/// Global external library registry
#[cfg(not(feature = "no-std"))]
static EXTERNAL_REGISTRY: once_cell::sync::Lazy<std::sync::Mutex<ExternalLibraryRegistry>> =
    once_cell::sync::Lazy::new(|| std::sync::Mutex::new(ExternalLibraryRegistry::default()));

#[cfg(feature = "no-std")]
static EXTERNAL_REGISTRY: spin::Once<spin::Mutex<ExternalLibraryRegistry>> = spin::Once::new();

/// Get the global external library registry
#[cfg(not(feature = "no-std"))]
pub fn get_registry() -> &'static std::sync::Mutex<ExternalLibraryRegistry> {
    &EXTERNAL_REGISTRY
}

#[cfg(feature = "no-std")]
pub fn get_registry() -> &'static spin::Mutex<ExternalLibraryRegistry> {
    EXTERNAL_REGISTRY.call_once(|| spin::Mutex::new(ExternalLibraryRegistry::default()))
}

/// Perform dot product using external BLAS if available, fallback to internal
pub fn external_dot(x: &[f32], y: &[f32]) -> ExternalResult<f32> {
    #[cfg(not(feature = "no-std"))]
    {
        if let Some(blas) = get_registry()
            .lock()
            .expect("lock should not be poisoned")
            .get_blas()
        {
            // Try to use external BLAS, but fallback to internal if it fails
            match blas
                .lock()
                .expect("matrix dimensions should be compatible for dot product")
                .dot(x, y)
            {
                Ok(result) => Ok(result),
                Err(_) => {
                    // Fall back to internal implementation if external library fails
                    Ok(crate::vector::dot_product(x, y))
                }
            }
        } else {
            Ok(crate::vector::dot_product(x, y))
        }
    }
    #[cfg(feature = "no-std")]
    {
        if let Some(blas) = get_registry().lock().get_blas() {
            // Try to use external BLAS, but fallback to internal if it fails
            match blas.lock().dot(x, y) {
                Ok(result) => Ok(result),
                Err(_) => {
                    // Fall back to internal implementation if external library fails
                    Ok(crate::vector::dot_product(x, y))
                }
            }
        } else {
            Ok(crate::vector::dot_product(x, y))
        }
    }
}

/// Perform matrix-vector multiplication using external BLAS if available
pub fn external_gemv(
    alpha: f32,
    a: &[f32],
    m: usize,
    n: usize,
    x: &[f32],
    beta: f32,
    y: &mut [f32],
) -> ExternalResult<()> {
    #[cfg(not(feature = "no-std"))]
    {
        if let Some(blas) = get_registry()
            .lock()
            .expect("lock should not be poisoned")
            .get_blas()
        {
            // Try to use external BLAS, but fallback to internal if it fails
            match blas
                .lock()
                .expect("lock should not be poisoned")
                .gemv(alpha, a, m, n, x, beta, y)
            {
                Ok(()) => Ok(()),
                Err(_) => {
                    // Fall back to internal implementation if external library fails
                    use scirs2_autograd::ndarray::{Array1, Array2};
                    let a_matrix = Array2::from_shape_vec((m, n), a.to_vec()).map_err(|_| {
                        SimdError::ExternalLibraryError("Invalid matrix shape".to_string())
                    })?;
                    let x_vector = Array1::from_vec(x.to_vec());
                    let result = crate::matrix::matrix_vector_multiply_f32(&a_matrix, &x_vector);

                    for (yi, &ri) in y.iter_mut().zip(result.iter()) {
                        *yi = alpha * ri + beta * (*yi);
                    }
                    Ok(())
                }
            }
        } else {
            // Fallback to internal implementation
            use scirs2_autograd::ndarray::{Array1, Array2};
            let a_matrix = Array2::from_shape_vec((m, n), a.to_vec())
                .map_err(|_| SimdError::ExternalLibraryError("Invalid matrix shape".to_string()))?;
            let x_vector = Array1::from_vec(x.to_vec());
            let result = crate::matrix::matrix_vector_multiply_f32(&a_matrix, &x_vector);

            for (yi, &ri) in y.iter_mut().zip(result.iter()) {
                *yi = alpha * ri + beta * (*yi);
            }
            Ok(())
        }
    }
    #[cfg(feature = "no-std")]
    {
        if let Some(blas) = get_registry().lock().get_blas() {
            // Try to use external BLAS, but fallback to internal if it fails
            match blas.lock().gemv(alpha, a, m, n, x, beta, y) {
                Ok(()) => Ok(()),
                Err(_) => {
                    // Fall back to internal implementation if external library fails
                    use scirs2_autograd::ndarray::{Array1, Array2};
                    let a_matrix = Array2::from_shape_vec((m, n), a.to_vec()).map_err(|_| {
                        SimdError::ExternalLibraryError("Invalid matrix shape".to_string())
                    })?;
                    let x_vector = Array1::from_vec(x.to_vec());
                    let result = crate::matrix::matrix_vector_multiply_f32(&a_matrix, &x_vector);

                    for (yi, &ri) in y.iter_mut().zip(result.iter()) {
                        *yi = alpha * ri + beta * (*yi);
                    }
                    Ok(())
                }
            }
        } else {
            // Fallback to internal implementation
            use scirs2_autograd::ndarray::{Array1, Array2};
            let a_matrix = Array2::from_shape_vec((m, n), a.to_vec())
                .map_err(|_| SimdError::ExternalLibraryError("Invalid matrix shape".to_string()))?;
            let x_vector = Array1::from_vec(x.to_vec());
            let result = crate::matrix::matrix_vector_multiply_f32(&a_matrix, &x_vector);

            for (yi, &ri) in y.iter_mut().zip(result.iter()) {
                *yi = alpha * ri + beta * (*yi);
            }
            Ok(())
        }
    }
}

#[allow(non_snake_case)]
#[cfg(all(test, not(feature = "no-std")))]
mod tests {
    use super::*;

    #[cfg(feature = "no-std")]
    use alloc::{
        string::{String, ToString},
        vec,
        vec::Vec,
    };

    #[test]
    fn test_mkl_adapter_creation() {
        let adapter = MklAdapter::new();
        assert_eq!(adapter.name(), "Intel MKL");
        assert_eq!(adapter.version(), "2024.0");
        assert!(!adapter.is_available()); // Mock: not available
    }

    #[test]
    fn test_openblas_adapter_creation() {
        let adapter = OpenBlasAdapter::new();
        assert_eq!(adapter.name(), "OpenBLAS");
        assert_eq!(adapter.version(), "0.3.21");
        assert!(adapter.is_available()); // Mock: available
    }

    #[test]
    fn test_openblas_initialization() {
        let mut adapter = OpenBlasAdapter::new();
        assert!(adapter.initialize().is_ok());
    }

    #[test]
    fn test_openblas_dot_product() {
        let mut adapter = OpenBlasAdapter::new();
        adapter.initialize().expect("operation should succeed");

        let x = vec![1.0, 2.0, 3.0];
        let y = vec![4.0, 5.0, 6.0];
        let result = adapter
            .dot(&x, &y)
            .expect("matrix dimensions should be compatible for dot product");

        assert_eq!(result, 32.0); // 1*4 + 2*5 + 3*6
    }

    #[test]
    fn test_openblas_scal() {
        let mut adapter = OpenBlasAdapter::new();
        adapter.initialize().expect("operation should succeed");

        let mut x = vec![1.0, 2.0, 3.0];
        adapter.scal(2.0, &mut x).expect("operation should succeed");

        assert_eq!(x, vec![2.0, 4.0, 6.0]);
    }

    #[test]
    fn test_registry_blas_registration() {
        let mut registry = ExternalLibraryRegistry::new();
        let adapter = OpenBlasAdapter::new();

        registry.register_blas(adapter);

        assert!(registry.get_blas().is_some());
        assert_eq!(registry.list_libraries(), vec!["OpenBLAS"]);
    }

    #[test]
    fn test_registry_preferences() {
        let mut registry = ExternalLibraryRegistry::new();
        let adapter1 = OpenBlasAdapter::new();
        let adapter2 = MklAdapter::new();

        registry.register_blas(adapter1);
        registry.register_blas(adapter2);

        // Set preference to MKL
        registry
            .set_preference("blas", "Intel MKL")
            .expect("operation should succeed");

        // Should fail for unknown library
        assert!(registry.set_preference("blas", "Unknown").is_err());
    }

    #[test]
    fn test_registry_availability_check() {
        let registry = ExternalLibraryRegistry::default();
        let availability = registry.check_availability();

        // OpenBLAS should be available (mock), MKL should not
        assert_eq!(availability.get("OpenBLAS"), Some(&true));
        assert_eq!(availability.get("Intel MKL"), Some(&false));
    }

    #[test]
    fn test_external_dot_fallback() {
        // This should fallback to internal implementation
        let x = vec![1.0, 2.0, 3.0];
        let y = vec![4.0, 5.0, 6.0];
        let result = external_dot(&x, &y).expect("operation should succeed");

        assert_eq!(result, 32.0);
    }

    #[test]
    fn test_invalid_dimensions() {
        let mut adapter = OpenBlasAdapter::new();
        adapter.initialize().expect("operation should succeed");

        let x = vec![1.0, 2.0];
        let y = vec![3.0, 4.0, 5.0];

        assert!(adapter.dot(&x, &y).is_err());
    }

    #[test]
    fn test_uninitialized_adapter() {
        let adapter = OpenBlasAdapter::new();
        let x = vec![1.0, 2.0, 3.0];
        let y = vec![4.0, 5.0, 6.0];

        assert!(adapter.dot(&x, &y).is_err());
    }
}