Skip to main content

torsh_backend/cpu/
memory_patterns.rs

1//! Advanced memory access pattern optimization
2//!
3//! This module provides sophisticated memory access pattern optimizations
4//! including cache-friendly data layouts, prefetching strategies, and
5//! NUMA-aware memory allocation patterns.
6
7// Framework infrastructure - components designed for future use
8#![allow(dead_code)]
9use std::alloc::{self, Layout};
10use std::ptr::NonNull;
11
12use crate::cpu::error::CpuResult;
13
14/// Cache line size (typically 64 bytes on modern CPUs)
15pub const CACHE_LINE_SIZE: usize = 64;
16
17/// Memory access pattern types
18#[derive(Debug, Clone, Copy)]
19pub enum AccessPattern {
20    Sequential,     // Linear access through memory
21    Strided(usize), // Access with fixed stride
22    Random,         // Random access pattern
23    Blocked(usize), // Block-based access with given block size
24}
25
26/// Memory layout optimization strategies
27#[derive(Debug, Clone, Copy)]
28pub enum LayoutStrategy {
29    RowMajor,       // Standard row-major layout
30    ColumnMajor,    // Column-major layout
31    Blocked(usize), // Blocked layout with given block size
32    ZMorton,        // Z-order (Morton) curve layout
33    Hilbert,        // Hilbert curve layout
34    CacheOblivious, // Cache-oblivious layout
35}
36
37/// NUMA memory policy
38#[derive(Debug, Clone, Copy)]
39pub enum NumaPolicy {
40    Local,            // Allocate on local NUMA node
41    Interleave,       // Interleave across NUMA nodes
42    Preferred(usize), // Prefer specific NUMA node
43    Bind(usize),      // Bind to specific NUMA node
44}
45
46/// Memory prefetch strategy
47#[derive(Debug, Clone, Copy)]
48pub enum PrefetchStrategy {
49    None,
50    Software(usize), // Software prefetch with distance
51    Hardware,        // Hardware prefetching
52    Adaptive,        // Adaptive prefetching based on pattern
53}
54
55/// Cache-aligned memory allocator
56pub struct CacheAlignedAllocator {
57    alignment: usize,
58    numa_policy: NumaPolicy,
59}
60
61impl Default for CacheAlignedAllocator {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67impl CacheAlignedAllocator {
68    pub fn new() -> Self {
69        Self {
70            alignment: CACHE_LINE_SIZE,
71            numa_policy: NumaPolicy::Local,
72        }
73    }
74
75    pub fn with_alignment(alignment: usize) -> Self {
76        Self {
77            alignment,
78            numa_policy: NumaPolicy::Local,
79        }
80    }
81
82    pub fn with_numa_policy(numa_policy: NumaPolicy) -> Self {
83        Self {
84            alignment: CACHE_LINE_SIZE,
85            numa_policy,
86        }
87    }
88
89    /// Allocate cache-aligned memory
90    pub fn allocate<T>(&self, count: usize) -> CpuResult<CacheAlignedBuffer<T>> {
91        let layout = Layout::from_size_align(
92            count * std::mem::size_of::<T>(),
93            self.alignment.max(std::mem::align_of::<T>()),
94        )
95        .map_err(|_| crate::cpu::error::cpu_errors::memory_allocation_error("Invalid layout"))?;
96
97        let ptr = unsafe { alloc::alloc(layout) };
98        if ptr.is_null() {
99            return Err(crate::cpu::error::cpu_errors::memory_allocation_error(
100                "Allocation failed",
101            ));
102        }
103
104        Ok(CacheAlignedBuffer {
105            ptr: NonNull::new(ptr as *mut T).expect("ptr should not be null after null check"),
106            len: count,
107            layout,
108            numa_policy: self.numa_policy,
109        })
110    }
111
112    /// Allocate zero-initialized memory
113    pub fn allocate_zeroed<T>(&self, count: usize) -> CpuResult<CacheAlignedBuffer<T>> {
114        let layout = Layout::from_size_align(
115            count * std::mem::size_of::<T>(),
116            self.alignment.max(std::mem::align_of::<T>()),
117        )
118        .map_err(|_| crate::cpu::error::cpu_errors::memory_allocation_error("Invalid layout"))?;
119
120        let ptr = unsafe { alloc::alloc_zeroed(layout) };
121        if ptr.is_null() {
122            return Err(crate::cpu::error::cpu_errors::memory_allocation_error(
123                "Allocation failed",
124            ));
125        }
126
127        Ok(CacheAlignedBuffer {
128            ptr: NonNull::new(ptr as *mut T).expect("ptr should not be null after null check"),
129            len: count,
130            layout,
131            numa_policy: self.numa_policy,
132        })
133    }
134}
135
136/// Cache-aligned memory buffer
137pub struct CacheAlignedBuffer<T> {
138    ptr: NonNull<T>,
139    len: usize,
140    layout: Layout,
141    #[allow(dead_code)]
142    numa_policy: NumaPolicy,
143}
144
145impl<T> CacheAlignedBuffer<T> {
146    /// Get raw pointer
147    pub fn as_ptr(&self) -> *const T {
148        self.ptr.as_ptr()
149    }
150
151    /// Get mutable raw pointer
152    pub fn as_mut_ptr(&mut self) -> *mut T {
153        self.ptr.as_ptr()
154    }
155
156    /// Get length
157    pub fn len(&self) -> usize {
158        self.len
159    }
160
161    /// Check if empty
162    pub fn is_empty(&self) -> bool {
163        self.len == 0
164    }
165
166    /// Get as slice
167    ///
168    /// # Safety
169    ///
170    /// The caller must ensure that:
171    /// - The pointer is valid and points to `len` elements of type `T`
172    /// - The memory is properly aligned for type `T`
173    /// - The memory is not deallocated during the lifetime of the returned slice
174    pub unsafe fn as_slice(&self) -> &[T] {
175        std::slice::from_raw_parts(self.ptr.as_ptr(), self.len)
176    }
177
178    /// Get as mutable slice
179    ///
180    /// # Safety
181    ///
182    /// The caller must ensure that:
183    /// - The pointer is valid and points to `len` elements of type `T`
184    /// - The memory is properly aligned for type `T`
185    /// - The memory is not deallocated during the lifetime of the returned slice
186    /// - No other references to the same memory exist during the lifetime of the returned slice
187    pub unsafe fn as_mut_slice(&mut self) -> &mut [T] {
188        std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len)
189    }
190
191    /// Check if pointer is cache-aligned
192    pub fn is_cache_aligned(&self) -> bool {
193        (self.ptr.as_ptr() as usize).is_multiple_of(CACHE_LINE_SIZE)
194    }
195}
196
197impl<T> Drop for CacheAlignedBuffer<T> {
198    fn drop(&mut self) {
199        unsafe {
200            alloc::dealloc(self.ptr.as_ptr() as *mut u8, self.layout);
201        }
202    }
203}
204
205unsafe impl<T: Send> Send for CacheAlignedBuffer<T> {}
206unsafe impl<T: Sync> Sync for CacheAlignedBuffer<T> {}
207
208/// Memory access pattern optimizer
209pub struct AccessPatternOptimizer {
210    prefetch_strategy: PrefetchStrategy,
211    layout_strategy: LayoutStrategy,
212    cache_line_size: usize,
213    l1_cache_size: usize,
214    l2_cache_size: usize,
215    l3_cache_size: usize,
216}
217
218impl Default for AccessPatternOptimizer {
219    fn default() -> Self {
220        Self::new()
221    }
222}
223
224impl AccessPatternOptimizer {
225    pub fn new() -> Self {
226        Self {
227            prefetch_strategy: PrefetchStrategy::Adaptive,
228            layout_strategy: LayoutStrategy::RowMajor,
229            cache_line_size: CACHE_LINE_SIZE,
230            l1_cache_size: 32 * 1024,       // 32KB
231            l2_cache_size: 256 * 1024,      // 256KB
232            l3_cache_size: 8 * 1024 * 1024, // 8MB
233        }
234    }
235
236    pub fn with_cache_sizes(l1: usize, l2: usize, l3: usize) -> Self {
237        Self {
238            prefetch_strategy: PrefetchStrategy::Adaptive,
239            layout_strategy: LayoutStrategy::RowMajor,
240            cache_line_size: CACHE_LINE_SIZE,
241            l1_cache_size: l1,
242            l2_cache_size: l2,
243            l3_cache_size: l3,
244        }
245    }
246
247    /// Set prefetch strategy
248    pub fn set_prefetch_strategy(&mut self, strategy: PrefetchStrategy) {
249        self.prefetch_strategy = strategy;
250    }
251
252    /// Set layout strategy
253    pub fn set_layout_strategy(&mut self, strategy: LayoutStrategy) {
254        self.layout_strategy = strategy;
255    }
256
257    /// Calculate optimal block size for cache efficiency
258    pub fn optimal_block_size(&self, element_size: usize, cache_level: CacheLevel) -> usize {
259        let cache_size = match cache_level {
260            CacheLevel::L1 => self.l1_cache_size,
261            CacheLevel::L2 => self.l2_cache_size,
262            CacheLevel::L3 => self.l3_cache_size,
263        };
264
265        // Use fraction of cache to leave room for other data
266        let usable_cache = cache_size / 2;
267        let _elements_in_cache = usable_cache / element_size;
268
269        // Find largest power of 2 that fits
270        let mut block_size = 1;
271        while block_size * block_size * element_size <= usable_cache {
272            block_size *= 2;
273        }
274        block_size / 2
275    }
276
277    /// Optimize matrix access pattern for cache efficiency
278    pub fn optimize_matrix_access<T: Copy>(
279        &self,
280        matrix: &[T],
281        rows: usize,
282        cols: usize,
283        access_pattern: AccessPattern,
284    ) -> Vec<usize> {
285        match access_pattern {
286            AccessPattern::Sequential => (0..matrix.len()).collect(),
287            AccessPattern::Strided(stride) => (0..matrix.len()).step_by(stride).collect(),
288            AccessPattern::Random => {
289                // Generate cache-friendly random access pattern
290                let mut indices: Vec<usize> = (0..matrix.len()).collect();
291                // Sort by cache line to improve locality
292                indices.sort_by_key(|&i| i / (self.cache_line_size / std::mem::size_of::<T>()));
293                indices
294            }
295            AccessPattern::Blocked(block_size) => {
296                self.generate_blocked_access_pattern(rows, cols, block_size)
297            }
298        }
299    }
300
301    /// Generate blocked access pattern for matrices
302    fn generate_blocked_access_pattern(
303        &self,
304        rows: usize,
305        cols: usize,
306        block_size: usize,
307    ) -> Vec<usize> {
308        let mut indices = Vec::new();
309
310        let row_blocks = (rows + block_size - 1) / block_size;
311        let col_blocks = (cols + block_size - 1) / block_size;
312
313        for block_row in 0..row_blocks {
314            for block_col in 0..col_blocks {
315                let start_row = block_row * block_size;
316                let end_row = ((block_row + 1) * block_size).min(rows);
317                let start_col = block_col * block_size;
318                let end_col = ((block_col + 1) * block_size).min(cols);
319
320                for i in start_row..end_row {
321                    for j in start_col..end_col {
322                        indices.push(i * cols + j);
323                    }
324                }
325            }
326        }
327
328        indices
329    }
330
331    /// Prefetch memory for improved cache performance
332    pub fn prefetch_memory<T>(&self, ptr: *const T, len: usize, access_pattern: AccessPattern) {
333        match self.prefetch_strategy {
334            PrefetchStrategy::None => {}
335            PrefetchStrategy::Software(distance) => {
336                self.software_prefetch(ptr, len, distance, access_pattern);
337            }
338            PrefetchStrategy::Hardware => {
339                // Enable hardware prefetching (platform-specific)
340                #[cfg(target_arch = "x86_64")]
341                unsafe {
342                    // Intel hardware prefetch hints
343                    std::arch::x86_64::_mm_prefetch(
344                        ptr as *const i8,
345                        std::arch::x86_64::_MM_HINT_T0,
346                    );
347                }
348            }
349            PrefetchStrategy::Adaptive => {
350                // Choose strategy based on access pattern
351                match access_pattern {
352                    AccessPattern::Sequential => {
353                        self.software_prefetch(ptr, len, 4, access_pattern);
354                    }
355                    AccessPattern::Strided(stride) if stride <= 16 => {
356                        self.software_prefetch(ptr, len, 2, access_pattern);
357                    }
358                    _ => {
359                        // Use hardware prefetching for complex patterns
360                        #[cfg(target_arch = "x86_64")]
361                        unsafe {
362                            std::arch::x86_64::_mm_prefetch(
363                                ptr as *const i8,
364                                std::arch::x86_64::_MM_HINT_T1,
365                            );
366                        }
367                    }
368                }
369            }
370        }
371    }
372
373    /// Software prefetching implementation
374    fn software_prefetch<T>(
375        &self,
376        _ptr: *const T,
377        len: usize,
378        distance: usize,
379        pattern: AccessPattern,
380    ) {
381        match pattern {
382            AccessPattern::Sequential => {
383                for _i in (0..len).step_by(self.cache_line_size / std::mem::size_of::<T>()) {
384                    if _i + distance < len {
385                        #[cfg(target_arch = "x86_64")]
386                        unsafe {
387                            let prefetch_ptr = _ptr.add(_i + distance);
388                            std::arch::x86_64::_mm_prefetch(
389                                prefetch_ptr as *const i8,
390                                std::arch::x86_64::_MM_HINT_T0,
391                            );
392                        }
393                    }
394                }
395            }
396            AccessPattern::Strided(stride) => {
397                for _i in (0..len).step_by(stride) {
398                    if _i + distance * stride < len {
399                        #[cfg(target_arch = "x86_64")]
400                        unsafe {
401                            let prefetch_ptr = _ptr.add(_i + distance * stride);
402                            std::arch::x86_64::_mm_prefetch(
403                                prefetch_ptr as *const i8,
404                                std::arch::x86_64::_MM_HINT_T0,
405                            );
406                        }
407                    }
408                }
409            }
410            _ => {
411                // Default to cache line granularity
412                for _i in (0..len).step_by(self.cache_line_size / std::mem::size_of::<T>()) {
413                    #[cfg(target_arch = "x86_64")]
414                    unsafe {
415                        let prefetch_ptr = _ptr.add(_i);
416                        std::arch::x86_64::_mm_prefetch(
417                            prefetch_ptr as *const i8,
418                            std::arch::x86_64::_MM_HINT_T1,
419                        );
420                    }
421                }
422            }
423        }
424    }
425
426    /// Calculate memory bandwidth utilization
427    pub fn calculate_bandwidth_utilization(
428        &self,
429        bytes_transferred: usize,
430        time_elapsed: std::time::Duration,
431    ) -> f64 {
432        if time_elapsed.as_secs_f64() > 0.0 {
433            bytes_transferred as f64 / time_elapsed.as_secs_f64() / (1024.0 * 1024.0 * 1024.0)
434        // GB/s
435        } else {
436            0.0
437        }
438    }
439
440    /// Get optimal chunk size for streaming operations
441    pub fn optimal_streaming_chunk_size(&self, element_size: usize) -> usize {
442        // Target 75% of L2 cache for streaming
443        let target_bytes = (self.l2_cache_size * 3) / 4;
444        let chunk_elements = target_bytes / element_size;
445
446        // Round down to nearest cache line boundary
447        let elements_per_line = self.cache_line_size / element_size;
448        (chunk_elements / elements_per_line) * elements_per_line
449    }
450}
451
452/// Cache level enumeration
453#[derive(Debug, Clone, Copy)]
454pub enum CacheLevel {
455    L1,
456    L2,
457    L3,
458}
459
460/// Memory layout transformer for different access patterns
461pub struct LayoutTransformer {
462    optimizer: AccessPatternOptimizer,
463}
464
465impl Default for LayoutTransformer {
466    fn default() -> Self {
467        Self::new()
468    }
469}
470
471impl LayoutTransformer {
472    pub fn new() -> Self {
473        Self {
474            optimizer: AccessPatternOptimizer::new(),
475        }
476    }
477
478    /// Transform matrix from row-major to blocked layout
479    pub fn to_blocked_layout<T: Copy>(
480        &self,
481        input: &[T],
482        rows: usize,
483        cols: usize,
484        block_size: usize,
485    ) -> Vec<T> {
486        let mut output = vec![input[0]; input.len()]; // Use first element as default
487
488        let row_blocks = (rows + block_size - 1) / block_size;
489        let col_blocks = (cols + block_size - 1) / block_size;
490
491        let mut out_idx = 0;
492
493        for block_row in 0..row_blocks {
494            for block_col in 0..col_blocks {
495                let start_row = block_row * block_size;
496                let end_row = ((block_row + 1) * block_size).min(rows);
497                let start_col = block_col * block_size;
498                let end_col = ((block_col + 1) * block_size).min(cols);
499
500                for i in start_row..end_row {
501                    for j in start_col..end_col {
502                        if out_idx < output.len() {
503                            output[out_idx] = input[i * cols + j];
504                            out_idx += 1;
505                        }
506                    }
507                }
508            }
509        }
510
511        output
512    }
513
514    /// Transform matrix from blocked back to row-major layout
515    pub fn from_blocked_layout<T: Copy>(
516        &self,
517        input: &[T],
518        rows: usize,
519        cols: usize,
520        block_size: usize,
521    ) -> Vec<T> {
522        let mut output = vec![input[0]; input.len()];
523
524        let row_blocks = (rows + block_size - 1) / block_size;
525        let col_blocks = (cols + block_size - 1) / block_size;
526
527        let mut in_idx = 0;
528
529        for block_row in 0..row_blocks {
530            for block_col in 0..col_blocks {
531                let start_row = block_row * block_size;
532                let end_row = ((block_row + 1) * block_size).min(rows);
533                let start_col = block_col * block_size;
534                let end_col = ((block_col + 1) * block_size).min(cols);
535
536                for i in start_row..end_row {
537                    for j in start_col..end_col {
538                        if in_idx < input.len() {
539                            output[i * cols + j] = input[in_idx];
540                            in_idx += 1;
541                        }
542                    }
543                }
544            }
545        }
546
547        output
548    }
549
550    /// Calculate cache miss rate estimate for given access pattern
551    pub fn estimate_cache_miss_rate(
552        &self,
553        data_size: usize,
554        access_pattern: AccessPattern,
555        cache_level: CacheLevel,
556    ) -> f64 {
557        let cache_size = match cache_level {
558            CacheLevel::L1 => self.optimizer.l1_cache_size,
559            CacheLevel::L2 => self.optimizer.l2_cache_size,
560            CacheLevel::L3 => self.optimizer.l3_cache_size,
561        };
562
563        match access_pattern {
564            AccessPattern::Sequential => {
565                if data_size <= cache_size {
566                    0.01 // Very low miss rate for sequential access within cache
567                } else {
568                    1.0 - (cache_size as f64 / data_size as f64)
569                }
570            }
571            AccessPattern::Strided(stride) => {
572                let effective_size = data_size * stride;
573                if effective_size <= cache_size {
574                    0.05
575                } else {
576                    0.8
577                }
578            }
579            AccessPattern::Random => {
580                if data_size <= cache_size {
581                    0.1
582                } else {
583                    0.95 // Very high miss rate for random access
584                }
585            }
586            AccessPattern::Blocked(block_size) => {
587                let block_data_size = block_size * block_size * 4; // Assume 4 bytes per element
588                if block_data_size <= cache_size {
589                    0.02
590                } else {
591                    0.3
592                }
593            }
594        }
595    }
596}
597
598#[cfg(test)]
599mod tests {
600    use super::*;
601
602    #[test]
603    fn test_cache_aligned_allocator() {
604        let allocator = CacheAlignedAllocator::new();
605        let buffer = allocator
606            .allocate::<f32>(1000)
607            .expect("operation should succeed");
608
609        assert_eq!(buffer.len(), 1000);
610        assert!(buffer.is_cache_aligned());
611    }
612
613    #[test]
614    fn test_access_pattern_optimizer() {
615        let optimizer = AccessPatternOptimizer::new();
616
617        let block_size = optimizer.optimal_block_size(4, CacheLevel::L1);
618        assert!(block_size > 0);
619        assert!(block_size.is_power_of_two());
620
621        let streaming_chunk = optimizer.optimal_streaming_chunk_size(4);
622        assert!(streaming_chunk > 0);
623        assert!(streaming_chunk % (CACHE_LINE_SIZE / 4) == 0);
624    }
625
626    #[test]
627    fn test_matrix_access_optimization() {
628        let optimizer = AccessPatternOptimizer::new();
629        let matrix = vec![1.0f32; 100];
630
631        let indices = optimizer.optimize_matrix_access(&matrix, 10, 10, AccessPattern::Sequential);
632
633        assert_eq!(indices.len(), matrix.len());
634        assert_eq!(indices, (0..100).collect::<Vec<_>>());
635
636        let blocked_indices =
637            optimizer.optimize_matrix_access(&matrix, 10, 10, AccessPattern::Blocked(4));
638
639        assert_eq!(blocked_indices.len(), matrix.len());
640    }
641
642    #[test]
643    fn test_layout_transformer() {
644        let transformer = LayoutTransformer::new();
645        let input: Vec<f32> = (0..16).map(|i| i as f32).collect();
646
647        let blocked = transformer.to_blocked_layout(&input, 4, 4, 2);
648        assert_eq!(blocked.len(), input.len());
649
650        let restored = transformer.from_blocked_layout(&blocked, 4, 4, 2);
651        assert_eq!(restored, input);
652    }
653
654    #[test]
655    fn test_cache_miss_estimation() {
656        let transformer = LayoutTransformer::new();
657
658        let miss_rate_seq =
659            transformer.estimate_cache_miss_rate(1000, AccessPattern::Sequential, CacheLevel::L1);
660
661        let miss_rate_random =
662            transformer.estimate_cache_miss_rate(1000, AccessPattern::Random, CacheLevel::L1);
663
664        assert!(miss_rate_seq < miss_rate_random);
665    }
666
667    #[test]
668    fn test_bandwidth_calculation() {
669        let optimizer = AccessPatternOptimizer::new();
670        let bandwidth = optimizer.calculate_bandwidth_utilization(
671            1024 * 1024 * 1024, // 1GB
672            std::time::Duration::from_secs(1),
673        );
674
675        assert!((bandwidth - 1.0).abs() < 0.01); // Should be ~1 GB/s
676    }
677}
678
679/// Calculate memory bandwidth in GB/s given bytes transferred and time elapsed
680///
681/// This is a standalone utility function for benchmarking purposes
682pub fn calculate_memory_bandwidth(bytes: usize, elapsed: std::time::Duration) -> f64 {
683    if elapsed.as_secs_f64() > 0.0 {
684        bytes as f64 / elapsed.as_secs_f64() / (1024.0 * 1024.0 * 1024.0) // GB/s
685    } else {
686        0.0
687    }
688}