sklears-simd 0.1.2

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
//! Custom accelerator support framework
//!
//! This module provides a flexible framework for integrating custom hardware
//! accelerators with the SIMD operations, including ASICs, custom chips, and
//! specialized processing units.

use crate::traits::SimdError;

#[cfg(feature = "no-std")]
use core::any::Any;
#[cfg(not(feature = "no-std"))]
use std::any::Any;

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

#[cfg(feature = "no-std")]
extern crate alloc;

/// Accelerator types
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AcceleratorType {
    ASIC,
    Custom,
    DSP,
    VPU,    // Vision Processing Unit
    NPU,    // Neural Processing Unit
    DPU,    // Deep Learning Processing Unit
    AI,     // Generic AI accelerator
    Crypto, // Cryptographic accelerator
    Signal, // Signal processing accelerator
    Matrix, // Matrix processing accelerator
}

/// Accelerator capabilities
#[derive(Debug, Clone)]
pub struct AcceleratorCapabilities {
    pub supported_operations: Vec<AcceleratorOperation>,
    pub data_types: Vec<AcceleratorDataType>,
    pub max_batch_size: usize,
    pub memory_mb: u64,
    pub compute_units: u32,
    pub peak_performance_ops: u64,
    pub power_consumption_w: f64,
    pub precision_modes: Vec<AcceleratorPrecision>,
}

/// Accelerator operations
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AcceleratorOperation {
    MatrixMultiply,
    Convolution,
    Activation,
    Pooling,
    Normalization,
    Attention,
    Embedding,
    Reduction,
    Transform,
    Sort,
    Search,
    Compress,
    Encrypt,
    Hash,
    Custom(u32),
}

/// Accelerator data types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AcceleratorDataType {
    F32,
    F16,
    BF16,
    I32,
    I16,
    I8,
    U32,
    U16,
    U8,
    Bool,
    Custom(u32),
}

/// Accelerator precision modes
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AcceleratorPrecision {
    High,
    Medium,
    Low,
    Mixed,
    Adaptive,
}

/// Accelerator device information
#[derive(Debug, Clone)]
pub struct AcceleratorDevice {
    pub id: u32,
    pub name: String,
    pub vendor: String,
    pub model: String,
    pub accelerator_type: AcceleratorType,
    pub capabilities: AcceleratorCapabilities,
    pub driver_version: String,
    pub firmware_version: String,
    pub pci_id: Option<String>,
    pub numa_node: Option<u32>,
}

/// Accelerator buffer
#[derive(Debug)]
pub struct AcceleratorBuffer<T> {
    pub ptr: *mut T,
    pub size: usize,
    pub device: AcceleratorDevice,
    pub alignment: usize,
    pub memory_type: AcceleratorMemoryType,
    #[allow(dead_code)] // Reserved for native accelerator backend handle (CUDA/OpenCL/custom)
    backend_handle: Option<Box<dyn Any + Send + Sync>>,
}

/// Accelerator memory types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AcceleratorMemoryType {
    Device,
    Host,
    Unified,
    Pinned,
    Cached,
    Uncached,
}

unsafe impl<T: Send> Send for AcceleratorBuffer<T> {}
unsafe impl<T: Sync> Sync for AcceleratorBuffer<T> {}

impl<T> Drop for AcceleratorBuffer<T> {
    fn drop(&mut self) {
        // Free accelerator memory when buffer is dropped
    }
}

/// Accelerator context
pub struct AcceleratorContext {
    pub device: AcceleratorDevice,
    pub command_queues: Vec<AcceleratorQueue>,
    pub memory_pools: HashMap<AcceleratorMemoryType, AcceleratorMemoryPool>,
    #[allow(dead_code)] // Reserved for native accelerator backend context (CUDA/OpenCL/custom)
    backend_context: Option<Box<dyn Any + Send + Sync>>,
}

/// Accelerator command queue
#[derive(Debug)]
pub struct AcceleratorQueue {
    pub id: u32,
    pub priority: AcceleratorPriority,
    pub device_id: u32,
    #[allow(dead_code)] // Reserved for native command queue handle (CUDA stream / OpenCL queue)
    backend_queue: Option<Box<dyn Any + Send + Sync>>,
}

/// Accelerator priority levels
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AcceleratorPriority {
    Low,
    Normal,
    High,
    Critical,
}

/// Accelerator memory pool
#[derive(Debug)]
pub struct AcceleratorMemoryPool {
    pub total_size: usize,
    pub available_size: usize,
    pub allocation_count: usize,
    pub memory_type: AcceleratorMemoryType,
    #[allow(dead_code)] // Reserved for native memory pool handle (CUDA/OpenCL/custom allocator)
    backend_pool: Option<Box<dyn Any + Send + Sync>>,
}

/// Accelerator kernel configuration
#[derive(Debug, Clone)]
pub struct AcceleratorKernel {
    pub name: String,
    pub operation: AcceleratorOperation,
    pub input_buffers: Vec<u32>,
    pub output_buffers: Vec<u32>,
    pub parameters: HashMap<String, AcceleratorParameter>,
    pub work_size: (usize, usize, usize),
    pub local_size: (usize, usize, usize),
}

/// Accelerator parameter
#[derive(Debug, Clone)]
pub enum AcceleratorParameter {
    Int(i64),
    Float(f64),
    Bool(bool),
    String(String),
    Array(Vec<u8>),
}

/// Accelerator operations interface
pub trait AcceleratorOperations {
    /// Allocate accelerator memory
    fn allocate<T>(
        &self,
        size: usize,
        memory_type: AcceleratorMemoryType,
    ) -> Result<AcceleratorBuffer<T>, SimdError>;

    /// Copy data to accelerator
    fn copy_to_accelerator<T>(
        &self,
        host_data: &[T],
        accel_buffer: &mut AcceleratorBuffer<T>,
        queue: Option<&AcceleratorQueue>,
    ) -> Result<(), SimdError>;

    /// Copy data from accelerator
    fn copy_from_accelerator<T>(
        &self,
        accel_buffer: &AcceleratorBuffer<T>,
        host_data: &mut [T],
        queue: Option<&AcceleratorQueue>,
    ) -> Result<(), SimdError>;

    /// Execute kernel on accelerator
    fn execute_kernel(
        &self,
        kernel: &AcceleratorKernel,
        buffers: &[&AcceleratorBuffer<u8>],
        queue: Option<&AcceleratorQueue>,
    ) -> Result<(), SimdError>;

    /// Synchronize accelerator operations
    fn synchronize(&self, queue: Option<&AcceleratorQueue>) -> Result<(), SimdError>;

    /// Get accelerator status
    fn get_status(&self) -> Result<AcceleratorStatus, SimdError>;
}

/// Accelerator status
#[derive(Debug, Clone)]
pub struct AcceleratorStatus {
    pub utilization_percent: f64,
    pub memory_usage_percent: f64,
    pub temperature_c: f64,
    pub power_consumption_w: f64,
    pub clock_frequency_mhz: f64,
    pub active_operations: Vec<AcceleratorOperation>,
    pub error_count: u32,
}

/// Accelerator runtime
pub struct AcceleratorRuntime {
    devices: Vec<AcceleratorDevice>,
    contexts: Vec<AcceleratorContext>,
    drivers: HashMap<AcceleratorType, Box<dyn AcceleratorDriver>>,
}

/// Accelerator driver interface
pub trait AcceleratorDriver: Send + Sync {
    fn initialize(&self) -> Result<(), SimdError>;
    fn discover_devices(&self) -> Result<Vec<AcceleratorDevice>, SimdError>;
    fn create_context(&self, device: &AcceleratorDevice) -> Result<AcceleratorContext, SimdError>;
    fn is_available(&self) -> bool;
}

impl AcceleratorRuntime {
    /// Create new accelerator runtime
    pub fn new() -> Result<Self, SimdError> {
        let mut runtime = Self {
            devices: Vec::new(),
            contexts: Vec::new(),
            drivers: HashMap::new(),
        };

        // Register built-in drivers
        runtime.register_driver(AcceleratorType::ASIC, Box::new(AsicDriver::new()));
        runtime.register_driver(AcceleratorType::DSP, Box::new(DspDriver::new()));
        runtime.register_driver(AcceleratorType::VPU, Box::new(VpuDriver::new()));
        runtime.register_driver(AcceleratorType::NPU, Box::new(NpuDriver::new()));

        // Discover devices
        runtime.discover_all_devices()?;

        Ok(runtime)
    }

    /// Register accelerator driver
    pub fn register_driver(
        &mut self,
        accel_type: AcceleratorType,
        driver: Box<dyn AcceleratorDriver>,
    ) {
        self.drivers.insert(accel_type, driver);
    }

    /// Discover all devices
    fn discover_all_devices(&mut self) -> Result<(), SimdError> {
        for driver in self.drivers.values() {
            if driver.is_available() {
                let devices = driver.discover_devices()?;
                self.devices.extend(devices);
            }
        }
        Ok(())
    }

    /// Get available devices
    pub fn devices(&self) -> &[AcceleratorDevice] {
        &self.devices
    }

    /// Get devices by type
    pub fn devices_by_type(&self, accel_type: AcceleratorType) -> Vec<&AcceleratorDevice> {
        self.devices
            .iter()
            .filter(|d| d.accelerator_type == accel_type)
            .collect()
    }

    /// Create context for device
    pub fn create_context(&mut self, device_id: u32) -> Result<&AcceleratorContext, SimdError> {
        let device = self.devices.get(device_id as usize).ok_or_else(|| {
            SimdError::InvalidArgument("Invalid accelerator device ID".to_string())
        })?;

        let driver = self
            .drivers
            .get(&device.accelerator_type)
            .ok_or_else(|| SimdError::NotImplemented("Driver not available".to_string()))?;

        let context = driver.create_context(device)?;
        self.contexts.push(context);
        Ok(self
            .contexts
            .last()
            .expect("collection should not be empty"))
    }

    /// Get best device for operation
    pub fn get_best_device(&self, operation: AcceleratorOperation) -> Option<&AcceleratorDevice> {
        self.devices
            .iter()
            .filter(|d| d.capabilities.supported_operations.contains(&operation))
            .max_by(|a, b| {
                a.capabilities
                    .peak_performance_ops
                    .cmp(&b.capabilities.peak_performance_ops)
            })
    }
}

/// Built-in accelerator drivers
struct AsicDriver;
struct DspDriver;
struct VpuDriver;
struct NpuDriver;

impl AsicDriver {
    fn new() -> Self {
        Self
    }
}

impl AcceleratorDriver for AsicDriver {
    fn initialize(&self) -> Result<(), SimdError> {
        Ok(())
    }

    fn discover_devices(&self) -> Result<Vec<AcceleratorDevice>, SimdError> {
        Ok(vec![])
    }

    fn create_context(&self, device: &AcceleratorDevice) -> Result<AcceleratorContext, SimdError> {
        Ok(AcceleratorContext {
            device: device.clone(),
            command_queues: vec![],
            memory_pools: HashMap::new(),
            backend_context: None,
        })
    }

    fn is_available(&self) -> bool {
        false
    }
}

impl DspDriver {
    fn new() -> Self {
        Self
    }
}

impl AcceleratorDriver for DspDriver {
    fn initialize(&self) -> Result<(), SimdError> {
        Ok(())
    }

    fn discover_devices(&self) -> Result<Vec<AcceleratorDevice>, SimdError> {
        Ok(vec![])
    }

    fn create_context(&self, device: &AcceleratorDevice) -> Result<AcceleratorContext, SimdError> {
        Ok(AcceleratorContext {
            device: device.clone(),
            command_queues: vec![],
            memory_pools: HashMap::new(),
            backend_context: None,
        })
    }

    fn is_available(&self) -> bool {
        false
    }
}

impl VpuDriver {
    fn new() -> Self {
        Self
    }
}

impl AcceleratorDriver for VpuDriver {
    fn initialize(&self) -> Result<(), SimdError> {
        Ok(())
    }

    fn discover_devices(&self) -> Result<Vec<AcceleratorDevice>, SimdError> {
        Ok(vec![])
    }

    fn create_context(&self, device: &AcceleratorDevice) -> Result<AcceleratorContext, SimdError> {
        Ok(AcceleratorContext {
            device: device.clone(),
            command_queues: vec![],
            memory_pools: HashMap::new(),
            backend_context: None,
        })
    }

    fn is_available(&self) -> bool {
        false
    }
}

impl NpuDriver {
    fn new() -> Self {
        Self
    }
}

impl AcceleratorDriver for NpuDriver {
    fn initialize(&self) -> Result<(), SimdError> {
        Ok(())
    }

    fn discover_devices(&self) -> Result<Vec<AcceleratorDevice>, SimdError> {
        Ok(vec![])
    }

    fn create_context(&self, device: &AcceleratorDevice) -> Result<AcceleratorContext, SimdError> {
        Ok(AcceleratorContext {
            device: device.clone(),
            command_queues: vec![],
            memory_pools: HashMap::new(),
            backend_context: None,
        })
    }

    fn is_available(&self) -> bool {
        false
    }
}

/// Accelerator optimization utilities
pub mod optimization {
    use super::*;

    /// Optimize kernel for specific accelerator
    pub fn optimize_kernel(
        kernel: &AcceleratorKernel,
        device: &AcceleratorDevice,
    ) -> Result<AcceleratorKernel, SimdError> {
        let mut optimized = kernel.clone();

        // Optimize based on device capabilities
        match device.accelerator_type {
            AcceleratorType::NPU => {
                // Optimize for neural processing
                optimized.work_size = optimize_for_npu(kernel.work_size, &device.capabilities);
            }
            AcceleratorType::VPU => {
                // Optimize for vision processing
                optimized.work_size = optimize_for_vpu(kernel.work_size, &device.capabilities);
            }
            AcceleratorType::DSP => {
                // Optimize for signal processing
                optimized.work_size = optimize_for_dsp(kernel.work_size, &device.capabilities);
            }
            _ => {
                // Generic optimization
                optimized.work_size = optimize_generic(kernel.work_size, &device.capabilities);
            }
        }

        Ok(optimized)
    }

    fn optimize_for_npu(
        work_size: (usize, usize, usize),
        caps: &AcceleratorCapabilities,
    ) -> (usize, usize, usize) {
        let optimal_batch = caps.max_batch_size.min(work_size.0);
        (optimal_batch, work_size.1, work_size.2)
    }

    fn optimize_for_vpu(
        work_size: (usize, usize, usize),
        caps: &AcceleratorCapabilities,
    ) -> (usize, usize, usize) {
        let compute_units = caps.compute_units as usize;
        let optimal_x = work_size.0.div_ceil(compute_units) * compute_units;
        (optimal_x, work_size.1, work_size.2)
    }

    fn optimize_for_dsp(
        work_size: (usize, usize, usize),
        _caps: &AcceleratorCapabilities,
    ) -> (usize, usize, usize) {
        // DSP typically works well with power-of-2 sizes
        let next_power_of_2 = |n: usize| {
            if n == 0 {
                1
            } else {
                1 << (64 - (n - 1).leading_zeros())
            }
        };

        (next_power_of_2(work_size.0), work_size.1, work_size.2)
    }

    fn optimize_generic(
        work_size: (usize, usize, usize),
        caps: &AcceleratorCapabilities,
    ) -> (usize, usize, usize) {
        let compute_units = caps.compute_units as usize;
        let optimal_size = work_size.0.div_ceil(compute_units) * compute_units;
        (optimal_size, work_size.1, work_size.2)
    }

    /// Select best accelerator for operation
    pub fn select_accelerator(
        operation: AcceleratorOperation,
        data_size: usize,
        devices: &[AcceleratorDevice],
    ) -> Option<&AcceleratorDevice> {
        devices
            .iter()
            .filter(|d| d.capabilities.supported_operations.contains(&operation))
            .filter(|d| d.capabilities.max_batch_size >= data_size)
            .max_by(|a, b| {
                let score_a = compute_device_score(a, operation, data_size);
                let score_b = compute_device_score(b, operation, data_size);
                score_a
                    .partial_cmp(&score_b)
                    .unwrap_or(core::cmp::Ordering::Equal)
            })
    }

    fn compute_device_score(
        device: &AcceleratorDevice,
        operation: AcceleratorOperation,
        data_size: usize,
    ) -> f64 {
        let mut score = 0.0;

        // Performance score
        score += device.capabilities.peak_performance_ops as f64 / 1e9;

        // Memory score
        let memory_ratio =
            data_size as f64 / (device.capabilities.memory_mb as f64 * 1024.0 * 1024.0);
        score += if memory_ratio <= 1.0 {
            1.0
        } else {
            1.0 / memory_ratio
        };

        // Power efficiency score
        let ops_per_watt = device.capabilities.peak_performance_ops as f64
            / device.capabilities.power_consumption_w;
        score += ops_per_watt / 1e9;

        // Operation-specific bonuses
        match (operation, device.accelerator_type) {
            (AcceleratorOperation::MatrixMultiply, AcceleratorType::NPU) => score += 2.0,
            (AcceleratorOperation::Convolution, AcceleratorType::VPU) => score += 2.0,
            (AcceleratorOperation::Transform, AcceleratorType::DSP) => score += 2.0,
            _ => {}
        }

        score
    }
}

#[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_accelerator_runtime_creation() {
        let runtime = AcceleratorRuntime::new();
        assert!(runtime.is_ok());
    }

    #[test]
    fn test_accelerator_type_display() {
        let types = vec![
            AcceleratorType::ASIC,
            AcceleratorType::Custom,
            AcceleratorType::DSP,
            AcceleratorType::VPU,
            AcceleratorType::NPU,
        ];

        for accel_type in types {
            println!("Accelerator type: {:?}", accel_type);
        }
    }

    #[test]
    fn test_accelerator_capabilities() {
        let caps = AcceleratorCapabilities {
            supported_operations: vec![
                AcceleratorOperation::MatrixMultiply,
                AcceleratorOperation::Convolution,
            ],
            data_types: vec![AcceleratorDataType::F32, AcceleratorDataType::F16],
            max_batch_size: 1024,
            memory_mb: 8192,
            compute_units: 64,
            peak_performance_ops: 1000000000,
            power_consumption_w: 150.0,
            precision_modes: vec![AcceleratorPrecision::High, AcceleratorPrecision::Mixed],
        };

        assert_eq!(caps.supported_operations.len(), 2);
        assert_eq!(caps.data_types.len(), 2);
        assert_eq!(caps.max_batch_size, 1024);
    }

    #[test]
    fn test_accelerator_kernel() {
        let mut params = HashMap::new();
        params.insert("alpha".to_string(), AcceleratorParameter::Float(1.0));
        params.insert("beta".to_string(), AcceleratorParameter::Float(0.0));

        let kernel = AcceleratorKernel {
            name: "test_kernel".to_string(),
            operation: AcceleratorOperation::MatrixMultiply,
            input_buffers: vec![0, 1],
            output_buffers: vec![2],
            parameters: params,
            work_size: (1024, 1024, 1),
            local_size: (16, 16, 1),
        };

        assert_eq!(kernel.name, "test_kernel");
        assert_eq!(kernel.operation, AcceleratorOperation::MatrixMultiply);
        assert_eq!(kernel.input_buffers.len(), 2);
        assert_eq!(kernel.output_buffers.len(), 1);
        assert_eq!(kernel.parameters.len(), 2);
    }

    #[test]
    fn test_accelerator_device() {
        let device = AcceleratorDevice {
            id: 0,
            name: "Test Accelerator".to_string(),
            vendor: "Test Vendor".to_string(),
            model: "Test Model".to_string(),
            accelerator_type: AcceleratorType::NPU,
            capabilities: AcceleratorCapabilities {
                supported_operations: vec![AcceleratorOperation::MatrixMultiply],
                data_types: vec![AcceleratorDataType::F32],
                max_batch_size: 512,
                memory_mb: 4096,
                compute_units: 32,
                peak_performance_ops: 500000000,
                power_consumption_w: 100.0,
                precision_modes: vec![AcceleratorPrecision::High],
            },
            driver_version: "1.0.0".to_string(),
            firmware_version: "2.0.0".to_string(),
            pci_id: Some("1234:5678".to_string()),
            numa_node: Some(0),
        };

        assert_eq!(device.id, 0);
        assert_eq!(device.accelerator_type, AcceleratorType::NPU);
        assert_eq!(device.capabilities.compute_units, 32);
    }

    #[test]
    fn test_kernel_optimization() {
        let device = AcceleratorDevice {
            id: 0,
            name: "Test NPU".to_string(),
            vendor: "Test".to_string(),
            model: "NPU-100".to_string(),
            accelerator_type: AcceleratorType::NPU,
            capabilities: AcceleratorCapabilities {
                supported_operations: vec![AcceleratorOperation::MatrixMultiply],
                data_types: vec![AcceleratorDataType::F32],
                max_batch_size: 256,
                memory_mb: 2048,
                compute_units: 16,
                peak_performance_ops: 100000000,
                power_consumption_w: 50.0,
                precision_modes: vec![AcceleratorPrecision::High],
            },
            driver_version: "1.0.0".to_string(),
            firmware_version: "1.0.0".to_string(),
            pci_id: None,
            numa_node: None,
        };

        let kernel = AcceleratorKernel {
            name: "test".to_string(),
            operation: AcceleratorOperation::MatrixMultiply,
            input_buffers: vec![0, 1],
            output_buffers: vec![2],
            parameters: HashMap::new(),
            work_size: (512, 512, 1),
            local_size: (16, 16, 1),
        };

        let optimized = optimization::optimize_kernel(&kernel, &device);
        assert!(optimized.is_ok());

        let opt_kernel = optimized.expect("operation should succeed");
        assert_eq!(opt_kernel.work_size.0, 256); // Limited by max_batch_size
    }

    #[test]
    fn test_accelerator_selection() {
        let devices = vec![
            AcceleratorDevice {
                id: 0,
                name: "NPU".to_string(),
                vendor: "Test".to_string(),
                model: "NPU-100".to_string(),
                accelerator_type: AcceleratorType::NPU,
                capabilities: AcceleratorCapabilities {
                    supported_operations: vec![AcceleratorOperation::MatrixMultiply],
                    data_types: vec![AcceleratorDataType::F32],
                    max_batch_size: 1024,
                    memory_mb: 4096,
                    compute_units: 32,
                    peak_performance_ops: 1000000000,
                    power_consumption_w: 100.0,
                    precision_modes: vec![AcceleratorPrecision::High],
                },
                driver_version: "1.0.0".to_string(),
                firmware_version: "1.0.0".to_string(),
                pci_id: None,
                numa_node: None,
            },
            AcceleratorDevice {
                id: 1,
                name: "VPU".to_string(),
                vendor: "Test".to_string(),
                model: "VPU-200".to_string(),
                accelerator_type: AcceleratorType::VPU,
                capabilities: AcceleratorCapabilities {
                    supported_operations: vec![AcceleratorOperation::Convolution],
                    data_types: vec![AcceleratorDataType::F16],
                    max_batch_size: 512,
                    memory_mb: 2048,
                    compute_units: 16,
                    peak_performance_ops: 500000000,
                    power_consumption_w: 50.0,
                    precision_modes: vec![AcceleratorPrecision::Mixed],
                },
                driver_version: "1.0.0".to_string(),
                firmware_version: "1.0.0".to_string(),
                pci_id: None,
                numa_node: None,
            },
        ];

        let selected =
            optimization::select_accelerator(AcceleratorOperation::MatrixMultiply, 512, &devices);
        assert!(selected.is_some());
        assert_eq!(selected.expect("operation should succeed").id, 0);

        let selected =
            optimization::select_accelerator(AcceleratorOperation::Convolution, 256, &devices);
        assert!(selected.is_some());
        assert_eq!(selected.expect("operation should succeed").id, 1);
    }
}