Skip to main content

torsh_backend/cpu/
optimizations.rs

1//! Advanced CPU backend optimizations
2
3use std::collections::HashMap;
4use std::sync::{
5    atomic::{AtomicUsize, Ordering},
6    Arc, Mutex,
7};
8use std::thread;
9use std::time::{Duration, Instant};
10use torsh_core::sync::MutexExt;
11
12use crate::cpu::error::CpuResult;
13
14// SciRS2 POLICY: Use scirs2_parallel for parallel operations (wraps rayon for now)
15// This provides a unified API that will be migrated to scirs2-core in the future
16#[cfg(feature = "cpu")]
17use crate::cpu::scirs2_parallel::prelude::*;
18
19/// Kernel fusion optimizer for combining multiple operations
20pub struct KernelFusionOptimizer {
21    /// Cache of fused kernels
22    fused_kernels: Arc<Mutex<HashMap<String, Box<dyn FusedKernel + Send + Sync>>>>,
23    /// Enable/disable fusion
24    enabled: bool,
25}
26
27impl Default for KernelFusionOptimizer {
28    fn default() -> Self {
29        Self::new()
30    }
31}
32
33impl KernelFusionOptimizer {
34    /// Create new kernel fusion optimizer
35    pub fn new() -> Self {
36        Self {
37            fused_kernels: Arc::new(Mutex::new(HashMap::new())),
38            enabled: true,
39        }
40    }
41
42    /// Enable or disable kernel fusion
43    pub fn set_enabled(&mut self, enabled: bool) {
44        self.enabled = enabled;
45    }
46
47    /// Check if fusion is enabled
48    pub fn is_enabled(&self) -> bool {
49        self.enabled
50    }
51
52    /// Register a fused kernel
53    pub fn register_fused_kernel(&self, name: String, kernel: Box<dyn FusedKernel + Send + Sync>) {
54        let mut kernels = self.fused_kernels.lock_or_recover();
55        kernels.insert(name, kernel);
56    }
57
58    /// Execute fused operation if available
59    pub fn try_execute_fused(
60        &self,
61        operation_sequence: &[&str],
62        inputs: &[&[f32]],
63        outputs: &mut [&mut [f32]],
64    ) -> CpuResult<bool> {
65        if !self.enabled {
66            return Ok(false);
67        }
68
69        let fusion_key = operation_sequence.join("->");
70        let kernels = self.fused_kernels.lock_or_recover();
71
72        if let Some(kernel) = kernels.get(&fusion_key) {
73            kernel.execute(inputs, outputs)?;
74            Ok(true)
75        } else {
76            Ok(false)
77        }
78    }
79
80    /// Common fused operations
81    #[allow(clippy::too_many_arguments)]
82    pub fn conv_relu_fusion(
83        &self,
84        input: &[f32],
85        weight: &[f32],
86        bias: Option<&[f32]>,
87        output: &mut [f32],
88        input_shape: (usize, usize, usize, usize), // (N, C, H, W)
89        kernel_shape: (usize, usize, usize, usize), // (K, C, H, W)
90        stride: (usize, usize),
91        padding: (usize, usize),
92    ) -> CpuResult<()> {
93        // Fused convolution + ReLU operation
94        let (n, c, h, w) = input_shape;
95        let (k, _, kh, kw) = kernel_shape;
96        let (sh, sw) = stride;
97        let (ph, pw) = padding;
98
99        let out_h = (h + 2 * ph - kh) / sh + 1;
100        let out_w = (w + 2 * pw - kw) / sw + 1;
101
102        // Parallel processing over output channels and batch
103        output
104            .par_chunks_mut(out_h * out_w)
105            .enumerate()
106            .for_each(|(out_idx, out_slice)| {
107                let batch_idx = out_idx / k;
108                let channel_idx = out_idx % k;
109
110                if batch_idx >= n {
111                    return;
112                }
113
114                // Perform convolution for this output channel
115                for oh in 0..out_h {
116                    for ow in 0..out_w {
117                        let mut sum = 0.0f32;
118
119                        // Convolve with kernel
120                        for ic in 0..c {
121                            for kh_idx in 0..kh {
122                                for kw_idx in 0..kw {
123                                    let ih = oh * sh + kh_idx;
124                                    let iw = ow * sw + kw_idx;
125
126                                    if ih >= ph && ih < h + ph && iw >= pw && iw < w + pw {
127                                        let input_h = ih - ph;
128                                        let input_w = iw - pw;
129
130                                        if input_h < h && input_w < w {
131                                            let input_idx = batch_idx * c * h * w
132                                                + ic * h * w
133                                                + input_h * w
134                                                + input_w;
135
136                                            let weight_idx = channel_idx * c * kh * kw
137                                                + ic * kh * kw
138                                                + kh_idx * kw
139                                                + kw_idx;
140
141                                            sum += input[input_idx] * weight[weight_idx];
142                                        }
143                                    }
144                                }
145                            }
146                        }
147
148                        // Add bias if provided
149                        if let Some(bias_data) = bias {
150                            sum += bias_data[channel_idx];
151                        }
152
153                        // Apply ReLU activation (fusion)
154                        let out_idx = oh * out_w + ow;
155                        out_slice[out_idx] = sum.max(0.0);
156                    }
157                }
158            });
159
160        Ok(())
161    }
162
163    /// Linear + activation fusion
164    #[allow(clippy::too_many_arguments)]
165    pub fn linear_activation_fusion(
166        &self,
167        input: &[f32],
168        weight: &[f32],
169        bias: Option<&[f32]>,
170        output: &mut [f32],
171        input_shape: (usize, usize),  // (batch_size, input_dim)
172        weight_shape: (usize, usize), // (output_dim, input_dim)
173        activation: ActivationType,
174    ) -> CpuResult<()> {
175        let (batch_size, input_dim) = input_shape;
176        let (output_dim, _) = weight_shape;
177
178        // Parallel processing over batch
179        output
180            .par_chunks_mut(output_dim)
181            .enumerate()
182            .for_each(|(batch_idx, batch_output)| {
183                if batch_idx >= batch_size {
184                    return;
185                }
186
187                // Compute linear transformation
188                for out_idx in 0..output_dim {
189                    let mut sum = 0.0f32;
190
191                    // Matrix multiplication
192                    for in_idx in 0..input_dim {
193                        let input_val = input[batch_idx * input_dim + in_idx];
194                        let weight_val = weight[out_idx * input_dim + in_idx];
195                        sum += input_val * weight_val;
196                    }
197
198                    // Add bias if provided
199                    if let Some(bias_data) = bias {
200                        sum += bias_data[out_idx];
201                    }
202
203                    // Apply activation
204                    batch_output[out_idx] = match activation {
205                        ActivationType::ReLU => sum.max(0.0),
206                        ActivationType::Sigmoid => 1.0 / (1.0 + (-sum).exp()),
207                        ActivationType::Tanh => sum.tanh(),
208                        ActivationType::GELU => {
209                            sum * 0.5
210                                * (1.0 + (sum * std::f32::consts::FRAC_2_SQRT_PI * 0.5).tanh())
211                        }
212                        ActivationType::None => sum,
213                    };
214                }
215            });
216
217        Ok(())
218    }
219}
220
221/// Trait for fused kernels
222pub trait FusedKernel {
223    fn execute(&self, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) -> CpuResult<()>;
224}
225
226/// Activation types for fusion
227#[derive(Debug, Clone, Copy)]
228pub enum ActivationType {
229    None,
230    ReLU,
231    Sigmoid,
232    Tanh,
233    GELU,
234}
235
236/// Memory optimization manager
237pub struct MemoryOptimizer {
238    /// Memory pool for reusing buffers
239    memory_pool: Arc<Mutex<HashMap<usize, Vec<Vec<f32>>>>>,
240    /// Enable memory pooling
241    pooling_enabled: bool,
242    /// Memory usage statistics
243    stats: Arc<Mutex<MemoryStats>>,
244}
245
246#[derive(Debug, Default)]
247pub struct MemoryStats {
248    pub total_allocated: usize,
249    pub pool_hits: usize,
250    pub pool_misses: usize,
251    pub peak_usage: usize,
252}
253
254impl Default for MemoryOptimizer {
255    fn default() -> Self {
256        Self::new()
257    }
258}
259
260impl MemoryOptimizer {
261    /// Create new memory optimizer
262    pub fn new() -> Self {
263        Self {
264            memory_pool: Arc::new(Mutex::new(HashMap::new())),
265            pooling_enabled: true,
266            stats: Arc::new(Mutex::new(MemoryStats::default())),
267        }
268    }
269
270    /// Enable or disable memory pooling
271    pub fn set_pooling_enabled(&mut self, enabled: bool) {
272        self.pooling_enabled = enabled;
273    }
274
275    /// Get buffer from pool or allocate new one
276    pub fn get_buffer(&self, size: usize) -> Vec<f32> {
277        if !self.pooling_enabled {
278            return vec![0.0; size];
279        }
280
281        let mut pool = self.memory_pool.lock_or_recover();
282        let mut stats = self.stats.lock_or_recover();
283
284        if let Some(buffers) = pool.get_mut(&size) {
285            if let Some(buffer) = buffers.pop() {
286                stats.pool_hits += 1;
287                return buffer;
288            }
289        }
290
291        stats.pool_misses += 1;
292        stats.total_allocated += size * std::mem::size_of::<f32>();
293        stats.peak_usage = stats.peak_usage.max(stats.total_allocated);
294
295        vec![0.0; size]
296    }
297
298    /// Return buffer to pool
299    pub fn return_buffer(&self, mut buffer: Vec<f32>) {
300        if !self.pooling_enabled {
301            return;
302        }
303
304        let size = buffer.len();
305        buffer.fill(0.0); // Clear for reuse
306
307        let mut pool = self.memory_pool.lock_or_recover();
308        pool.entry(size).or_default().push(buffer);
309    }
310
311    /// Get memory statistics
312    pub fn get_stats(&self) -> MemoryStats {
313        let stats = self.stats.lock_or_recover();
314        MemoryStats {
315            total_allocated: stats.total_allocated,
316            pool_hits: stats.pool_hits,
317            pool_misses: stats.pool_misses,
318            peak_usage: stats.peak_usage,
319        }
320    }
321
322    /// Clear memory pool
323    pub fn clear_pool(&self) {
324        let mut pool = self.memory_pool.lock_or_recover();
325        pool.clear();
326
327        let mut stats = self.stats.lock_or_recover();
328        stats.total_allocated = 0;
329    }
330}
331
332/// Cache line size for memory optimization (typically 64 bytes)
333const CACHE_LINE_SIZE: usize = 64;
334
335/// Work stealing statistics for thread pool optimization
336#[derive(Debug, Default)]
337pub struct WorkStealingStats {
338    pub tasks_executed: AtomicUsize,
339    pub tasks_stolen: AtomicUsize,
340    pub idle_time_ns: AtomicUsize,
341    pub work_time_ns: AtomicUsize,
342}
343
344impl WorkStealingStats {
345    pub fn new() -> Self {
346        Self::default()
347    }
348
349    pub fn record_task_executed(&self) {
350        self.tasks_executed.fetch_add(1, Ordering::Relaxed);
351    }
352
353    pub fn record_task_stolen(&self) {
354        self.tasks_stolen.fetch_add(1, Ordering::Relaxed);
355    }
356
357    pub fn record_work_time(&self, duration: Duration) {
358        self.work_time_ns
359            .fetch_add(duration.as_nanos() as usize, Ordering::Relaxed);
360    }
361
362    pub fn record_idle_time(&self, duration: Duration) {
363        self.idle_time_ns
364            .fetch_add(duration.as_nanos() as usize, Ordering::Relaxed);
365    }
366
367    pub fn get_steal_ratio(&self) -> f64 {
368        let executed = self.tasks_executed.load(Ordering::Relaxed);
369        let stolen = self.tasks_stolen.load(Ordering::Relaxed);
370        if executed > 0 {
371            stolen as f64 / executed as f64
372        } else {
373            0.0
374        }
375    }
376
377    pub fn get_efficiency(&self) -> f64 {
378        let work_time = self.work_time_ns.load(Ordering::Relaxed);
379        let idle_time = self.idle_time_ns.load(Ordering::Relaxed);
380        let total_time = work_time + idle_time;
381        if total_time > 0 {
382            work_time as f64 / total_time as f64
383        } else {
384            0.0
385        }
386    }
387}
388
389/// Thread pool optimizer for better parallelization
390pub struct ThreadPoolOptimizer {
391    /// Number of threads to use
392    num_threads: usize,
393    /// Thread affinity settings
394    affinity_enabled: bool,
395    /// Cache size per core (in bytes)
396    l1_cache_size: usize,
397    l2_cache_size: usize,
398    l3_cache_size: usize,
399    /// Work stealing metrics
400    work_stealing_stats: Arc<WorkStealingStats>,
401    /// Custom thread pool for advanced scheduling
402    custom_pool: Option<rayon::ThreadPool>,
403}
404
405impl Default for ThreadPoolOptimizer {
406    fn default() -> Self {
407        Self::new()
408    }
409}
410
411impl ThreadPoolOptimizer {
412    /// Create new thread pool optimizer
413    pub fn new() -> Self {
414        let num_threads = thread::available_parallelism()
415            .map(|n| n.get())
416            .unwrap_or(4);
417
418        // Detect cache sizes (simplified detection, could be enhanced with CPUID)
419        let (l1_cache, l2_cache, l3_cache) = Self::detect_cache_sizes();
420
421        Self {
422            num_threads,
423            affinity_enabled: false,
424            l1_cache_size: l1_cache,
425            l2_cache_size: l2_cache,
426            l3_cache_size: l3_cache,
427            work_stealing_stats: Arc::new(WorkStealingStats::new()),
428            custom_pool: None,
429        }
430    }
431
432    /// Detect CPU cache sizes (simplified implementation)
433    fn detect_cache_sizes() -> (usize, usize, usize) {
434        // Default values for common x86_64 architectures
435        // In a real implementation, we would use CPUID or system files
436        #[cfg(target_arch = "x86_64")]
437        {
438            (32 * 1024, 256 * 1024, 8 * 1024 * 1024) // 32KB L1, 256KB L2, 8MB L3
439        }
440        #[cfg(target_arch = "aarch64")]
441        {
442            (64 * 1024, 512 * 1024, 4 * 1024 * 1024) // Apple Silicon typical values
443        }
444        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
445        {
446            (32 * 1024, 256 * 1024, 2 * 1024 * 1024) // Conservative defaults
447        }
448    }
449
450    /// Set number of threads
451    pub fn set_num_threads(&mut self, num_threads: usize) {
452        self.num_threads = num_threads;
453
454        // Create custom thread pool with enhanced settings
455        let builder = rayon::ThreadPoolBuilder::new()
456            .num_threads(num_threads)
457            .stack_size(2 * 1024 * 1024) // 2MB stack for deep recursions
458            .thread_name(|index| format!("torsh-cpu-{}", index))
459            .panic_handler(|_| {
460                eprintln!("Thread panic in torsh CPU backend");
461            });
462
463        match builder.build() {
464            Ok(pool) => {
465                self.custom_pool = Some(pool);
466            }
467            Err(_) => {
468                // Fallback to global pool update
469                rayon::ThreadPoolBuilder::new()
470                    .num_threads(num_threads)
471                    .build_global()
472                    .ok();
473            }
474        }
475    }
476
477    /// Get number of threads
478    pub fn get_num_threads(&self) -> usize {
479        self.num_threads
480    }
481
482    /// Enable thread affinity
483    pub fn set_affinity_enabled(&mut self, enabled: bool) {
484        self.affinity_enabled = enabled;
485    }
486
487    /// Get cache-aware chunk size for optimal memory access patterns
488    pub fn get_cache_aware_chunk_size(&self, total_size: usize, element_size: usize) -> usize {
489        // Calculate optimal chunk size based on L1 cache
490        let l1_elements = self.l1_cache_size / element_size;
491        let cache_friendly_chunk = l1_elements / 2; // Leave room for other data
492
493        // Balance between cache efficiency and parallelism
494        let parallel_chunk = total_size / self.num_threads;
495        let min_chunk = 64; // Minimum to avoid overhead
496
497        // Choose the size that provides good cache locality while maintaining parallelism
498        if cache_friendly_chunk < min_chunk {
499            min_chunk
500        } else if parallel_chunk < cache_friendly_chunk {
501            parallel_chunk.max(min_chunk)
502        } else {
503            cache_friendly_chunk
504        }
505    }
506
507    /// Get optimal chunk size for parallel operations (legacy method)
508    pub fn get_optimal_chunk_size(&self, total_size: usize, min_chunk_size: usize) -> usize {
509        self.get_cache_aware_chunk_size(total_size, 4)
510            .max(min_chunk_size)
511    }
512
513    /// Calculate optimal block size for matrix operations
514    pub fn get_matrix_block_size(&self, _matrix_elements: usize, element_size: usize) -> usize {
515        // For square matrices, find block size that fits in L2 cache
516        let l2_elements = self.l2_cache_size / element_size;
517        let sqrt_elements = (l2_elements as f64).sqrt() as usize;
518
519        // Ensure block size is a power of 2 for better alignment
520        let mut block_size = 1;
521        while block_size < sqrt_elements {
522            block_size *= 2;
523        }
524        block_size / 2 // Back off one level for safety
525    }
526
527    /// Get cache line aligned size
528    pub fn get_cache_aligned_size(&self, size: usize) -> usize {
529        ((size + CACHE_LINE_SIZE - 1) / CACHE_LINE_SIZE) * CACHE_LINE_SIZE
530    }
531
532    /// Execute parallel operation with optimal chunking
533    pub fn parallel_for<F>(&self, range: std::ops::Range<usize>, op: F)
534    where
535        F: Fn(usize) + Send + Sync,
536    {
537        let chunk_size = self.get_optimal_chunk_size(range.len(), 1);
538
539        if let Some(pool) = &self.custom_pool {
540            pool.install(|| {
541                range.into_par_iter().with_min_len(chunk_size).for_each(op);
542            });
543        } else {
544            range.into_par_iter().with_min_len(chunk_size).for_each(op);
545        }
546    }
547
548    /// Execute cache-aware parallel operation with memory locality optimization
549    pub fn parallel_for_cache_aware<F>(
550        &self,
551        range: std::ops::Range<usize>,
552        element_size: usize,
553        op: F,
554    ) where
555        F: Fn(usize) + Send + Sync,
556    {
557        let chunk_size = self.get_cache_aware_chunk_size(range.len(), element_size);
558        let stats = Arc::clone(&self.work_stealing_stats);
559
560        let timed_op = move |idx: usize| {
561            let start = Instant::now();
562            stats.record_task_executed();
563            op(idx);
564            stats.record_work_time(start.elapsed());
565        };
566
567        if let Some(pool) = &self.custom_pool {
568            pool.install(|| {
569                range
570                    .into_par_iter()
571                    .with_min_len(chunk_size)
572                    .for_each(timed_op);
573            });
574        } else {
575            range
576                .into_par_iter()
577                .with_min_len(chunk_size)
578                .for_each(timed_op);
579        }
580    }
581
582    /// Execute parallel map operation with cache-aware chunking
583    pub fn parallel_map<T, R, F>(&self, data: &[T], op: F) -> Vec<R>
584    where
585        T: Sync,
586        R: Send,
587        F: Fn(&T) -> R + Send + Sync,
588    {
589        let chunk_size = self.get_optimal_chunk_size(data.len(), 1);
590
591        if let Some(pool) = &self.custom_pool {
592            pool.install(|| data.par_iter().with_min_len(chunk_size).map(op).collect())
593        } else {
594            data.par_iter().with_min_len(chunk_size).map(op).collect()
595        }
596    }
597
598    /// Cache-aware parallel matrix multiplication block processing
599    pub fn parallel_matrix_blocks<F>(&self, rows: usize, cols: usize, element_size: usize, op: F)
600    where
601        F: Fn(usize, usize, usize, usize) + Send + Sync, // (row_start, row_end, col_start, col_end)
602    {
603        let block_size = self.get_matrix_block_size(rows * cols, element_size);
604
605        let row_blocks = (rows + block_size - 1) / block_size;
606        let col_blocks = (cols + block_size - 1) / block_size;
607
608        (0..row_blocks).into_par_iter().for_each(|row_block| {
609            (0..col_blocks).into_par_iter().for_each(|col_block| {
610                let row_start = row_block * block_size;
611                let row_end = ((row_block + 1) * block_size).min(rows);
612                let col_start = col_block * block_size;
613                let col_end = ((col_block + 1) * block_size).min(cols);
614
615                op(row_start, row_end, col_start, col_end);
616            });
617        });
618    }
619
620    /// Parallel reduction with work stealing optimization
621    pub fn parallel_reduce<T, F, R, C>(&self, data: &[T], identity: R, map_op: F, reduce_op: C) -> R
622    where
623        T: Sync,
624        R: Send + Clone + Sync,
625        F: Fn(R, &T) -> R + Send + Sync,
626        C: Fn(R, R) -> R + Send + Sync,
627    {
628        let chunk_size = self.get_cache_aware_chunk_size(data.len(), std::mem::size_of::<T>());
629
630        if let Some(pool) = &self.custom_pool {
631            pool.install(|| {
632                data.par_chunks(chunk_size)
633                    .map(|chunk| chunk.iter().fold(identity.clone(), &map_op))
634                    .reduce(|| identity.clone(), &reduce_op)
635            })
636        } else {
637            data.par_chunks(chunk_size)
638                .map(|chunk| chunk.iter().fold(identity.clone(), &map_op))
639                .reduce(|| identity.clone(), &reduce_op)
640        }
641    }
642
643    /// Get work stealing statistics
644    pub fn get_work_stealing_stats(&self) -> (f64, f64) {
645        (
646            self.work_stealing_stats.get_steal_ratio(),
647            self.work_stealing_stats.get_efficiency(),
648        )
649    }
650
651    /// Reset work stealing statistics
652    pub fn reset_stats(&self) {
653        let stats = &self.work_stealing_stats;
654        stats.tasks_executed.store(0, Ordering::Relaxed);
655        stats.tasks_stolen.store(0, Ordering::Relaxed);
656        stats.work_time_ns.store(0, Ordering::Relaxed);
657        stats.idle_time_ns.store(0, Ordering::Relaxed);
658    }
659
660    /// Get cache information
661    pub fn get_cache_info(&self) -> (usize, usize, usize) {
662        (self.l1_cache_size, self.l2_cache_size, self.l3_cache_size)
663    }
664}
665
666/// Combined optimization manager
667pub struct OptimizationManager {
668    /// Kernel fusion optimizer
669    pub kernel_fusion: KernelFusionOptimizer,
670    /// Memory optimizer
671    pub memory: MemoryOptimizer,
672    /// Thread pool optimizer
673    pub thread_pool: ThreadPoolOptimizer,
674    /// Global optimization settings
675    optimization_level: OptimizationLevel,
676}
677
678#[derive(Debug, Clone, Copy)]
679pub enum OptimizationLevel {
680    None,
681    Basic,
682    Balanced,
683    Aggressive,
684}
685
686impl OptimizationManager {
687    /// Create new optimization manager
688    pub fn new(level: OptimizationLevel) -> Self {
689        let mut manager = Self {
690            kernel_fusion: KernelFusionOptimizer::new(),
691            memory: MemoryOptimizer::new(),
692            thread_pool: ThreadPoolOptimizer::new(),
693            optimization_level: level,
694        };
695
696        // Configure based on optimization level
697        match level {
698            OptimizationLevel::None => {
699                manager.kernel_fusion.set_enabled(false);
700                manager.memory.set_pooling_enabled(false);
701            }
702            OptimizationLevel::Basic => {
703                manager.kernel_fusion.set_enabled(true);
704                manager.memory.set_pooling_enabled(true);
705            }
706            OptimizationLevel::Balanced => {
707                manager.kernel_fusion.set_enabled(true);
708                manager.memory.set_pooling_enabled(true);
709                // Moderate thread pool optimizations
710            }
711            OptimizationLevel::Aggressive => {
712                manager.kernel_fusion.set_enabled(true);
713                manager.memory.set_pooling_enabled(true);
714                manager.thread_pool.set_affinity_enabled(true);
715
716                // Use more threads for aggressive optimization
717                let max_threads = thread::available_parallelism()
718                    .map(|n| n.get())
719                    .unwrap_or(4);
720                manager.thread_pool.set_num_threads(max_threads);
721            }
722        }
723
724        manager
725    }
726
727    /// Get optimization level
728    pub fn get_optimization_level(&self) -> OptimizationLevel {
729        self.optimization_level
730    }
731
732    /// Set optimization level
733    pub fn set_optimization_level(&mut self, level: OptimizationLevel) {
734        self.optimization_level = level;
735
736        // Reconfigure optimizers
737        match level {
738            OptimizationLevel::None => {
739                self.kernel_fusion.set_enabled(false);
740                self.memory.set_pooling_enabled(false);
741            }
742            OptimizationLevel::Basic => {
743                self.kernel_fusion.set_enabled(true);
744                self.memory.set_pooling_enabled(true);
745            }
746            OptimizationLevel::Balanced => {
747                self.kernel_fusion.set_enabled(true);
748                self.memory.set_pooling_enabled(true);
749                // Moderate thread pool optimizations
750            }
751            OptimizationLevel::Aggressive => {
752                self.kernel_fusion.set_enabled(true);
753                self.memory.set_pooling_enabled(true);
754                self.thread_pool.set_affinity_enabled(true);
755            }
756        }
757    }
758
759    /// Print optimization statistics
760    pub fn print_stats(&self) {
761        let mem_stats = self.memory.get_stats();
762        let (steal_ratio, efficiency) = self.thread_pool.get_work_stealing_stats();
763        let (l1, l2, l3) = self.thread_pool.get_cache_info();
764
765        println!("Optimization Statistics:");
766        println!("  Memory Pool Hits: {}", mem_stats.pool_hits);
767        println!("  Memory Pool Misses: {}", mem_stats.pool_misses);
768        println!("  Total Allocated: {} bytes", mem_stats.total_allocated);
769        println!("  Peak Usage: {} bytes", mem_stats.peak_usage);
770        println!("  Threads: {}", self.thread_pool.get_num_threads());
771        println!("  Kernel Fusion: {}", self.kernel_fusion.is_enabled());
772        println!("  Work Steal Ratio: {:.2}%", steal_ratio * 100.0);
773        println!("  Thread Efficiency: {:.2}%", efficiency * 100.0);
774        println!(
775            "  Cache Sizes: L1={} KB, L2={} KB, L3={} KB",
776            l1 / 1024,
777            l2 / 1024,
778            l3 / 1024
779        );
780    }
781}
782
783impl Default for OptimizationManager {
784    fn default() -> Self {
785        Self::new(OptimizationLevel::Basic)
786    }
787}
788
789#[cfg(test)]
790mod tests {
791    use super::*;
792
793    #[test]
794    fn test_kernel_fusion_optimizer() {
795        let optimizer = KernelFusionOptimizer::new();
796        assert!(optimizer.is_enabled());
797    }
798
799    #[test]
800    fn test_memory_optimizer() {
801        let optimizer = MemoryOptimizer::new();
802
803        // Test buffer allocation and return
804        let buffer = optimizer.get_buffer(1024);
805        assert_eq!(buffer.len(), 1024);
806
807        optimizer.return_buffer(buffer);
808
809        // Test pool hit
810        let buffer2 = optimizer.get_buffer(1024);
811        assert_eq!(buffer2.len(), 1024);
812
813        let stats = optimizer.get_stats();
814        assert!(stats.pool_hits > 0 || stats.pool_misses > 0);
815    }
816
817    #[test]
818    fn test_thread_pool_optimizer() {
819        let optimizer = ThreadPoolOptimizer::new();
820        assert!(optimizer.get_num_threads() > 0);
821
822        let chunk_size = optimizer.get_optimal_chunk_size(1000, 10);
823        assert!(chunk_size >= 10);
824
825        // Test cache-aware chunk size
826        let cache_chunk = optimizer.get_cache_aware_chunk_size(1000, 4);
827        assert!(cache_chunk > 0);
828
829        // Test matrix block size
830        let block_size = optimizer.get_matrix_block_size(1000, 4);
831        assert!(block_size > 0);
832        assert!(block_size.is_power_of_two());
833
834        // Test cache alignment
835        let aligned_size = optimizer.get_cache_aligned_size(100);
836        assert_eq!(aligned_size % CACHE_LINE_SIZE, 0);
837
838        // Test cache info
839        let (l1, l2, l3) = optimizer.get_cache_info();
840        assert!(l1 > 0);
841        assert!(l2 > l1);
842        assert!(l3 > l2);
843    }
844
845    #[test]
846    fn test_optimization_manager() {
847        let manager = OptimizationManager::new(OptimizationLevel::Basic);
848        assert!(manager.kernel_fusion.is_enabled());
849        assert!(manager.memory.pooling_enabled);
850    }
851
852    #[test]
853    fn test_conv_relu_fusion() {
854        let optimizer = KernelFusionOptimizer::new();
855
856        // Simple test case
857        let input = vec![1.0, 2.0, 3.0, 4.0]; // 1x1x2x2
858        let weight = vec![0.5, 0.5, 0.5, 0.5]; // 1x1x2x2
859        let mut output = vec![0.0; 1]; // 1x1x1x1
860
861        let result = optimizer.conv_relu_fusion(
862            &input,
863            &weight,
864            None,
865            &mut output,
866            (1, 1, 2, 2), // input shape
867            (1, 1, 2, 2), // kernel shape
868            (1, 1),       // stride
869            (0, 0),       // padding
870        );
871
872        assert!(result.is_ok());
873        assert!(output[0] > 0.0); // ReLU should have activated
874    }
875
876    #[test]
877    fn test_linear_activation_fusion() {
878        let optimizer = KernelFusionOptimizer::new();
879
880        let input = vec![1.0, 2.0]; // batch_size=1, input_dim=2
881        let weight = vec![0.5, 0.5]; // output_dim=1, input_dim=2
882        let bias = vec![0.1];
883        let mut output = vec![0.0]; // batch_size=1, output_dim=1
884
885        let result = optimizer.linear_activation_fusion(
886            &input,
887            &weight,
888            Some(&bias),
889            &mut output,
890            (1, 2), // input shape
891            (1, 2), // weight shape
892            ActivationType::ReLU,
893        );
894
895        assert!(result.is_ok());
896        assert!(output[0] > 0.0); // Should be 1.0*0.5 + 2.0*0.5 + 0.1 = 1.6
897    }
898
899    #[test]
900    fn test_work_stealing_stats() {
901        let stats = WorkStealingStats::new();
902
903        // Record some metrics
904        stats.record_task_executed();
905        stats.record_task_stolen();
906        stats.record_work_time(Duration::from_millis(10));
907        stats.record_idle_time(Duration::from_millis(2));
908
909        assert!(stats.get_steal_ratio() > 0.0);
910        assert!(stats.get_efficiency() > 0.0);
911    }
912
913    #[test]
914    fn test_cache_aware_parallel_operations() {
915        let optimizer = ThreadPoolOptimizer::new();
916
917        // Test parallel_for_cache_aware
918        let data = vec![0; 1000];
919        let counter = Arc::new(AtomicUsize::new(0));
920        let counter_clone = Arc::clone(&counter);
921
922        optimizer.parallel_for_cache_aware(0..data.len(), 4, move |_| {
923            counter_clone.fetch_add(1, Ordering::Relaxed);
924        });
925
926        assert_eq!(counter.load(Ordering::Relaxed), data.len());
927
928        // Test parallel_reduce
929        let data: Vec<i32> = (0..1000).collect();
930        let sum = optimizer.parallel_reduce(&data, 0i32, |acc, &val| acc + val, |a, b| a + b);
931
932        let expected_sum: i32 = (0..1000).sum();
933        assert_eq!(sum, expected_sum);
934    }
935
936    #[test]
937    fn test_parallel_matrix_blocks() {
938        let optimizer = ThreadPoolOptimizer::new();
939        let counter = Arc::new(AtomicUsize::new(0));
940        let counter_clone = Arc::clone(&counter);
941
942        optimizer.parallel_matrix_blocks(100, 100, 4, move |_r1, _r2, _c1, _c2| {
943            counter_clone.fetch_add(1, Ordering::Relaxed);
944        });
945
946        assert!(counter.load(Ordering::Relaxed) > 0);
947    }
948}