Skip to main content

trustformers_mobile/optimization/
memory_pool.rs

1//! Mobile Memory Pool Module
2//!
3//! Provides efficient memory pooling and management for mobile inference,
4//! reducing allocation overhead and memory fragmentation.
5
6use std::alloc::{alloc, dealloc, Layout};
7use std::collections::{BTreeMap, HashMap};
8use std::sync::{Arc, Mutex};
9use trustformers_core::error::{CoreError, Result};
10use trustformers_core::TrustformersError;
11
12/// Memory allocation strategy
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum AllocationStrategy {
15    /// First-fit allocation
16    FirstFit,
17    /// Best-fit allocation
18    BestFit,
19    /// Buddy system allocation
20    BuddySystem,
21    /// Size-class based allocation
22    SizeClass,
23}
24
25/// Memory pool configuration
26#[derive(Debug, Clone)]
27pub struct MemoryPoolConfig {
28    /// Maximum memory in bytes
29    pub max_memory_bytes: usize,
30    /// Allocation strategy
31    pub allocation_strategy: AllocationStrategy,
32    /// Enable defragmentation
33    pub enable_defragmentation: bool,
34}
35
36/// Memory allocation handle
37#[derive(Debug, Clone)]
38pub struct MemoryAllocation {
39    /// Unique allocation ID
40    pub id: usize,
41    /// Pointer to allocated memory
42    pub ptr: *mut u8,
43    /// Size of allocation
44    pub size: usize,
45    /// Alignment requirement
46    pub alignment: usize,
47    /// Allocation timestamp
48    pub timestamp: std::time::Instant,
49}
50
51unsafe impl Send for MemoryAllocation {}
52unsafe impl Sync for MemoryAllocation {}
53
54/// Mobile memory pool implementation
55#[derive(Debug)]
56pub struct MobileMemoryPool {
57    config: MemoryPoolConfig,
58    allocations: Arc<Mutex<HashMap<usize, MemoryAllocation>>>,
59    free_blocks: Arc<Mutex<BTreeMap<usize, Vec<FreeBlock>>>>,
60    total_allocated: Arc<Mutex<usize>>,
61    peak_allocated: Arc<Mutex<usize>>,
62    allocation_counter: Arc<Mutex<usize>>,
63    stats: Arc<Mutex<PoolStats>>,
64}
65
66/// Free memory block
67#[derive(Debug, Clone)]
68struct FreeBlock {
69    ptr: *mut u8,
70    size: usize,
71    alignment: usize,
72}
73
74unsafe impl Send for FreeBlock {}
75unsafe impl Sync for FreeBlock {}
76
77/// Memory pool statistics
78#[derive(Debug, Clone, Default)]
79pub struct PoolStats {
80    pub total_allocations: usize,
81    pub total_deallocations: usize,
82    pub current_allocations: usize,
83    pub current_memory_bytes: usize,
84    pub peak_memory_bytes: usize,
85    pub fragmentation_ratio: f32,
86    pub allocation_failures: usize,
87    pub defragmentation_count: usize,
88}
89
90impl MobileMemoryPool {
91    /// Create new memory pool
92    pub fn new(config: MemoryPoolConfig) -> Result<Self> {
93        if config.max_memory_bytes == 0 {
94            return Err(
95                TrustformersError::config_error("Memory pool size must be > 0", "new").into(),
96            );
97        }
98
99        let pool = Self {
100            config,
101            allocations: Arc::new(Mutex::new(HashMap::new())),
102            free_blocks: Arc::new(Mutex::new(BTreeMap::new())),
103            total_allocated: Arc::new(Mutex::new(0)),
104            peak_allocated: Arc::new(Mutex::new(0)),
105            allocation_counter: Arc::new(Mutex::new(0)),
106            stats: Arc::new(Mutex::new(PoolStats::default())),
107        };
108
109        // Pre-allocate some common sizes
110        pool.preallocate_common_sizes()?;
111
112        Ok(pool)
113    }
114
115    /// Allocate memory from pool
116    pub fn allocate(&self, size: usize, alignment: usize) -> Result<MemoryAllocation> {
117        let size = self.align_size(size, alignment);
118
119        // Check if allocation would exceed limit
120        {
121            let total = self.total_allocated.lock().unwrap_or_else(|p| p.into_inner());
122            if *total + size > self.config.max_memory_bytes {
123                let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
124                stats.allocation_failures += 1;
125                return Err(TrustformersError::hardware_error(
126                    &format!(
127                        "Memory pool exhausted: requested {}, available {}",
128                        size,
129                        self.config.max_memory_bytes - *total
130                    ),
131                    "allocate",
132                )
133                .into());
134            }
135        }
136
137        // Try to find a suitable free block
138        if let Some(allocation) = self.try_allocate_from_free(size, alignment)? {
139            return Ok(allocation);
140        }
141
142        // Allocate new memory
143        self.allocate_new(size, alignment)
144    }
145
146    /// Deallocate memory back to pool
147    pub fn deallocate(&self, allocation: MemoryAllocation) -> Result<()> {
148        // Remove from active allocations
149        {
150            let mut allocations = self.allocations.lock().unwrap_or_else(|p| p.into_inner());
151            allocations.remove(&allocation.id);
152        }
153
154        // Add to free blocks
155        {
156            let mut free_blocks = self.free_blocks.lock().unwrap_or_else(|p| p.into_inner());
157            let blocks = free_blocks.entry(allocation.size).or_default();
158            blocks.push(FreeBlock {
159                ptr: allocation.ptr,
160                size: allocation.size,
161                alignment: allocation.alignment,
162            });
163        }
164
165        // Update statistics
166        {
167            let mut total = self.total_allocated.lock().unwrap_or_else(|p| p.into_inner());
168            *total -= allocation.size;
169
170            let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
171            stats.total_deallocations += 1;
172            stats.current_allocations -= 1;
173            stats.current_memory_bytes = *total;
174        }
175
176        // Trigger defragmentation if needed
177        if self.config.enable_defragmentation {
178            self.maybe_defragment()?;
179        }
180
181        Ok(())
182    }
183
184    /// Get pool statistics
185    pub fn get_stats(&self) -> PoolStats {
186        self.stats.lock().unwrap_or_else(|p| p.into_inner()).clone()
187    }
188
189    /// Get memory usage ratio (0.0 to 1.0)
190    pub fn get_usage_ratio(&self) -> f32 {
191        let total_allocated = *self.total_allocated.lock().unwrap_or_else(|p| p.into_inner());
192        total_allocated as f32 / self.config.max_memory_bytes as f32
193    }
194
195    /// Get available memory in bytes
196    pub fn get_available_memory(&self) -> usize {
197        let total_allocated = *self.total_allocated.lock().unwrap_or_else(|p| p.into_inner());
198        self.config.max_memory_bytes - total_allocated
199    }
200
201    /// Get peak memory usage in bytes
202    pub fn get_peak_usage(&self) -> usize {
203        *self.peak_allocated.lock().unwrap_or_else(|p| p.into_inner())
204    }
205
206    /// Clear all allocations (dangerous!)
207    pub fn clear(&self) -> Result<()> {
208        // Deallocate all active allocations
209        let allocations: Vec<_> = {
210            let allocs = self.allocations.lock().unwrap_or_else(|p| p.into_inner());
211            allocs.values().cloned().collect()
212        };
213
214        for allocation in allocations {
215            unsafe {
216                let layout = Layout::from_size_align(allocation.size, allocation.alignment)
217                    .map_err(|e| TrustformersError::runtime_error(e.to_string()))?;
218                dealloc(allocation.ptr, layout);
219            }
220        }
221
222        // Clear all tracking
223        self.allocations.lock().unwrap_or_else(|p| p.into_inner()).clear();
224        self.free_blocks.lock().unwrap_or_else(|p| p.into_inner()).clear();
225        *self.total_allocated.lock().unwrap_or_else(|p| p.into_inner()) = 0;
226
227        // Reset stats
228        let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
229        stats.current_allocations = 0;
230        stats.current_memory_bytes = 0;
231
232        Ok(())
233    }
234
235    // Private helper methods
236
237    fn preallocate_common_sizes(&self) -> Result<()> {
238        // Pre-allocate some common tensor sizes for mobile
239        let common_sizes = [
240            1024,    // 1KB
241            4096,    // 4KB
242            16384,   // 16KB
243            65536,   // 64KB
244            262144,  // 256KB
245            1048576, // 1MB
246        ];
247
248        for &size in &common_sizes {
249            // Pre-allocate 2 blocks of each size
250            for _ in 0..2 {
251                if let Ok(alloc) = self.allocate_new_for_preallocation(size, 64) {
252                    // Immediately add to free list
253                    let mut free_blocks =
254                        self.free_blocks.lock().unwrap_or_else(|p| p.into_inner());
255                    let blocks = free_blocks.entry(size).or_default();
256                    blocks.push(FreeBlock {
257                        ptr: alloc.ptr,
258                        size: alloc.size,
259                        alignment: alloc.alignment,
260                    });
261                }
262            }
263        }
264
265        Ok(())
266    }
267
268    fn try_allocate_from_free(
269        &self,
270        size: usize,
271        alignment: usize,
272    ) -> Result<Option<MemoryAllocation>> {
273        let mut free_blocks = self.free_blocks.lock().unwrap_or_else(|p| p.into_inner());
274
275        match self.config.allocation_strategy {
276            AllocationStrategy::FirstFit => {
277                // Find first block that fits
278                for (&block_size, blocks) in free_blocks.iter_mut() {
279                    if block_size >= size && !blocks.is_empty() {
280                        if let Some(block) = blocks.iter().position(|b| b.alignment >= alignment) {
281                            let free_block = blocks.remove(block);
282                            return Ok(Some(self.create_allocation_from_block(free_block)?));
283                        }
284                    }
285                }
286            },
287            AllocationStrategy::BestFit => {
288                // Find smallest block that fits
289                let mut best_size = usize::MAX;
290                let mut best_key = None;
291
292                for (&block_size, blocks) in free_blocks.iter() {
293                    if block_size >= size
294                        && block_size < best_size
295                        && !blocks.is_empty()
296                        && blocks.iter().any(|b| b.alignment >= alignment)
297                    {
298                        best_size = block_size;
299                        best_key = Some(block_size);
300                    }
301                }
302
303                if let Some(key) = best_key {
304                    if let Some(blocks) = free_blocks.get_mut(&key) {
305                        if let Some(idx) = blocks.iter().position(|b| b.alignment >= alignment) {
306                            let block = blocks.remove(idx);
307                            return Ok(Some(self.create_allocation_from_block(block)?));
308                        }
309                    }
310                }
311            },
312            AllocationStrategy::BuddySystem => {
313                // Find power-of-2 sized block
314                let buddy_size = size.next_power_of_two();
315                if let Some(blocks) = free_blocks.get_mut(&buddy_size) {
316                    if let Some(idx) = blocks.iter().position(|b| b.alignment >= alignment) {
317                        let block = blocks.remove(idx);
318                        return Ok(Some(self.create_allocation_from_block(block)?));
319                    }
320                }
321            },
322            AllocationStrategy::SizeClass => {
323                // Use size classes (small, medium, large)
324                let size_class = self.get_size_class(size);
325                if let Some(blocks) = free_blocks.get_mut(&size_class) {
326                    if let Some(idx) = blocks.iter().position(|b| b.alignment >= alignment) {
327                        let block = blocks.remove(idx);
328                        return Ok(Some(self.create_allocation_from_block(block)?));
329                    }
330                }
331            },
332        }
333
334        Ok(None)
335    }
336
337    fn allocate_new(&self, size: usize, alignment: usize) -> Result<MemoryAllocation> {
338        let layout = Layout::from_size_align(size, alignment)
339            .map_err(|e| TrustformersError::runtime_error(e.to_string()))?;
340
341        let ptr = unsafe {
342            let ptr = alloc(layout);
343            if ptr.is_null() {
344                return Err(
345                    TrustformersError::runtime_error("Failed to allocate memory".into()).into(),
346                );
347            }
348            ptr
349        };
350
351        let id = {
352            let mut counter = self.allocation_counter.lock().unwrap_or_else(|p| p.into_inner());
353            *counter += 1;
354            *counter
355        };
356
357        let allocation = MemoryAllocation {
358            id,
359            ptr,
360            size,
361            alignment,
362            timestamp: std::time::Instant::now(),
363        };
364
365        // Track allocation
366        {
367            let mut allocations = self.allocations.lock().unwrap_or_else(|p| p.into_inner());
368            allocations.insert(id, allocation.clone());
369        }
370
371        // Update statistics
372        {
373            let mut total = self.total_allocated.lock().unwrap_or_else(|p| p.into_inner());
374            *total += size;
375
376            let mut peak = self.peak_allocated.lock().unwrap_or_else(|p| p.into_inner());
377            if *total > *peak {
378                *peak = *total;
379            }
380
381            let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
382            stats.total_allocations += 1;
383            stats.current_allocations += 1;
384            stats.current_memory_bytes = *total;
385            stats.peak_memory_bytes = *peak;
386        }
387
388        Ok(allocation)
389    }
390
391    /// Allocate memory for preallocation (doesn't count toward active allocations)
392    fn allocate_new_for_preallocation(
393        &self,
394        size: usize,
395        alignment: usize,
396    ) -> Result<MemoryAllocation> {
397        let layout = Layout::from_size_align(size, alignment)
398            .map_err(|e| TrustformersError::runtime_error(e.to_string()))?;
399
400        let ptr = unsafe {
401            let ptr = alloc(layout);
402            if ptr.is_null() {
403                return Err(
404                    TrustformersError::runtime_error("Failed to allocate memory".into()).into(),
405                );
406            }
407            ptr
408        };
409
410        let id = {
411            let mut counter = self.allocation_counter.lock().unwrap_or_else(|p| p.into_inner());
412            *counter += 1;
413            *counter
414        };
415
416        let allocation = MemoryAllocation {
417            id,
418            ptr,
419            size,
420            alignment,
421            timestamp: std::time::Instant::now(),
422        };
423
424        // Don't track in active allocations since this goes directly to free list
425        // No stats update for preallocation
426
427        Ok(allocation)
428    }
429
430    fn create_allocation_from_block(&self, block: FreeBlock) -> Result<MemoryAllocation> {
431        let id = {
432            let mut counter = self.allocation_counter.lock().unwrap_or_else(|p| p.into_inner());
433            *counter += 1;
434            *counter
435        };
436
437        let allocation = MemoryAllocation {
438            id,
439            ptr: block.ptr,
440            size: block.size,
441            alignment: block.alignment,
442            timestamp: std::time::Instant::now(),
443        };
444
445        // Track allocation
446        {
447            let mut allocations = self.allocations.lock().unwrap_or_else(|p| p.into_inner());
448            allocations.insert(id, allocation.clone());
449        }
450
451        // Update statistics
452        {
453            let mut total = self.total_allocated.lock().unwrap_or_else(|p| p.into_inner());
454            *total += block.size;
455
456            let mut peak = self.peak_allocated.lock().unwrap_or_else(|p| p.into_inner());
457            if *total > *peak {
458                *peak = *total;
459            }
460
461            let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
462            stats.total_allocations += 1;
463            stats.current_allocations += 1;
464            stats.current_memory_bytes = *total;
465            stats.peak_memory_bytes = *peak;
466        }
467
468        Ok(allocation)
469    }
470
471    fn maybe_defragment(&self) -> Result<()> {
472        let fragmentation = self.calculate_fragmentation();
473
474        if fragmentation > 0.3 {
475            // High fragmentation, trigger defragmentation
476            self.defragment()?;
477        }
478
479        Ok(())
480    }
481
482    fn defragment(&self) -> Result<()> {
483        // Simple defragmentation: merge adjacent free blocks
484        let mut free_blocks = self.free_blocks.lock().unwrap_or_else(|p| p.into_inner());
485
486        for (_, blocks) in free_blocks.iter_mut() {
487            if blocks.len() > 1 {
488                // Sort by pointer address
489                blocks.sort_by_key(|b| b.ptr as usize);
490
491                // Merge adjacent blocks
492                let mut merged = Vec::new();
493                let mut current = blocks[0].clone();
494
495                for block in &blocks[1..] {
496                    let current_end = current.ptr as usize + current.size;
497                    let block_start = block.ptr as usize;
498
499                    if current_end == block_start && current.alignment == block.alignment {
500                        // Adjacent blocks, merge them
501                        current.size += block.size;
502                    } else {
503                        // Non-adjacent, save current and start new
504                        merged.push(current);
505                        current = block.clone();
506                    }
507                }
508
509                merged.push(current);
510                *blocks = merged;
511            }
512        }
513
514        // Update stats
515        {
516            let mut stats = self.stats.lock().unwrap_or_else(|p| p.into_inner());
517            stats.defragmentation_count += 1;
518            stats.fragmentation_ratio = self.calculate_fragmentation();
519        }
520
521        Ok(())
522    }
523
524    fn calculate_fragmentation(&self) -> f32 {
525        let free_blocks = self.free_blocks.lock().unwrap_or_else(|p| p.into_inner());
526
527        let total_free_blocks: usize = free_blocks.values().map(|blocks| blocks.len()).sum();
528
529        let total_free_memory: usize = free_blocks
530            .values()
531            .flat_map(|blocks| blocks.iter())
532            .map(|block| block.size)
533            .sum();
534
535        if total_free_memory == 0 {
536            return 0.0;
537        }
538
539        // Fragmentation = 1 - (largest_free_block / total_free_memory)
540        let largest_free_block = free_blocks
541            .values()
542            .flat_map(|blocks| blocks.iter())
543            .map(|block| block.size)
544            .max()
545            .unwrap_or(0);
546
547        1.0 - (largest_free_block as f32 / total_free_memory as f32)
548    }
549
550    fn align_size(&self, size: usize, alignment: usize) -> usize {
551        (size + alignment - 1) & !(alignment - 1)
552    }
553
554    fn get_size_class(&self, size: usize) -> usize {
555        // Define size classes for mobile
556        match size {
557            0..=1024 => 1024,         // 1KB
558            1025..=16384 => 16384,    // 16KB
559            16385..=262144 => 262144, // 256KB
560            _ => 1048576,             // 1MB
561        }
562    }
563}
564
565impl Clone for MobileMemoryPool {
566    fn clone(&self) -> Self {
567        Self {
568            config: self.config.clone(),
569            allocations: Arc::clone(&self.allocations),
570            free_blocks: Arc::clone(&self.free_blocks),
571            total_allocated: Arc::clone(&self.total_allocated),
572            peak_allocated: Arc::clone(&self.peak_allocated),
573            allocation_counter: Arc::clone(&self.allocation_counter),
574            stats: Arc::clone(&self.stats),
575        }
576    }
577}
578
579/// Scoped allocation for automatic cleanup
580pub struct ScopedAllocation<'a> {
581    pool: &'a MobileMemoryPool,
582    allocation: Option<MemoryAllocation>,
583}
584
585impl<'a> ScopedAllocation<'a> {
586    /// Create new scoped allocation
587    pub fn new(pool: &'a MobileMemoryPool, size: usize, alignment: usize) -> Result<Self> {
588        let allocation = pool.allocate(size, alignment)?;
589        Ok(Self {
590            pool,
591            allocation: Some(allocation),
592        })
593    }
594
595    /// Get pointer to allocated memory
596    pub fn ptr(&self) -> *mut u8 {
597        self.allocation
598            .as_ref()
599            .map_or(std::ptr::null_mut(), |allocation| allocation.ptr)
600    }
601
602    /// Get size of allocation
603    pub fn size(&self) -> usize {
604        self.allocation.as_ref().map_or(0, |allocation| allocation.size)
605    }
606}
607
608impl<'a> Drop for ScopedAllocation<'a> {
609    fn drop(&mut self) {
610        if let Some(allocation) = self.allocation.take() {
611            let _ = self.pool.deallocate(allocation);
612        }
613    }
614}
615
616#[cfg(test)]
617mod tests {
618    use super::*;
619
620    #[test]
621    fn test_memory_pool_creation() {
622        let config = MemoryPoolConfig {
623            max_memory_bytes: 10 * 1024 * 1024, // 10MB
624            allocation_strategy: AllocationStrategy::FirstFit,
625            enable_defragmentation: true,
626        };
627
628        let pool = MobileMemoryPool::new(config).expect("Failed to create pool");
629        let stats = pool.get_stats();
630
631        assert_eq!(stats.current_allocations, 0);
632        assert_eq!(stats.current_memory_bytes, 0);
633    }
634
635    #[test]
636    fn test_allocation_deallocation() {
637        let config = MemoryPoolConfig {
638            max_memory_bytes: 10 * 1024 * 1024,
639            allocation_strategy: AllocationStrategy::BestFit,
640            enable_defragmentation: false,
641        };
642
643        let pool = MobileMemoryPool::new(config).expect("Failed to create pool");
644
645        // Allocate memory
646        let alloc1 = pool.allocate(1024, 64).expect("Allocation failed");
647        assert_eq!(alloc1.size, 1024);
648        assert!(!alloc1.ptr.is_null());
649
650        let stats = pool.get_stats();
651        assert_eq!(stats.current_allocations, 1);
652
653        // Deallocate
654        pool.deallocate(alloc1).expect("Deallocation failed");
655
656        let stats = pool.get_stats();
657        assert_eq!(stats.current_allocations, 0);
658    }
659
660    #[test]
661    fn test_scoped_allocation() {
662        let config = MemoryPoolConfig {
663            max_memory_bytes: 10 * 1024 * 1024,
664            allocation_strategy: AllocationStrategy::FirstFit,
665            enable_defragmentation: false,
666        };
667
668        let pool = MobileMemoryPool::new(config).expect("Failed to create pool");
669
670        {
671            let scoped = ScopedAllocation::new(&pool, 2048, 128).expect("Scoped allocation failed");
672            assert!(!scoped.ptr().is_null());
673            assert_eq!(scoped.size(), 2048);
674
675            let stats = pool.get_stats();
676            assert_eq!(stats.current_allocations, 1);
677        }
678
679        // Should be deallocated after scope
680        let stats = pool.get_stats();
681        assert_eq!(stats.current_allocations, 0);
682    }
683
684    #[test]
685    fn test_memory_limit() {
686        let config = MemoryPoolConfig {
687            max_memory_bytes: 1024, // Only 1KB
688            allocation_strategy: AllocationStrategy::FirstFit,
689            enable_defragmentation: false,
690        };
691
692        let pool = MobileMemoryPool::new(config).expect("Failed to create pool");
693
694        // This should succeed
695        let alloc1 = pool.allocate(512, 64).expect("Allocation failed");
696
697        // This should fail (would exceed limit)
698        let result = pool.allocate(1024, 64);
699        assert!(result.is_err());
700
701        // Deallocate first allocation
702        pool.deallocate(alloc1).expect("Deallocation failed");
703
704        // Now the large allocation should succeed
705        let alloc2 = pool.allocate(1024, 64).expect("Allocation failed");
706        assert_eq!(alloc2.size, 1024);
707    }
708}