Skip to main content

trustformers_mobile/optimization/
cache_optimizer.rs

1//! Cache Optimization Module
2//!
3//! Optimizes memory access patterns and data layouts for mobile cache hierarchies
4
5use super::{ComputationGraph, GraphOperator, KernelType};
6use crate::MobilePlatform;
7use std::collections::HashMap;
8use trustformers_core::errors::Result;
9use trustformers_core::Tensor;
10use trustformers_core::TrustformersError;
11
12/// Cache optimization strategy
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum CacheStrategy {
15    /// Optimize for L1 cache
16    L1Optimized,
17    /// Optimize for L2 cache
18    L2Optimized,
19    /// Streaming (bypass cache)
20    Streaming,
21    /// Prefetch-heavy
22    Prefetch,
23}
24
25/// Loop tiling configuration
26#[derive(Debug, Clone)]
27pub struct TilingConfig {
28    /// Tile dimensions
29    pub tile_sizes: Vec<usize>,
30    /// Nested loop order
31    pub loop_order: Vec<usize>,
32    /// Unroll factors
33    pub unroll_factors: Vec<usize>,
34}
35
36/// Data layout for cache efficiency
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum DataLayout {
39    /// NCHW - batch, channels, height, width
40    NCHW,
41    /// NHWC - batch, height, width, channels
42    NHWC,
43    /// NC4HW4 - packed format for SIMD
44    NC4HW4,
45    /// Custom layout
46    Custom,
47}
48
49/// Memory access pattern analysis
50#[derive(Debug, Clone)]
51pub struct AccessPattern {
52    /// Stride pattern
53    pub strides: Vec<isize>,
54    /// Access order (sequential, strided, random)
55    pub access_type: AccessType,
56    /// Reuse distance
57    pub reuse_distance: usize,
58    /// Working set size
59    pub working_set_size: usize,
60}
61
62/// Access type classification
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum AccessType {
65    Sequential,
66    Strided,
67    Random,
68    Broadcast,
69}
70
71/// Cache hints for operators
72#[derive(Debug, Clone)]
73pub struct CacheHints {
74    /// Prefetch distance
75    pub prefetch_distance: usize,
76    /// Cache bypass for certain tensors
77    pub bypass_cache: Vec<String>,
78    /// Temporal locality hints
79    pub temporal_hints: HashMap<String, TemporalHint>,
80    /// Spatial locality hints
81    pub spatial_hints: HashMap<String, SpatialHint>,
82}
83
84/// Temporal locality hint
85#[derive(Debug, Clone, Copy)]
86pub enum TemporalHint {
87    /// High reuse - keep in cache
88    HighReuse,
89    /// Medium reuse
90    MediumReuse,
91    /// Low reuse - consider streaming
92    LowReuse,
93    /// No reuse - bypass cache
94    NoReuse,
95}
96
97/// Spatial locality hint
98#[derive(Debug, Clone, Copy)]
99pub enum SpatialHint {
100    /// Contiguous access
101    Contiguous,
102    /// Strided access
103    Strided { stride: usize },
104    /// Blocked access
105    Blocked { block_size: usize },
106}
107
108/// Cache optimizer
109pub struct CacheOptimizer {
110    platform: MobilePlatform,
111    cache_hierarchy: CacheHierarchy,
112    optimization_cache: HashMap<String, CacheStrategy>,
113}
114
115/// Cache hierarchy description
116#[derive(Debug, Clone)]
117struct CacheHierarchy {
118    l1_size: usize,
119    l1_line_size: usize,
120    l1_associativity: usize,
121    l2_size: usize,
122    l2_line_size: usize,
123    l2_associativity: usize,
124    l3_size: Option<usize>,
125}
126
127impl CacheOptimizer {
128    /// Create new cache optimizer
129    pub fn new(platform: MobilePlatform) -> Self {
130        let cache_hierarchy = Self::detect_cache_hierarchy(&platform);
131
132        Self {
133            platform,
134            cache_hierarchy,
135            optimization_cache: HashMap::new(),
136        }
137    }
138
139    /// Optimize tensor layout for cache efficiency
140    pub fn optimize_layout(&self, tensor: &Tensor, pattern: &AccessPattern) -> Result<Tensor> {
141        let layout = self.select_optimal_layout(&tensor.shape(), pattern)?;
142
143        match layout {
144            DataLayout::NHWC if self.current_layout_is_nchw(tensor) => {
145                self.transpose_nchw_to_nhwc(tensor)
146            },
147            DataLayout::NC4HW4 => self.pack_to_nc4hw4(tensor),
148            _ => Ok(tensor.clone()),
149        }
150    }
151
152    /// Generate cache hints for kernel
153    pub fn generate_hints(
154        &self,
155        kernel: &KernelType,
156        input_shapes: &[Vec<usize>],
157    ) -> Result<CacheHints> {
158        let prefetch_distance = self.calculate_prefetch_distance(kernel, input_shapes)?;
159        let bypass_cache = self.identify_streaming_tensors(kernel, input_shapes)?;
160        let temporal_hints = self.analyze_temporal_locality(kernel, input_shapes)?;
161        let spatial_hints = self.analyze_spatial_locality(kernel, input_shapes)?;
162
163        Ok(CacheHints {
164            prefetch_distance,
165            bypass_cache,
166            temporal_hints,
167            spatial_hints,
168        })
169    }
170
171    /// Apply loop tiling optimization
172    pub fn apply_tiling(&self, graph: &mut ComputationGraph) -> Result<()> {
173        for operator in &mut graph.operators {
174            if self.can_tile(&operator.kernel) {
175                let tiling_config = self.compute_tiling_config(operator)?;
176
177                // Store tiling configuration in operator metadata
178                if let Some(ref mut hints) = operator.cache_hints {
179                    // Apply tiling configuration
180                    self.apply_tiling_to_operator(operator, &tiling_config)?;
181                }
182            }
183        }
184
185        Ok(())
186    }
187
188    /// Analyze access pattern for tensor
189    pub fn analyze(&self, tensor_name: &str, kernel: &KernelType) -> Result<AccessPattern> {
190        let access_type = match kernel {
191            KernelType::Conv2d => AccessType::Strided,
192            KernelType::Linear => AccessType::Sequential,
193            KernelType::Attention => AccessType::Random,
194            _ => AccessType::Sequential,
195        };
196
197        let pattern = AccessPattern {
198            strides: self.compute_strides(kernel)?,
199            access_type,
200            reuse_distance: self.estimate_reuse_distance(kernel)?,
201            working_set_size: self.estimate_working_set(kernel)?,
202        };
203
204        Ok(pattern)
205    }
206
207    // Private helper methods
208
209    fn detect_cache_hierarchy(platform: &MobilePlatform) -> CacheHierarchy {
210        match platform {
211            MobilePlatform::Ios => CacheHierarchy {
212                l1_size: 64 * 1024, // 64KB L1
213                l1_line_size: 64,
214                l1_associativity: 4,
215                l2_size: 3 * 1024 * 1024, // 3MB L2
216                l2_line_size: 128,
217                l2_associativity: 8,
218                l3_size: None,
219            },
220            MobilePlatform::Android => CacheHierarchy {
221                l1_size: 32 * 1024, // 32KB L1 (conservative)
222                l1_line_size: 64,
223                l1_associativity: 4,
224                l2_size: 1024 * 1024, // 1MB L2
225                l2_line_size: 64,
226                l2_associativity: 8,
227                l3_size: None,
228            },
229            MobilePlatform::Generic => CacheHierarchy {
230                l1_size: 32 * 1024,
231                l1_line_size: 64,
232                l1_associativity: 4,
233                l2_size: 256 * 1024,
234                l2_line_size: 64,
235                l2_associativity: 8,
236                l3_size: None,
237            },
238        }
239    }
240
241    fn select_optimal_layout(
242        &self,
243        shape: &[usize],
244        pattern: &AccessPattern,
245    ) -> Result<DataLayout> {
246        match pattern.access_type {
247            AccessType::Sequential => Ok(DataLayout::NCHW),
248            AccessType::Strided => {
249                // NHWC is often better for strided access on mobile
250                if self.platform == MobilePlatform::Android {
251                    Ok(DataLayout::NHWC)
252                } else {
253                    Ok(DataLayout::NCHW)
254                }
255            },
256            AccessType::Random => Ok(DataLayout::Custom),
257            AccessType::Broadcast => Ok(DataLayout::NC4HW4), // Packed for SIMD
258        }
259    }
260
261    fn current_layout_is_nchw(&self, tensor: &Tensor) -> bool {
262        // Simplified check - would need actual layout metadata
263        tensor.shape().len() == 4
264    }
265
266    fn transpose_nchw_to_nhwc(&self, tensor: &Tensor) -> Result<Tensor> {
267        if tensor.shape().len() != 4 {
268            return Err(TrustformersError::tensor_op_error(
269                "Expected 4D tensor",
270                "transpose_nchw_to_nhwc",
271            ));
272        }
273
274        let [n, c, h, w] = [
275            tensor.shape()[0],
276            tensor.shape()[1],
277            tensor.shape()[2],
278            tensor.shape()[3],
279        ];
280        let mut transposed_data = vec![0.0f32; n * h * w * c];
281        let src_data = tensor.data()?;
282
283        // Transpose from NCHW to NHWC
284        for batch in 0..n {
285            for channel in 0..c {
286                for row in 0..h {
287                    for col in 0..w {
288                        let src_idx = batch * c * h * w + channel * h * w + row * w + col;
289                        let dst_idx = batch * h * w * c + row * w * c + col * c + channel;
290                        transposed_data[dst_idx] = src_data[src_idx];
291                    }
292                }
293            }
294        }
295
296        Tensor::from_vec(transposed_data, &[n, h, w, c])
297    }
298
299    fn pack_to_nc4hw4(&self, tensor: &Tensor) -> Result<Tensor> {
300        if tensor.shape().len() != 4 {
301            return Err(TrustformersError::tensor_op_error(
302                "Expected 4D tensor",
303                "transpose_nchw_to_nhwc",
304            ));
305        }
306
307        let [n, c, h, w] = [
308            tensor.shape()[0],
309            tensor.shape()[1],
310            tensor.shape()[2],
311            tensor.shape()[3],
312        ];
313        let c_padded = c.div_ceil(4) * 4; // Round up to multiple of 4
314
315        let mut packed_data = vec![0.0f32; n * c_padded * h * w];
316        let src_data = tensor.data()?;
317
318        // Pack channels in groups of 4 for SIMD
319        for batch in 0..n {
320            for c_group in 0..c.div_ceil(4) {
321                for row in 0..h {
322                    for col in 0..w {
323                        for c_offset in 0..4 {
324                            let c_idx = c_group * 4 + c_offset;
325                            if c_idx < c {
326                                let src_idx = batch * c * h * w + c_idx * h * w + row * w + col;
327                                let dst_idx = batch * c_padded * h * w
328                                    + c_group * 4 * h * w
329                                    + row * w * 4
330                                    + col * 4
331                                    + c_offset;
332                                packed_data[dst_idx] = src_data[src_idx];
333                            }
334                        }
335                    }
336                }
337            }
338        }
339
340        Tensor::from_vec(packed_data, &[n, c_padded, h, w])
341    }
342
343    fn calculate_prefetch_distance(
344        &self,
345        kernel: &KernelType,
346        input_shapes: &[Vec<usize>],
347    ) -> Result<usize> {
348        // Calculate based on memory bandwidth and compute intensity
349        let compute_intensity = match kernel {
350            KernelType::Conv2d => 10.0,
351            KernelType::Linear => 2.0,
352            KernelType::Attention => 5.0,
353            _ => 1.0,
354        };
355
356        // Higher compute intensity = larger prefetch distance
357        Ok((compute_intensity * 2.0) as usize)
358    }
359
360    fn identify_streaming_tensors(
361        &self,
362        kernel: &KernelType,
363        input_shapes: &[Vec<usize>],
364    ) -> Result<Vec<String>> {
365        let mut streaming = Vec::new();
366
367        // Large tensors that won't fit in cache should stream
368        for (idx, shape) in input_shapes.iter().enumerate() {
369            let size_bytes = shape.iter().product::<usize>() * 4; // 4 bytes per float
370
371            if size_bytes > self.cache_hierarchy.l2_size {
372                streaming.push(format!("input_{}", idx));
373            }
374        }
375
376        Ok(streaming)
377    }
378
379    fn analyze_temporal_locality(
380        &self,
381        kernel: &KernelType,
382        input_shapes: &[Vec<usize>],
383    ) -> Result<HashMap<String, TemporalHint>> {
384        let mut hints = HashMap::new();
385
386        match kernel {
387            KernelType::Conv2d => {
388                hints.insert("weights".to_string(), TemporalHint::HighReuse);
389                hints.insert("input".to_string(), TemporalHint::MediumReuse);
390            },
391            KernelType::Linear => {
392                hints.insert("weights".to_string(), TemporalHint::HighReuse);
393                hints.insert("input".to_string(), TemporalHint::LowReuse);
394            },
395            KernelType::BatchNorm => {
396                hints.insert("mean".to_string(), TemporalHint::HighReuse);
397                hints.insert("variance".to_string(), TemporalHint::HighReuse);
398            },
399            _ => {},
400        }
401
402        Ok(hints)
403    }
404
405    fn analyze_spatial_locality(
406        &self,
407        kernel: &KernelType,
408        input_shapes: &[Vec<usize>],
409    ) -> Result<HashMap<String, SpatialHint>> {
410        let mut hints = HashMap::new();
411
412        match kernel {
413            KernelType::Conv2d => {
414                hints.insert("input".to_string(), SpatialHint::Blocked { block_size: 16 });
415                hints.insert("output".to_string(), SpatialHint::Contiguous);
416            },
417            KernelType::Linear => {
418                hints.insert("input".to_string(), SpatialHint::Contiguous);
419                hints.insert(
420                    "weights".to_string(),
421                    SpatialHint::Strided {
422                        stride: input_shapes[0][1],
423                    },
424                );
425            },
426            _ => {
427                hints.insert("default".to_string(), SpatialHint::Contiguous);
428            },
429        }
430
431        Ok(hints)
432    }
433
434    fn can_tile(&self, kernel: &KernelType) -> bool {
435        matches!(
436            kernel,
437            KernelType::Conv2d | KernelType::Linear | KernelType::Attention
438        )
439    }
440
441    fn compute_tiling_config(&self, operator: &GraphOperator) -> Result<TilingConfig> {
442        let tile_size = self.compute_optimal_tile_size(operator)?;
443
444        let config = match operator.kernel {
445            KernelType::Conv2d => TilingConfig {
446                tile_sizes: vec![1, tile_size, tile_size, tile_size], // N, C, H, W
447                loop_order: vec![0, 2, 3, 1], // N, H, W, C for better locality
448                unroll_factors: vec![1, 4, 1, 1],
449            },
450            KernelType::Linear => TilingConfig {
451                tile_sizes: vec![tile_size, tile_size], // M, N
452                loop_order: vec![0, 1],
453                unroll_factors: vec![4, 4],
454            },
455            _ => TilingConfig {
456                tile_sizes: vec![tile_size],
457                loop_order: vec![0],
458                unroll_factors: vec![4],
459            },
460        };
461
462        Ok(config)
463    }
464
465    fn compute_optimal_tile_size(&self, operator: &GraphOperator) -> Result<usize> {
466        // Calculate tile size to fit in L1 cache
467        let working_set_elements = operator
468            .input_shapes
469            .iter()
470            .map(|shape| shape.iter().product::<usize>())
471            .sum::<usize>();
472
473        let element_size = 4; // 4 bytes per float
474        let working_set_bytes = working_set_elements * element_size;
475
476        // Use 75% of L1 cache
477        let available_cache = (self.cache_hierarchy.l1_size as f32 * 0.75) as usize;
478
479        // Find tile size that fits
480        let mut tile_size = 64;
481        while tile_size * tile_size * element_size > available_cache && tile_size > 8 {
482            tile_size /= 2;
483        }
484
485        Ok(tile_size)
486    }
487
488    fn apply_tiling_to_operator(
489        &self,
490        operator: &mut GraphOperator,
491        config: &TilingConfig,
492    ) -> Result<()> {
493        // This would modify the operator to use tiled execution
494        // For now, just store the configuration
495        operator.kernel = match operator.kernel.clone() {
496            KernelType::Conv2d => KernelType::Custom("TiledConv2d".to_string()),
497            KernelType::Linear => KernelType::Custom("TiledLinear".to_string()),
498            other => other,
499        };
500
501        Ok(())
502    }
503
504    fn compute_strides(&self, kernel: &KernelType) -> Result<Vec<isize>> {
505        Ok(match kernel {
506            KernelType::Conv2d => vec![1, 1],  // Typical conv stride
507            KernelType::Pooling => vec![2, 2], // Typical pooling stride
508            _ => vec![1],                      // Sequential access
509        })
510    }
511
512    fn estimate_reuse_distance(&self, kernel: &KernelType) -> Result<usize> {
513        Ok(match kernel {
514            KernelType::Conv2d => 1024,  // High reuse for weights
515            KernelType::Linear => 256,   // Medium reuse
516            KernelType::BatchNorm => 64, // Low reuse
517            _ => 128,
518        })
519    }
520
521    fn estimate_working_set(&self, kernel: &KernelType) -> Result<usize> {
522        Ok(match kernel {
523            KernelType::Conv2d => 256 * 1024,    // 256KB typical
524            KernelType::Linear => 128 * 1024,    // 128KB
525            KernelType::Attention => 512 * 1024, // 512KB
526            _ => 64 * 1024,                      // 64KB
527        })
528    }
529}
530
531impl AccessPattern {
532    /// Analyze access pattern for given tensor and kernel
533    pub fn analyze(tensor_name: &str, kernel: &KernelType) -> Result<Self> {
534        let access_type = if tensor_name.contains("weight") {
535            AccessType::Broadcast
536        } else if matches!(kernel, KernelType::Attention) {
537            AccessType::Random
538        } else {
539            AccessType::Sequential
540        };
541
542        Ok(Self {
543            strides: vec![1],
544            access_type,
545            reuse_distance: 128,
546            working_set_size: 64 * 1024,
547        })
548    }
549}
550
551#[cfg(test)]
552mod tests {
553    use super::*;
554
555    #[test]
556    fn test_cache_optimizer_creation() {
557        let optimizer = CacheOptimizer::new(MobilePlatform::Generic);
558        assert_eq!(optimizer.platform, MobilePlatform::Generic);
559    }
560
561    #[test]
562    fn test_layout_optimization() {
563        let optimizer = CacheOptimizer::new(MobilePlatform::Android);
564        let tensor = Tensor::ones(&[1, 64, 32, 32]).expect("Operation failed");
565        let pattern = AccessPattern {
566            strides: vec![1, 1],
567            access_type: AccessType::Strided,
568            reuse_distance: 128,
569            working_set_size: 64 * 1024,
570        };
571
572        let optimized = optimizer.optimize_layout(&tensor, &pattern).expect("Operation failed");
573        // On Android with strided access, should transpose to NHWC
574        assert_eq!(optimized.shape(), &[1, 32, 32, 64]);
575    }
576
577    #[test]
578    fn test_tiling_config() {
579        let optimizer = CacheOptimizer::new(MobilePlatform::Ios);
580        let operator = GraphOperator {
581            id: 0,
582            kernel: KernelType::Conv2d,
583            inputs: vec!["input".to_string()],
584            outputs: vec!["output".to_string()],
585            input_shapes: vec![vec![1, 64, 32, 32]],
586            output_shape: vec![1, 128, 16, 16],
587            cache_hints: None,
588        };
589
590        let config = optimizer.compute_tiling_config(&operator).expect("Operation failed");
591        assert!(!config.tile_sizes.is_empty());
592        assert!(!config.loop_order.is_empty());
593    }
594
595    #[test]
596    fn test_cache_hints_generation() {
597        let optimizer = CacheOptimizer::new(MobilePlatform::Generic);
598        let kernel = KernelType::Conv2d;
599        let input_shapes = vec![vec![1, 3, 224, 224]];
600
601        let hints = optimizer.generate_hints(&kernel, &input_shapes).expect("Operation failed");
602        assert!(hints.prefetch_distance > 0);
603        assert!(!hints.temporal_hints.is_empty());
604    }
605}