1use crate::memory_profiler::allocation::{AccessPattern, AccessType};
11use parking_lot::{Mutex, RwLock};
12use std::collections::{HashMap, VecDeque};
13use std::sync::Arc;
14use std::time::{Duration, Instant};
15
16#[derive(Debug)]
21pub struct AccessPatternAnalyzer {
22 active_patterns: Arc<RwLock<HashMap<usize, AccessPattern>>>,
24
25 pattern_classifications: Arc<Mutex<HashMap<usize, PatternClassification>>>,
27
28 pattern_statistics: Arc<Mutex<PatternStatistics>>,
30
31 optimization_suggestions: Arc<Mutex<Vec<PatternOptimizationSuggestion>>>,
33
34 config: PatternAnalysisConfig,
36
37 prediction_models: Arc<Mutex<HashMap<usize, AccessPredictionModel>>>,
39}
40
41#[derive(Debug, Clone)]
45pub struct PatternClassification {
46 pub primary_type: PatternType,
48
49 pub secondary_types: Vec<PatternType>,
51
52 pub confidence: f64,
54
55 pub classified_at: Instant,
57
58 pub stability: f64,
60
61 pub prediction: AccessPrediction,
63}
64
65#[derive(Debug, Clone, PartialEq)]
69pub enum PatternType {
70 Sequential {
72 stride: usize,
73 direction: AccessDirection,
74 },
75
76 Random {
78 entropy: f64,
79 distribution: AccessDistribution,
80 },
81
82 Streaming {
84 block_size: usize,
85 bandwidth_intensive: bool,
86 },
87
88 TemporalClustering {
90 cluster_size: usize,
91 access_frequency: f64,
92 },
93
94 SpatialClustering {
96 locality_radius: usize,
97 cluster_density: f64,
98 },
99
100 Strided {
102 stride_length: usize,
103 stride_consistency: f64,
104 },
105
106 CacheFriendly {
108 cache_line_utilization: f64,
109 prefetch_effectiveness: f64,
110 },
111
112 CacheHostile {
114 cache_miss_rate: f64,
115 thrashing_likelihood: f64,
116 },
117
118 ComputeIntensive {
120 compute_to_memory_ratio: f64,
121 arithmetic_intensity: f64,
122 },
123
124 BandwidthBound {
126 bandwidth_utilization: f64,
127 transfer_efficiency: f64,
128 },
129
130 Coalescing {
132 coalescing_factor: f64,
133 efficiency: f64,
134 },
135
136 Prefetch {
138 prefetch_distance: usize,
139 hit_rate: f64,
140 },
141}
142
143#[derive(Debug, Clone, PartialEq, Eq, Hash)]
145pub enum AccessDirection {
146 Forward,
147 Backward,
148 Bidirectional,
149}
150
151#[derive(Debug, Clone, PartialEq, Eq, Hash)]
153pub enum AccessDistribution {
154 Uniform,
155 Normal,
156 Exponential,
157 PowerLaw,
158 Bimodal,
159}
160
161#[derive(Debug, Clone)]
165pub struct AccessPrediction {
166 pub next_accesses: Vec<PredictedAccess>,
168
169 pub prediction_confidence: f64,
171
172 pub time_horizon: Duration,
174
175 pub prefetch_candidates: Vec<usize>,
177
178 pub cache_behavior: CacheBehaviorPrediction,
180}
181
182#[derive(Debug, Clone)]
184pub struct PredictedAccess {
185 pub address: usize,
187
188 pub access_type: AccessType,
190
191 pub size: usize,
193
194 pub confidence: f64,
196
197 pub estimated_time: Duration,
199}
200
201#[derive(Debug, Clone)]
203pub struct CacheBehaviorPrediction {
204 pub l1_hit_rate: f64,
206
207 pub l2_hit_rate: f64,
209
210 pub tlb_hit_rate: f64,
212
213 pub bandwidth_usage: f64,
215
216 pub cache_warming: Vec<CacheWarmingRecommendation>,
218}
219
220#[derive(Debug, Clone)]
222pub struct CacheWarmingRecommendation {
223 pub address_range: (usize, usize),
225
226 pub priority: f64,
228
229 pub estimated_benefit: f64,
231
232 pub target_cache_level: CacheLevel,
234}
235
236#[derive(Debug, Clone, PartialEq, Eq)]
238pub enum CacheLevel {
239 L1,
240 L2,
241 L3,
242 Memory,
243}
244
245#[derive(Debug, Clone)]
249pub struct PatternOptimizationSuggestion {
250 pub target: usize,
252
253 pub optimization_type: OptimizationType,
255
256 pub suggestion: String,
258
259 pub expected_improvement: f64,
261
262 pub complexity: OptimizationComplexity,
264
265 pub prerequisites: Vec<String>,
267
268 pub timeline: OptimizationTimeline,
270}
271
272#[derive(Debug, Clone)]
274pub enum OptimizationType {
275 DataLayoutOptimization {
277 suggested_layout: DataLayout,
278 memory_savings: usize,
279 },
280
281 PrefetchingOptimization {
283 prefetch_distance: usize,
284 prefetch_pattern: PrefetchPattern,
285 },
286
287 CacheOptimization {
289 cache_strategy: CacheStrategy,
290 target_cache_level: CacheLevel,
291 },
292
293 MemoryPooling {
295 pool_size: usize,
296 allocation_strategy: AllocationStrategy,
297 },
298
299 AccessTransformation {
301 transformation_type: TransformationType,
302 expected_locality_improvement: f64,
303 },
304
305 BandwidthOptimization {
307 batching_strategy: BatchingStrategy,
308 transfer_optimization: TransferOptimization,
309 },
310}
311
312#[derive(Debug, Clone)]
314pub enum DataLayout {
315 ArrayOfStructs,
316 StructOfArrays,
317 Columnar,
318 Tiled,
319 Compressed,
320 Interleaved,
321}
322
323#[derive(Debug, Clone)]
325pub enum PrefetchPattern {
326 Sequential,
327 Strided,
328 Adaptive,
329 Predictive,
330}
331
332#[derive(Debug, Clone)]
334pub enum CacheStrategy {
335 WriteThrough,
336 WriteBack,
337 WriteAround,
338 DirectMapped,
339 FullyAssociative,
340 SetAssociative { ways: usize },
341}
342
343#[derive(Debug, Clone)]
345pub enum AllocationStrategy {
346 BestFit,
347 FirstFit,
348 NextFit,
349 BuddySystem,
350 Slab,
351 Pool,
352}
353
354#[derive(Debug, Clone)]
356pub enum TransformationType {
357 Blocking,
358 Tiling,
359 LoopReordering,
360 DataReorganization,
361 TemporalBlocking,
362 SpatialBlocking,
363}
364
365#[derive(Debug, Clone)]
367pub enum BatchingStrategy {
368 TimeBased,
369 SizeBased,
370 AdaptiveBatching,
371 PriorityBatching,
372}
373
374#[derive(Debug, Clone)]
376pub enum TransferOptimization {
377 Coalescing,
378 Vectorization,
379 PipelinedTransfers,
380 AsynchronousTransfers,
381}
382
383#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
385pub enum OptimizationComplexity {
386 Low,
387 Medium,
388 High,
389 VeryHigh,
390}
391
392#[derive(Debug, Clone)]
394pub enum OptimizationTimeline {
395 Immediate,
396 ShortTerm, MediumTerm, LongTerm, }
400
401#[derive(Debug, Default, Clone)]
405pub struct PatternStatistics {
406 pub total_patterns: u64,
408
409 pub pattern_distribution: Vec<(String, u64)>,
411
412 pub average_confidence: f64,
414
415 pub cache_efficiency: CacheEfficiencyStats,
417
418 pub temporal_analysis: TemporalAnalysisStats,
420
421 pub spatial_analysis: SpatialAnalysisStats,
423
424 pub performance_impact: PerformanceImpactStats,
426}
427
428#[derive(Debug, Default, Clone)]
430pub struct CacheEfficiencyStats {
431 pub overall_hit_rate: f64,
433
434 pub l1_stats: CacheLevelStats,
436
437 pub l2_stats: CacheLevelStats,
439
440 pub tlb_stats: CacheLevelStats,
442
443 pub cache_friendly_percentage: f64,
445}
446
447#[derive(Debug, Default, Clone)]
449pub struct CacheLevelStats {
450 pub hit_rate: f64,
452
453 pub miss_rate: f64,
455
456 pub avg_latency: Duration,
458
459 pub bandwidth_utilization: f64,
461}
462
463#[derive(Debug, Default, Clone)]
465pub struct TemporalAnalysisStats {
466 pub avg_temporal_locality: f64,
468
469 pub hot_spots: Vec<TemporalHotSpot>,
471
472 pub frequency_distribution: Vec<(f64, u64)>, pub clustering_strength: f64,
477}
478
479#[derive(Debug, Clone)]
481pub struct TemporalHotSpot {
482 pub address_range: (usize, usize),
484
485 pub frequency: f64,
487
488 pub duration: Duration,
490
491 pub peak_time: Instant,
493}
494
495#[derive(Debug, Default, Clone)]
497pub struct SpatialAnalysisStats {
498 pub avg_spatial_locality: f64,
500
501 pub stride_patterns: Vec<StridePattern>,
503
504 pub locality_clusters: Vec<LocalityCluster>,
506
507 pub fragmentation_impact: f64,
509}
510
511#[derive(Debug, Clone)]
513pub struct StridePattern {
514 pub stride_length: usize,
516
517 pub frequency: u64,
519
520 pub consistency: f64,
522
523 pub memory_range: (usize, usize),
525}
526
527#[derive(Debug, Clone)]
529pub struct LocalityCluster {
530 pub center: usize,
532
533 pub radius: usize,
535
536 pub density: f64,
538
539 pub lifetime: Duration,
541}
542
543#[derive(Debug, Default, Clone)]
545pub struct PerformanceImpactStats {
546 pub bandwidth_efficiency: f64,
548
549 pub cache_miss_penalty: Duration,
551
552 pub contention_level: f64,
554
555 pub optimization_potential: f64,
557}
558
559#[derive(Debug, Clone)]
561pub struct PatternAnalysisConfig {
562 pub min_pattern_length: usize,
564
565 pub analysis_window: Duration,
567
568 pub confidence_threshold: f64,
570
571 pub enable_prediction: bool,
573
574 pub enable_optimization_suggestions: bool,
576
577 pub max_tracked_patterns: usize,
579
580 pub classification_sensitivity: f64,
582
583 pub cache_analysis_depth: usize,
585}
586
587#[derive(Debug)]
591pub struct AccessPredictionModel {
592 access_history: VecDeque<AccessEvent>,
594
595 pattern_state: PatternRecognitionState,
597
598 accuracy_tracker: AccuracyTracker,
600
601 model_params: PredictionModelParams,
603}
604
605#[derive(Debug, Clone)]
607pub struct AccessEvent {
608 pub address: usize,
610
611 pub access_type: AccessType,
613
614 pub size: usize,
616
617 pub timestamp: Instant,
619
620 pub context: AccessContext,
622}
623
624#[derive(Debug, Clone)]
626pub struct AccessContext {
627 pub thread_id: u64,
629
630 pub operation: String,
632
633 pub allocation_id: Option<usize>,
635}
636
637#[derive(Debug)]
639struct PatternRecognitionState {
640 current_hypothesis: Option<PatternType>,
642
643 transition_probabilities: HashMap<PatternType, HashMap<PatternType, f64>>,
645
646 confidence: f64,
648}
649
650#[derive(Debug)]
652struct AccuracyTracker {
653 correct_predictions: u64,
655
656 total_predictions: u64,
658
659 recent_accuracy: VecDeque<bool>,
661
662 accuracy_by_pattern: HashMap<PatternType, (u64, u64)>, }
665
666#[derive(Debug, Clone)]
668struct PredictionModelParams {
669 history_window: usize,
671
672 prediction_horizon: Duration,
674
675 learning_rate: f64,
677
678 pattern_threshold: f64,
680}
681
682fn pattern_type_name(pattern: &PatternType) -> String {
684 match pattern {
685 PatternType::Sequential { .. } => "Sequential".to_string(),
686 PatternType::Random { .. } => "Random".to_string(),
687 PatternType::Streaming { .. } => "Streaming".to_string(),
688 PatternType::TemporalClustering { .. } => "TemporalClustering".to_string(),
689 PatternType::SpatialClustering { .. } => "SpatialClustering".to_string(),
690 PatternType::Strided { .. } => "Strided".to_string(),
691 PatternType::Coalescing { .. } => "Coalescing".to_string(),
692 PatternType::Prefetch { .. } => "Prefetch".to_string(),
693 PatternType::CacheFriendly { .. } => "CacheFriendly".to_string(),
694 PatternType::CacheHostile { .. } => "CacheHostile".to_string(),
695 PatternType::ComputeIntensive { .. } => "ComputeIntensive".to_string(),
696 PatternType::BandwidthBound { .. } => "BandwidthBound".to_string(),
697 }
698}
699
700impl AccessPatternAnalyzer {
701 pub fn new(config: PatternAnalysisConfig) -> Self {
703 Self {
704 active_patterns: Arc::new(RwLock::new(HashMap::new())),
705 pattern_classifications: Arc::new(Mutex::new(HashMap::new())),
706 pattern_statistics: Arc::new(Mutex::new(PatternStatistics::default())),
707 optimization_suggestions: Arc::new(Mutex::new(Vec::new())),
708 config,
709 prediction_models: Arc::new(Mutex::new(HashMap::new())),
710 }
711 }
712
713 pub fn analyze_pattern(
715 &self,
716 address: usize,
717 pattern: &AccessPattern,
718 ) -> Option<PatternClassification> {
719 if pattern.access_times.len() < self.config.min_pattern_length {
720 return None;
721 }
722
723 let classification = self.classify_pattern(pattern);
724
725 if classification.confidence >= self.config.confidence_threshold {
726 self.pattern_classifications
728 .lock()
729 .insert(address, classification.clone());
730
731 self.update_statistics(&classification);
733
734 if self.config.enable_optimization_suggestions {
736 self.generate_optimization_suggestions(address, &classification);
737 }
738
739 if self.config.enable_prediction {
741 self.update_prediction_model(address, pattern);
742 }
743
744 Some(classification)
745 } else {
746 None
747 }
748 }
749
750 fn classify_pattern(&self, pattern: &AccessPattern) -> PatternClassification {
752 let mut confidence_scores: Vec<(PatternType, f64)> = Vec::new();
753
754 confidence_scores.push((
756 PatternType::Sequential {
757 stride: self.estimate_stride(pattern),
758 direction: self.determine_direction(pattern),
759 },
760 pattern.sequential_score,
761 ));
762
763 confidence_scores.push((
765 PatternType::Random {
766 entropy: self.calculate_entropy(pattern),
767 distribution: self.determine_distribution(pattern),
768 },
769 pattern.random_score,
770 ));
771
772 let streaming_score = self.analyze_streaming(pattern);
774 if streaming_score > 0.3 {
775 confidence_scores.push((
776 PatternType::Streaming {
777 block_size: self.estimate_block_size(pattern),
778 bandwidth_intensive: streaming_score > 0.7,
779 },
780 streaming_score,
781 ));
782 }
783
784 let temporal_score = pattern.temporal_locality;
786 if temporal_score > 0.5 {
787 confidence_scores.push((
788 PatternType::TemporalClustering {
789 cluster_size: self.estimate_cluster_size(pattern),
790 access_frequency: pattern.frequency,
791 },
792 temporal_score,
793 ));
794 }
795
796 let spatial_score = pattern.spatial_locality;
798 if spatial_score > 0.5 {
799 confidence_scores.push((
800 PatternType::SpatialClustering {
801 locality_radius: self.estimate_locality_radius(pattern),
802 cluster_density: spatial_score,
803 },
804 spatial_score,
805 ));
806 }
807
808 let primary_index = confidence_scores
810 .iter()
811 .enumerate()
812 .max_by(|(_, (_, a)), (_, (_, b))| {
813 a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
814 })
815 .map(|(i, _)| i)
816 .unwrap_or(0);
817
818 let (primary_type, confidence) = if primary_index < confidence_scores.len() {
819 confidence_scores[primary_index].clone()
820 } else {
821 (
822 PatternType::Random {
823 entropy: 1.0,
824 distribution: AccessDistribution::Uniform,
825 },
826 0.0,
827 )
828 };
829
830 let secondary_types: Vec<PatternType> = confidence_scores
832 .into_iter()
833 .enumerate()
834 .filter(|(i, (_, score))| *i != primary_index && *score > 0.3)
835 .map(|(_, (pattern, _))| pattern)
836 .collect();
837
838 let stability = self.calculate_pattern_stability(pattern);
840
841 let prediction = self.generate_access_prediction(pattern, &primary_type);
843
844 PatternClassification {
845 primary_type,
846 secondary_types,
847 confidence,
848 classified_at: Instant::now(),
849 stability,
850 prediction,
851 }
852 }
853
854 fn estimate_stride(&self, pattern: &AccessPattern) -> usize {
856 if pattern.access_sizes.len() < 2 {
857 return 0;
858 }
859
860 let mut strides = Vec::new();
861 let access_sizes_vec: Vec<_> = pattern.access_sizes.iter().collect();
862 for window in access_sizes_vec.windows(2) {
863 if window[1] > window[0] {
864 strides.push(window[1] - window[0]);
865 }
866 }
867
868 if strides.is_empty() {
869 0
870 } else {
871 strides.sort_unstable();
873 strides[strides.len() / 2]
874 }
875 }
876
877 fn determine_direction(&self, pattern: &AccessPattern) -> AccessDirection {
879 if pattern.access_sizes.len() < 3 {
880 return AccessDirection::Forward;
881 }
882
883 let mut forward_count = 0;
884 let mut backward_count = 0;
885
886 let access_sizes_vec: Vec<_> = pattern.access_sizes.iter().collect();
887 for window in access_sizes_vec.windows(2) {
888 if window[1] > window[0] {
889 forward_count += 1;
890 } else if window[1] < window[0] {
891 backward_count += 1;
892 }
893 }
894
895 let total = forward_count + backward_count;
896 if total == 0 {
897 return AccessDirection::Forward;
898 }
899
900 let forward_ratio = forward_count as f64 / total as f64;
901
902 if forward_ratio > 0.8 {
903 AccessDirection::Forward
904 } else if forward_ratio < 0.2 {
905 AccessDirection::Backward
906 } else {
907 AccessDirection::Bidirectional
908 }
909 }
910
911 fn calculate_entropy(&self, pattern: &AccessPattern) -> f64 {
913 if pattern.access_sizes.is_empty() {
914 return 0.0;
915 }
916
917 let mut freq_map = HashMap::new();
919 for &size in &pattern.access_sizes {
920 *freq_map.entry(size).or_insert(0) += 1;
921 }
922
923 let total = pattern.access_sizes.len() as f64;
924 let mut entropy = 0.0;
925
926 for count in freq_map.values() {
927 let p = *count as f64 / total;
928 if p > 0.0 {
929 entropy -= p * p.log2();
930 }
931 }
932
933 entropy
934 }
935
936 fn determine_distribution(&self, _pattern: &AccessPattern) -> AccessDistribution {
938 AccessDistribution::Uniform
941 }
942
943 fn analyze_streaming(&self, pattern: &AccessPattern) -> f64 {
945 if pattern.access_sizes.len() < 3 {
946 return 0.0;
947 }
948
949 let avg_size =
951 pattern.access_sizes.iter().sum::<usize>() as f64 / pattern.access_sizes.len() as f64;
952 let size_consistency = self.calculate_size_consistency(pattern);
953
954 if avg_size > 1024.0 && size_consistency > 0.8 {
956 (avg_size.log2() / 20.0).min(1.0) * size_consistency
957 } else {
958 0.0
959 }
960 }
961
962 fn calculate_size_consistency(&self, pattern: &AccessPattern) -> f64 {
964 if pattern.access_sizes.len() < 2 {
965 return 1.0;
966 }
967
968 let avg_size =
969 pattern.access_sizes.iter().sum::<usize>() as f64 / pattern.access_sizes.len() as f64;
970 let variance = pattern
971 .access_sizes
972 .iter()
973 .map(|&size| (size as f64 - avg_size).powi(2))
974 .sum::<f64>()
975 / pattern.access_sizes.len() as f64;
976
977 let std_dev = variance.sqrt();
978 let coefficient_of_variation = if avg_size > 0.0 {
979 std_dev / avg_size
980 } else {
981 0.0
982 };
983
984 (1.0 - coefficient_of_variation).max(0.0)
986 }
987
988 fn estimate_block_size(&self, pattern: &AccessPattern) -> usize {
990 if pattern.access_sizes.is_empty() {
991 return 0;
992 }
993
994 let mut sizes = pattern.access_sizes.iter().cloned().collect::<Vec<_>>();
996 sizes.sort_unstable();
997 sizes[sizes.len() / 2]
998 }
999
1000 fn estimate_cluster_size(&self, pattern: &AccessPattern) -> usize {
1002 (pattern.access_times.len() as f64 * pattern.temporal_locality).round() as usize
1005 }
1006
1007 fn estimate_locality_radius(&self, pattern: &AccessPattern) -> usize {
1009 if pattern.access_sizes.len() < 2 {
1010 return 0;
1011 }
1012
1013 let mut distances = Vec::new();
1015 let access_sizes_vec: Vec<_> = pattern.access_sizes.iter().collect();
1016 for window in access_sizes_vec.windows(2) {
1017 let distance = if window[1] > window[0] {
1018 window[1] - window[0]
1019 } else {
1020 window[0] - window[1]
1021 };
1022 distances.push(distance);
1023 }
1024
1025 if distances.is_empty() {
1026 0
1027 } else {
1028 distances.iter().sum::<usize>() / distances.len()
1029 }
1030 }
1031
1032 fn calculate_pattern_stability(&self, pattern: &AccessPattern) -> f64 {
1034 if pattern.access_times.len() < 5 {
1035 return 0.5; }
1037
1038 let mut intervals = Vec::new();
1040 let access_times_vec: Vec<_> = pattern.access_times.iter().collect();
1041 for window in access_times_vec.windows(2) {
1042 intervals.push(window[1].duration_since(*window[0]).as_nanos() as f64);
1043 }
1044
1045 if intervals.is_empty() {
1046 return 0.5;
1047 }
1048
1049 let avg_interval = intervals.iter().sum::<f64>() / intervals.len() as f64;
1050 let variance = intervals
1051 .iter()
1052 .map(|&interval| (interval - avg_interval).powi(2))
1053 .sum::<f64>()
1054 / intervals.len() as f64;
1055
1056 let std_dev = variance.sqrt();
1057 let coefficient_of_variation = if avg_interval > 0.0 {
1058 std_dev / avg_interval
1059 } else {
1060 0.0
1061 };
1062
1063 (1.0f64 - coefficient_of_variation.min(1.0f64)).max(0.0f64)
1065 }
1066
1067 fn generate_access_prediction(
1069 &self,
1070 pattern: &AccessPattern,
1071 pattern_type: &PatternType,
1072 ) -> AccessPrediction {
1073 let mut next_accesses = Vec::new();
1074 let mut prefetch_candidates = Vec::new();
1075
1076 match pattern_type {
1077 PatternType::Sequential { stride, direction } => {
1078 if let (Some(&last_size), Some(&_last_time)) =
1079 (pattern.access_sizes.back(), pattern.access_times.back())
1080 {
1081 let next_size = match direction {
1082 AccessDirection::Forward => last_size + stride,
1083 AccessDirection::Backward => last_size.saturating_sub(*stride),
1084 AccessDirection::Bidirectional => last_size + stride, };
1086
1087 next_accesses.push(PredictedAccess {
1088 address: next_size, access_type: AccessType::Read, size: last_size,
1091 confidence: 0.8,
1092 estimated_time: Duration::from_millis(1),
1093 });
1094
1095 for i in 1..=4 {
1097 let prefetch_addr = match direction {
1098 AccessDirection::Forward => next_size + (stride * i),
1099 AccessDirection::Backward => next_size.saturating_sub(stride * i),
1100 AccessDirection::Bidirectional => next_size + (stride * i),
1101 };
1102 prefetch_candidates.push(prefetch_addr);
1103 }
1104 }
1105 }
1106 PatternType::Streaming { block_size, .. } => {
1107 if let Some(&last_size) = pattern.access_sizes.back() {
1108 next_accesses.push(PredictedAccess {
1109 address: last_size + block_size,
1110 access_type: AccessType::Read,
1111 size: *block_size,
1112 confidence: 0.7,
1113 estimated_time: Duration::from_millis(2),
1114 });
1115 }
1116 }
1117 _ => {
1118 if let Some(&last_size) = pattern.access_sizes.back() {
1120 next_accesses.push(PredictedAccess {
1121 address: last_size,
1122 access_type: AccessType::Read,
1123 size: last_size,
1124 confidence: 0.3,
1125 estimated_time: Duration::from_millis(5),
1126 });
1127 }
1128 }
1129 }
1130
1131 AccessPrediction {
1132 next_accesses,
1133 prediction_confidence: 0.6, time_horizon: Duration::from_millis(100),
1135 prefetch_candidates,
1136 cache_behavior: CacheBehaviorPrediction {
1137 l1_hit_rate: 0.9,
1138 l2_hit_rate: 0.7,
1139 tlb_hit_rate: 0.95,
1140 bandwidth_usage: 0.5,
1141 cache_warming: Vec::new(),
1142 },
1143 }
1144 }
1145
1146 fn update_statistics(&self, classification: &PatternClassification) {
1148 let mut stats = self.pattern_statistics.lock();
1149 stats.total_patterns += 1;
1150
1151 let pattern_name = pattern_type_name(&classification.primary_type);
1153 if let Some((_, count)) = stats
1154 .pattern_distribution
1155 .iter_mut()
1156 .find(|(name, _)| name == &pattern_name)
1157 {
1158 *count += 1;
1159 } else {
1160 stats.pattern_distribution.push((pattern_name, 1));
1161 }
1162
1163 let total_confidence = stats.average_confidence * (stats.total_patterns - 1) as f64
1165 + classification.confidence;
1166 stats.average_confidence = total_confidence / stats.total_patterns as f64;
1167 }
1168
1169 fn generate_optimization_suggestions(
1171 &self,
1172 address: usize,
1173 classification: &PatternClassification,
1174 ) {
1175 let mut suggestions = self.optimization_suggestions.lock();
1176
1177 match &classification.primary_type {
1178 PatternType::Sequential { stride, .. } => {
1179 suggestions.push(PatternOptimizationSuggestion {
1180 target: address,
1181 optimization_type: OptimizationType::PrefetchingOptimization {
1182 prefetch_distance: *stride * 4,
1183 prefetch_pattern: PrefetchPattern::Sequential,
1184 },
1185 suggestion: "Implement sequential prefetching to improve cache performance"
1186 .to_string(),
1187 expected_improvement: 0.3,
1188 complexity: OptimizationComplexity::Low,
1189 prerequisites: vec!["Hardware prefetcher support".to_string()],
1190 timeline: OptimizationTimeline::Immediate,
1191 });
1192 }
1193 PatternType::Random { .. } => {
1194 suggestions.push(PatternOptimizationSuggestion {
1195 target: address,
1196 optimization_type: OptimizationType::CacheOptimization {
1197 cache_strategy: CacheStrategy::SetAssociative { ways: 8 },
1198 target_cache_level: CacheLevel::L2,
1199 },
1200 suggestion: "Use set-associative cache to handle random access patterns"
1201 .to_string(),
1202 expected_improvement: 0.2,
1203 complexity: OptimizationComplexity::Medium,
1204 prerequisites: vec!["Cache configuration access".to_string()],
1205 timeline: OptimizationTimeline::ShortTerm,
1206 });
1207 }
1208 PatternType::Streaming { .. } => {
1209 suggestions.push(PatternOptimizationSuggestion {
1210 target: address,
1211 optimization_type: OptimizationType::BandwidthOptimization {
1212 batching_strategy: BatchingStrategy::SizeBased,
1213 transfer_optimization: TransferOptimization::Coalescing,
1214 },
1215 suggestion: "Implement memory coalescing for streaming workloads".to_string(),
1216 expected_improvement: 0.4,
1217 complexity: OptimizationComplexity::Medium,
1218 prerequisites: vec!["DMA controller access".to_string()],
1219 timeline: OptimizationTimeline::MediumTerm,
1220 });
1221 }
1222 _ => {}
1223 }
1224 }
1225
1226 fn update_prediction_model(&self, address: usize, pattern: &AccessPattern) {
1228 let mut models = self.prediction_models.lock();
1231
1232 if !models.contains_key(&address) {
1233 models.insert(address, AccessPredictionModel::new());
1234 }
1235
1236 if let Some(model) = models.get_mut(&address) {
1237 for (i, (&time, &size)) in pattern
1239 .access_times
1240 .iter()
1241 .zip(pattern.access_sizes.iter())
1242 .enumerate()
1243 {
1244 let access_type = pattern
1245 .access_types
1246 .get(i)
1247 .copied()
1248 .unwrap_or(AccessType::Read);
1249
1250 let event = AccessEvent {
1251 address: size, access_type,
1253 size,
1254 timestamp: time,
1255 context: AccessContext {
1256 thread_id: 0, operation: "unknown".to_string(),
1258 allocation_id: Some(address),
1259 },
1260 };
1261
1262 model.add_access_event(event);
1263 }
1264 }
1265 }
1266
1267 pub fn get_classification(&self, address: usize) -> Option<PatternClassification> {
1269 self.pattern_classifications.lock().get(&address).cloned()
1270 }
1271
1272 pub fn get_optimization_suggestions(&self) -> Vec<PatternOptimizationSuggestion> {
1274 self.optimization_suggestions.lock().clone()
1275 }
1276
1277 pub fn get_statistics(&self) -> PatternStatistics {
1279 (*self.pattern_statistics.lock()).clone()
1280 }
1281
1282 pub fn cleanup_old_data(&self, max_age: Duration) {
1284 let cutoff = Instant::now() - max_age;
1285
1286 let mut classifications = self.pattern_classifications.lock();
1288 classifications.retain(|_, classification| classification.classified_at > cutoff);
1289
1290 let mut suggestions = self.optimization_suggestions.lock();
1292 suggestions.retain(|_suggestion| {
1293 true
1296 });
1297
1298 let mut models = self.prediction_models.lock();
1300 for model in models.values_mut() {
1301 model.cleanup_old_events(cutoff);
1302 }
1303 }
1304}
1305
1306impl AccessPredictionModel {
1307 fn new() -> Self {
1309 Self {
1310 access_history: VecDeque::new(),
1311 pattern_state: PatternRecognitionState {
1312 current_hypothesis: None,
1313 transition_probabilities: HashMap::new(),
1314 confidence: 0.0,
1315 },
1316 accuracy_tracker: AccuracyTracker {
1317 correct_predictions: 0,
1318 total_predictions: 0,
1319 recent_accuracy: VecDeque::new(),
1320 accuracy_by_pattern: HashMap::new(),
1321 },
1322 model_params: PredictionModelParams {
1323 history_window: 100,
1324 prediction_horizon: Duration::from_millis(100),
1325 learning_rate: 0.1,
1326 pattern_threshold: 0.7,
1327 },
1328 }
1329 }
1330
1331 fn add_access_event(&mut self, event: AccessEvent) {
1333 self.access_history.push_back(event);
1334
1335 while self.access_history.len() > self.model_params.history_window {
1337 self.access_history.pop_front();
1338 }
1339
1340 self.update_pattern_recognition();
1342 }
1343
1344 fn update_pattern_recognition(&mut self) {
1346 if self.access_history.len() >= 10 {
1349 self.pattern_state.confidence = 0.7; }
1351 }
1352
1353 fn cleanup_old_events(&mut self, cutoff: Instant) {
1355 self.access_history.retain(|event| event.timestamp > cutoff);
1356 }
1357}
1358
1359impl Default for PatternAnalysisConfig {
1360 fn default() -> Self {
1361 Self {
1362 min_pattern_length: 5,
1363 analysis_window: Duration::from_secs(60),
1364 confidence_threshold: 0.5,
1365 enable_prediction: true,
1366 enable_optimization_suggestions: true,
1367 max_tracked_patterns: 10000,
1368 classification_sensitivity: 0.1,
1369 cache_analysis_depth: 3,
1370 }
1371 }
1372}
1373
1374#[cfg(test)]
1375mod tests {
1376 use super::*;
1377 use crate::memory_profiler::allocation::AccessPattern;
1378
1379 #[test]
1380 fn test_pattern_analyzer_creation() {
1381 let config = PatternAnalysisConfig::default();
1382 let analyzer = AccessPatternAnalyzer::new(config);
1383
1384 assert!(analyzer.get_statistics().total_patterns == 0);
1385 assert!(analyzer.get_optimization_suggestions().is_empty());
1386 }
1387
1388 #[test]
1389 fn test_sequential_pattern_classification() {
1390 let analyzer = AccessPatternAnalyzer::new(PatternAnalysisConfig::default());
1391
1392 let mut pattern = AccessPattern::new();
1393 for i in 0..10 {
1395 pattern.record_access(AccessType::Read, 1000 + i * 8);
1396 }
1397 pattern.sequential_score = 0.9;
1398 pattern.temporal_locality = 0.5;
1399 pattern.spatial_locality = 0.8;
1400
1401 let classification = analyzer.analyze_pattern(0x1000, &pattern);
1402 assert!(classification.is_some());
1403
1404 let classification = classification.expect("operation should succeed");
1405 assert!(matches!(
1406 classification.primary_type,
1407 PatternType::Sequential { .. }
1408 ));
1409 assert!(classification.confidence > 0.5);
1410 }
1411
1412 #[test]
1413 fn test_optimization_suggestions() {
1414 let analyzer = AccessPatternAnalyzer::new(PatternAnalysisConfig::default());
1415
1416 let mut pattern = AccessPattern::new();
1417 for i in 0..10 {
1418 pattern.record_access(AccessType::Read, 1000 + i * 8);
1419 }
1420 pattern.sequential_score = 0.9;
1421
1422 analyzer.analyze_pattern(0x1000, &pattern);
1423 let suggestions = analyzer.get_optimization_suggestions();
1424
1425 assert!(!suggestions.is_empty());
1426 assert!(suggestions.iter().any(|s| matches!(
1427 s.optimization_type,
1428 OptimizationType::PrefetchingOptimization { .. }
1429 )));
1430 }
1431
1432 #[test]
1433 fn test_pattern_statistics_update() {
1434 let analyzer = AccessPatternAnalyzer::new(PatternAnalysisConfig::default());
1435
1436 let mut pattern = AccessPattern::new();
1437 for i in 0..10 {
1438 pattern.record_access(AccessType::Read, 1000 + i * 8);
1439 }
1440 pattern.sequential_score = 0.8;
1441
1442 analyzer.analyze_pattern(0x1000, &pattern);
1443
1444 let stats = analyzer.get_statistics();
1445 assert_eq!(stats.total_patterns, 1);
1446 assert!(stats.average_confidence > 0.0);
1447 }
1448
1449 #[test]
1450 fn test_streaming_pattern_detection() {
1451 let analyzer = AccessPatternAnalyzer::new(PatternAnalysisConfig::default());
1452
1453 let mut pattern = AccessPattern::new();
1454 for _i in 0..10 {
1456 pattern.record_access(AccessType::Read, 64 * 1024); }
1458 pattern.sequential_score = 0.6;
1459 pattern.spatial_locality = 0.9;
1460
1461 let streaming_score = analyzer.analyze_streaming(&pattern);
1462 assert!(streaming_score > 0.5);
1463 }
1464
1465 #[test]
1466 fn test_access_prediction() {
1467 let analyzer = AccessPatternAnalyzer::new(PatternAnalysisConfig::default());
1468
1469 let mut pattern = AccessPattern::new();
1470 for i in 0..5 {
1471 pattern.record_access(AccessType::Read, 1000 + i * 8);
1472 }
1473
1474 let pattern_type = PatternType::Sequential {
1475 stride: 8,
1476 direction: AccessDirection::Forward,
1477 };
1478
1479 let prediction = analyzer.generate_access_prediction(&pattern, &pattern_type);
1480 assert!(!prediction.next_accesses.is_empty());
1481 assert!(!prediction.prefetch_candidates.is_empty());
1482 }
1483}