torsh-backend 0.1.2

Backend abstraction layer for ToRSh
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
//! Advanced memory access pattern optimization
//!
//! This module provides sophisticated memory access pattern optimizations
//! including cache-friendly data layouts, prefetching strategies, and
//! NUMA-aware memory allocation patterns.

// Framework infrastructure - components designed for future use
#![allow(dead_code)]
use std::alloc::{self, Layout};
use std::ptr::NonNull;

use crate::cpu::error::CpuResult;

/// Cache line size (typically 64 bytes on modern CPUs)
pub const CACHE_LINE_SIZE: usize = 64;

/// Memory access pattern types
#[derive(Debug, Clone, Copy)]
pub enum AccessPattern {
    Sequential,     // Linear access through memory
    Strided(usize), // Access with fixed stride
    Random,         // Random access pattern
    Blocked(usize), // Block-based access with given block size
}

/// Memory layout optimization strategies
#[derive(Debug, Clone, Copy)]
pub enum LayoutStrategy {
    RowMajor,       // Standard row-major layout
    ColumnMajor,    // Column-major layout
    Blocked(usize), // Blocked layout with given block size
    ZMorton,        // Z-order (Morton) curve layout
    Hilbert,        // Hilbert curve layout
    CacheOblivious, // Cache-oblivious layout
}

/// NUMA memory policy
#[derive(Debug, Clone, Copy)]
pub enum NumaPolicy {
    Local,            // Allocate on local NUMA node
    Interleave,       // Interleave across NUMA nodes
    Preferred(usize), // Prefer specific NUMA node
    Bind(usize),      // Bind to specific NUMA node
}

/// Memory prefetch strategy
#[derive(Debug, Clone, Copy)]
pub enum PrefetchStrategy {
    None,
    Software(usize), // Software prefetch with distance
    Hardware,        // Hardware prefetching
    Adaptive,        // Adaptive prefetching based on pattern
}

/// Cache-aligned memory allocator
pub struct CacheAlignedAllocator {
    alignment: usize,
    numa_policy: NumaPolicy,
}

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

impl CacheAlignedAllocator {
    pub fn new() -> Self {
        Self {
            alignment: CACHE_LINE_SIZE,
            numa_policy: NumaPolicy::Local,
        }
    }

    pub fn with_alignment(alignment: usize) -> Self {
        Self {
            alignment,
            numa_policy: NumaPolicy::Local,
        }
    }

    pub fn with_numa_policy(numa_policy: NumaPolicy) -> Self {
        Self {
            alignment: CACHE_LINE_SIZE,
            numa_policy,
        }
    }

    /// Allocate cache-aligned memory
    pub fn allocate<T>(&self, count: usize) -> CpuResult<CacheAlignedBuffer<T>> {
        let layout = Layout::from_size_align(
            count * std::mem::size_of::<T>(),
            self.alignment.max(std::mem::align_of::<T>()),
        )
        .map_err(|_| crate::cpu::error::cpu_errors::memory_allocation_error("Invalid layout"))?;

        let ptr = unsafe { alloc::alloc(layout) };
        if ptr.is_null() {
            return Err(crate::cpu::error::cpu_errors::memory_allocation_error(
                "Allocation failed",
            ));
        }

        Ok(CacheAlignedBuffer {
            ptr: NonNull::new(ptr as *mut T).expect("ptr should not be null after null check"),
            len: count,
            layout,
            numa_policy: self.numa_policy,
        })
    }

    /// Allocate zero-initialized memory
    pub fn allocate_zeroed<T>(&self, count: usize) -> CpuResult<CacheAlignedBuffer<T>> {
        let layout = Layout::from_size_align(
            count * std::mem::size_of::<T>(),
            self.alignment.max(std::mem::align_of::<T>()),
        )
        .map_err(|_| crate::cpu::error::cpu_errors::memory_allocation_error("Invalid layout"))?;

        let ptr = unsafe { alloc::alloc_zeroed(layout) };
        if ptr.is_null() {
            return Err(crate::cpu::error::cpu_errors::memory_allocation_error(
                "Allocation failed",
            ));
        }

        Ok(CacheAlignedBuffer {
            ptr: NonNull::new(ptr as *mut T).expect("ptr should not be null after null check"),
            len: count,
            layout,
            numa_policy: self.numa_policy,
        })
    }
}

/// Cache-aligned memory buffer
pub struct CacheAlignedBuffer<T> {
    ptr: NonNull<T>,
    len: usize,
    layout: Layout,
    #[allow(dead_code)]
    numa_policy: NumaPolicy,
}

impl<T> CacheAlignedBuffer<T> {
    /// Get raw pointer
    pub fn as_ptr(&self) -> *const T {
        self.ptr.as_ptr()
    }

    /// Get mutable raw pointer
    pub fn as_mut_ptr(&mut self) -> *mut T {
        self.ptr.as_ptr()
    }

    /// Get length
    pub fn len(&self) -> usize {
        self.len
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Get as slice
    ///
    /// # Safety
    ///
    /// The caller must ensure that:
    /// - The pointer is valid and points to `len` elements of type `T`
    /// - The memory is properly aligned for type `T`
    /// - The memory is not deallocated during the lifetime of the returned slice
    pub unsafe fn as_slice(&self) -> &[T] {
        std::slice::from_raw_parts(self.ptr.as_ptr(), self.len)
    }

    /// Get as mutable slice
    ///
    /// # Safety
    ///
    /// The caller must ensure that:
    /// - The pointer is valid and points to `len` elements of type `T`
    /// - The memory is properly aligned for type `T`
    /// - The memory is not deallocated during the lifetime of the returned slice
    /// - No other references to the same memory exist during the lifetime of the returned slice
    pub unsafe fn as_mut_slice(&mut self) -> &mut [T] {
        std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len)
    }

    /// Check if pointer is cache-aligned
    pub fn is_cache_aligned(&self) -> bool {
        (self.ptr.as_ptr() as usize).is_multiple_of(CACHE_LINE_SIZE)
    }
}

impl<T> Drop for CacheAlignedBuffer<T> {
    fn drop(&mut self) {
        unsafe {
            alloc::dealloc(self.ptr.as_ptr() as *mut u8, self.layout);
        }
    }
}

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

/// Memory access pattern optimizer
pub struct AccessPatternOptimizer {
    prefetch_strategy: PrefetchStrategy,
    layout_strategy: LayoutStrategy,
    cache_line_size: usize,
    l1_cache_size: usize,
    l2_cache_size: usize,
    l3_cache_size: usize,
}

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

impl AccessPatternOptimizer {
    pub fn new() -> Self {
        Self {
            prefetch_strategy: PrefetchStrategy::Adaptive,
            layout_strategy: LayoutStrategy::RowMajor,
            cache_line_size: CACHE_LINE_SIZE,
            l1_cache_size: 32 * 1024,       // 32KB
            l2_cache_size: 256 * 1024,      // 256KB
            l3_cache_size: 8 * 1024 * 1024, // 8MB
        }
    }

    pub fn with_cache_sizes(l1: usize, l2: usize, l3: usize) -> Self {
        Self {
            prefetch_strategy: PrefetchStrategy::Adaptive,
            layout_strategy: LayoutStrategy::RowMajor,
            cache_line_size: CACHE_LINE_SIZE,
            l1_cache_size: l1,
            l2_cache_size: l2,
            l3_cache_size: l3,
        }
    }

    /// Set prefetch strategy
    pub fn set_prefetch_strategy(&mut self, strategy: PrefetchStrategy) {
        self.prefetch_strategy = strategy;
    }

    /// Set layout strategy
    pub fn set_layout_strategy(&mut self, strategy: LayoutStrategy) {
        self.layout_strategy = strategy;
    }

    /// Calculate optimal block size for cache efficiency
    pub fn optimal_block_size(&self, element_size: usize, cache_level: CacheLevel) -> usize {
        let cache_size = match cache_level {
            CacheLevel::L1 => self.l1_cache_size,
            CacheLevel::L2 => self.l2_cache_size,
            CacheLevel::L3 => self.l3_cache_size,
        };

        // Use fraction of cache to leave room for other data
        let usable_cache = cache_size / 2;
        let _elements_in_cache = usable_cache / element_size;

        // Find largest power of 2 that fits
        let mut block_size = 1;
        while block_size * block_size * element_size <= usable_cache {
            block_size *= 2;
        }
        block_size / 2
    }

    /// Optimize matrix access pattern for cache efficiency
    pub fn optimize_matrix_access<T: Copy>(
        &self,
        matrix: &[T],
        rows: usize,
        cols: usize,
        access_pattern: AccessPattern,
    ) -> Vec<usize> {
        match access_pattern {
            AccessPattern::Sequential => (0..matrix.len()).collect(),
            AccessPattern::Strided(stride) => (0..matrix.len()).step_by(stride).collect(),
            AccessPattern::Random => {
                // Generate cache-friendly random access pattern
                let mut indices: Vec<usize> = (0..matrix.len()).collect();
                // Sort by cache line to improve locality
                indices.sort_by_key(|&i| i / (self.cache_line_size / std::mem::size_of::<T>()));
                indices
            }
            AccessPattern::Blocked(block_size) => {
                self.generate_blocked_access_pattern(rows, cols, block_size)
            }
        }
    }

    /// Generate blocked access pattern for matrices
    fn generate_blocked_access_pattern(
        &self,
        rows: usize,
        cols: usize,
        block_size: usize,
    ) -> Vec<usize> {
        let mut indices = Vec::new();

        let row_blocks = (rows + block_size - 1) / block_size;
        let col_blocks = (cols + block_size - 1) / block_size;

        for block_row in 0..row_blocks {
            for block_col in 0..col_blocks {
                let start_row = block_row * block_size;
                let end_row = ((block_row + 1) * block_size).min(rows);
                let start_col = block_col * block_size;
                let end_col = ((block_col + 1) * block_size).min(cols);

                for i in start_row..end_row {
                    for j in start_col..end_col {
                        indices.push(i * cols + j);
                    }
                }
            }
        }

        indices
    }

    /// Prefetch memory for improved cache performance
    pub fn prefetch_memory<T>(&self, ptr: *const T, len: usize, access_pattern: AccessPattern) {
        match self.prefetch_strategy {
            PrefetchStrategy::None => {}
            PrefetchStrategy::Software(distance) => {
                self.software_prefetch(ptr, len, distance, access_pattern);
            }
            PrefetchStrategy::Hardware => {
                // Enable hardware prefetching (platform-specific)
                #[cfg(target_arch = "x86_64")]
                unsafe {
                    // Intel hardware prefetch hints
                    std::arch::x86_64::_mm_prefetch(
                        ptr as *const i8,
                        std::arch::x86_64::_MM_HINT_T0,
                    );
                }
            }
            PrefetchStrategy::Adaptive => {
                // Choose strategy based on access pattern
                match access_pattern {
                    AccessPattern::Sequential => {
                        self.software_prefetch(ptr, len, 4, access_pattern);
                    }
                    AccessPattern::Strided(stride) if stride <= 16 => {
                        self.software_prefetch(ptr, len, 2, access_pattern);
                    }
                    _ => {
                        // Use hardware prefetching for complex patterns
                        #[cfg(target_arch = "x86_64")]
                        unsafe {
                            std::arch::x86_64::_mm_prefetch(
                                ptr as *const i8,
                                std::arch::x86_64::_MM_HINT_T1,
                            );
                        }
                    }
                }
            }
        }
    }

    /// Software prefetching implementation
    fn software_prefetch<T>(
        &self,
        _ptr: *const T,
        len: usize,
        distance: usize,
        pattern: AccessPattern,
    ) {
        match pattern {
            AccessPattern::Sequential => {
                for _i in (0..len).step_by(self.cache_line_size / std::mem::size_of::<T>()) {
                    if _i + distance < len {
                        #[cfg(target_arch = "x86_64")]
                        unsafe {
                            let prefetch_ptr = _ptr.add(_i + distance);
                            std::arch::x86_64::_mm_prefetch(
                                prefetch_ptr as *const i8,
                                std::arch::x86_64::_MM_HINT_T0,
                            );
                        }
                    }
                }
            }
            AccessPattern::Strided(stride) => {
                for _i in (0..len).step_by(stride) {
                    if _i + distance * stride < len {
                        #[cfg(target_arch = "x86_64")]
                        unsafe {
                            let prefetch_ptr = _ptr.add(_i + distance * stride);
                            std::arch::x86_64::_mm_prefetch(
                                prefetch_ptr as *const i8,
                                std::arch::x86_64::_MM_HINT_T0,
                            );
                        }
                    }
                }
            }
            _ => {
                // Default to cache line granularity
                for _i in (0..len).step_by(self.cache_line_size / std::mem::size_of::<T>()) {
                    #[cfg(target_arch = "x86_64")]
                    unsafe {
                        let prefetch_ptr = _ptr.add(_i);
                        std::arch::x86_64::_mm_prefetch(
                            prefetch_ptr as *const i8,
                            std::arch::x86_64::_MM_HINT_T1,
                        );
                    }
                }
            }
        }
    }

    /// Calculate memory bandwidth utilization
    pub fn calculate_bandwidth_utilization(
        &self,
        bytes_transferred: usize,
        time_elapsed: std::time::Duration,
    ) -> f64 {
        if time_elapsed.as_secs_f64() > 0.0 {
            bytes_transferred as f64 / time_elapsed.as_secs_f64() / (1024.0 * 1024.0 * 1024.0)
        // GB/s
        } else {
            0.0
        }
    }

    /// Get optimal chunk size for streaming operations
    pub fn optimal_streaming_chunk_size(&self, element_size: usize) -> usize {
        // Target 75% of L2 cache for streaming
        let target_bytes = (self.l2_cache_size * 3) / 4;
        let chunk_elements = target_bytes / element_size;

        // Round down to nearest cache line boundary
        let elements_per_line = self.cache_line_size / element_size;
        (chunk_elements / elements_per_line) * elements_per_line
    }
}

/// Cache level enumeration
#[derive(Debug, Clone, Copy)]
pub enum CacheLevel {
    L1,
    L2,
    L3,
}

/// Memory layout transformer for different access patterns
pub struct LayoutTransformer {
    optimizer: AccessPatternOptimizer,
}

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

impl LayoutTransformer {
    pub fn new() -> Self {
        Self {
            optimizer: AccessPatternOptimizer::new(),
        }
    }

    /// Transform matrix from row-major to blocked layout
    pub fn to_blocked_layout<T: Copy>(
        &self,
        input: &[T],
        rows: usize,
        cols: usize,
        block_size: usize,
    ) -> Vec<T> {
        let mut output = vec![input[0]; input.len()]; // Use first element as default

        let row_blocks = (rows + block_size - 1) / block_size;
        let col_blocks = (cols + block_size - 1) / block_size;

        let mut out_idx = 0;

        for block_row in 0..row_blocks {
            for block_col in 0..col_blocks {
                let start_row = block_row * block_size;
                let end_row = ((block_row + 1) * block_size).min(rows);
                let start_col = block_col * block_size;
                let end_col = ((block_col + 1) * block_size).min(cols);

                for i in start_row..end_row {
                    for j in start_col..end_col {
                        if out_idx < output.len() {
                            output[out_idx] = input[i * cols + j];
                            out_idx += 1;
                        }
                    }
                }
            }
        }

        output
    }

    /// Transform matrix from blocked back to row-major layout
    pub fn from_blocked_layout<T: Copy>(
        &self,
        input: &[T],
        rows: usize,
        cols: usize,
        block_size: usize,
    ) -> Vec<T> {
        let mut output = vec![input[0]; input.len()];

        let row_blocks = (rows + block_size - 1) / block_size;
        let col_blocks = (cols + block_size - 1) / block_size;

        let mut in_idx = 0;

        for block_row in 0..row_blocks {
            for block_col in 0..col_blocks {
                let start_row = block_row * block_size;
                let end_row = ((block_row + 1) * block_size).min(rows);
                let start_col = block_col * block_size;
                let end_col = ((block_col + 1) * block_size).min(cols);

                for i in start_row..end_row {
                    for j in start_col..end_col {
                        if in_idx < input.len() {
                            output[i * cols + j] = input[in_idx];
                            in_idx += 1;
                        }
                    }
                }
            }
        }

        output
    }

    /// Calculate cache miss rate estimate for given access pattern
    pub fn estimate_cache_miss_rate(
        &self,
        data_size: usize,
        access_pattern: AccessPattern,
        cache_level: CacheLevel,
    ) -> f64 {
        let cache_size = match cache_level {
            CacheLevel::L1 => self.optimizer.l1_cache_size,
            CacheLevel::L2 => self.optimizer.l2_cache_size,
            CacheLevel::L3 => self.optimizer.l3_cache_size,
        };

        match access_pattern {
            AccessPattern::Sequential => {
                if data_size <= cache_size {
                    0.01 // Very low miss rate for sequential access within cache
                } else {
                    1.0 - (cache_size as f64 / data_size as f64)
                }
            }
            AccessPattern::Strided(stride) => {
                let effective_size = data_size * stride;
                if effective_size <= cache_size {
                    0.05
                } else {
                    0.8
                }
            }
            AccessPattern::Random => {
                if data_size <= cache_size {
                    0.1
                } else {
                    0.95 // Very high miss rate for random access
                }
            }
            AccessPattern::Blocked(block_size) => {
                let block_data_size = block_size * block_size * 4; // Assume 4 bytes per element
                if block_data_size <= cache_size {
                    0.02
                } else {
                    0.3
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cache_aligned_allocator() {
        let allocator = CacheAlignedAllocator::new();
        let buffer = allocator
            .allocate::<f32>(1000)
            .expect("operation should succeed");

        assert_eq!(buffer.len(), 1000);
        assert!(buffer.is_cache_aligned());
    }

    #[test]
    fn test_access_pattern_optimizer() {
        let optimizer = AccessPatternOptimizer::new();

        let block_size = optimizer.optimal_block_size(4, CacheLevel::L1);
        assert!(block_size > 0);
        assert!(block_size.is_power_of_two());

        let streaming_chunk = optimizer.optimal_streaming_chunk_size(4);
        assert!(streaming_chunk > 0);
        assert!(streaming_chunk % (CACHE_LINE_SIZE / 4) == 0);
    }

    #[test]
    fn test_matrix_access_optimization() {
        let optimizer = AccessPatternOptimizer::new();
        let matrix = vec![1.0f32; 100];

        let indices = optimizer.optimize_matrix_access(&matrix, 10, 10, AccessPattern::Sequential);

        assert_eq!(indices.len(), matrix.len());
        assert_eq!(indices, (0..100).collect::<Vec<_>>());

        let blocked_indices =
            optimizer.optimize_matrix_access(&matrix, 10, 10, AccessPattern::Blocked(4));

        assert_eq!(blocked_indices.len(), matrix.len());
    }

    #[test]
    fn test_layout_transformer() {
        let transformer = LayoutTransformer::new();
        let input: Vec<f32> = (0..16).map(|i| i as f32).collect();

        let blocked = transformer.to_blocked_layout(&input, 4, 4, 2);
        assert_eq!(blocked.len(), input.len());

        let restored = transformer.from_blocked_layout(&blocked, 4, 4, 2);
        assert_eq!(restored, input);
    }

    #[test]
    fn test_cache_miss_estimation() {
        let transformer = LayoutTransformer::new();

        let miss_rate_seq =
            transformer.estimate_cache_miss_rate(1000, AccessPattern::Sequential, CacheLevel::L1);

        let miss_rate_random =
            transformer.estimate_cache_miss_rate(1000, AccessPattern::Random, CacheLevel::L1);

        assert!(miss_rate_seq < miss_rate_random);
    }

    #[test]
    fn test_bandwidth_calculation() {
        let optimizer = AccessPatternOptimizer::new();
        let bandwidth = optimizer.calculate_bandwidth_utilization(
            1024 * 1024 * 1024, // 1GB
            std::time::Duration::from_secs(1),
        );

        assert!((bandwidth - 1.0).abs() < 0.01); // Should be ~1 GB/s
    }
}

/// Calculate memory bandwidth in GB/s given bytes transferred and time elapsed
///
/// This is a standalone utility function for benchmarking purposes
pub fn calculate_memory_bandwidth(bytes: usize, elapsed: std::time::Duration) -> f64 {
    if elapsed.as_secs_f64() > 0.0 {
        bytes as f64 / elapsed.as_secs_f64() / (1024.0 * 1024.0 * 1024.0) // GB/s
    } else {
        0.0
    }
}