trustformers-models 0.1.1

Model implementations for TrustformeRS
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
//! Performance Optimization Utilities
//!
//! This module provides performance optimization utilities for model inference,
//! including batch processing, memory optimization, and caching strategies.

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use trustformers_core::errors::{Result, TrustformersError};
use trustformers_core::Tensor;

/// Configuration for performance optimization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
    /// Maximum batch size for inference
    pub max_batch_size: usize,
    /// Whether to enable dynamic batching
    pub enable_dynamic_batching: bool,
    /// Cache size for frequently used tensors
    pub cache_size: usize,
    /// Whether to enable memory optimization
    pub enable_memory_optimization: bool,
    /// Number of threads for parallel processing
    pub num_threads: Option<usize>,
}

impl Default for PerformanceConfig {
    fn default() -> Self {
        Self {
            max_batch_size: 32,
            enable_dynamic_batching: true,
            cache_size: 1000,
            enable_memory_optimization: true,
            num_threads: None, // Use system default
        }
    }
}

/// LRU Cache implementation for tensors
#[derive(Debug)]
pub struct LruCache {
    capacity: usize,
    cache: HashMap<String, (Tensor, usize)>, // (tensor, access_order)
    access_order: usize,
    access_history: VecDeque<String>,
    hits: usize,
    misses: usize,
}

impl LruCache {
    pub fn new(capacity: usize) -> Self {
        Self {
            capacity,
            cache: HashMap::new(),
            access_order: 0,
            access_history: VecDeque::new(),
            hits: 0,
            misses: 0,
        }
    }

    pub fn get(&mut self, key: &str) -> Option<&Tensor> {
        if let Some((tensor, _)) = self.cache.get(key).cloned() {
            self.access_order += 1;
            self.cache.insert(key.to_string(), (tensor, self.access_order));
            self.hits += 1;
            self.cache.get(key).map(|(tensor, _)| tensor)
        } else {
            self.misses += 1;
            None
        }
    }

    pub fn put(&mut self, key: String, tensor: Tensor) {
        if self.cache.len() >= self.capacity && !self.cache.contains_key(&key) {
            self.evict_lru();
        }

        self.access_order += 1;
        self.cache.insert(key.clone(), (tensor, self.access_order));
        self.access_history.push_back(key);

        // Keep access history manageable
        if self.access_history.len() > self.capacity * 2 {
            self.access_history.pop_front();
        }
    }

    fn evict_lru(&mut self) {
        if let Some(lru_key) = self.find_lru_key() {
            self.cache.remove(&lru_key);
        }
    }

    fn find_lru_key(&self) -> Option<String> {
        self.cache
            .iter()
            .min_by_key(|(_, (_, access_order))| *access_order)
            .map(|(key, _)| key.clone())
    }

    pub fn clear(&mut self) {
        self.cache.clear();
        self.access_history.clear();
        self.access_order = 0;
        self.hits = 0;
        self.misses = 0;
    }

    pub fn len(&self) -> usize {
        self.cache.len()
    }

    pub fn hit_rate(&self) -> f64 {
        let total = self.hits + self.misses;
        if total > 0 {
            self.hits as f64 / total as f64
        } else {
            0.0
        }
    }

    pub fn statistics(&self) -> CacheStatistics {
        CacheStatistics {
            current_size: self.cache.len(),
            max_size: self.capacity,
            hit_rate: self.hit_rate(),
        }
    }
}

/// Batch processor for efficient inference
#[derive(Debug)]
pub struct BatchProcessor {
    config: PerformanceConfig,
    cache: LruCache,
    batch_buffer: Vec<Tensor>,
}

impl BatchProcessor {
    /// Create a new batch processor
    pub fn new(config: PerformanceConfig) -> Self {
        Self {
            cache: LruCache::new(config.cache_size),
            config,
            batch_buffer: Vec::new(),
        }
    }

    /// Add a tensor to the current batch
    pub fn add_to_batch(&mut self, tensor: Tensor) -> Result<Option<Vec<Tensor>>> {
        self.batch_buffer.push(tensor);

        if self.batch_buffer.len() >= self.config.max_batch_size {
            Ok(Some(self.flush_batch()?))
        } else {
            Ok(None)
        }
    }

    /// Flush the current batch and return it
    pub fn flush_batch(&mut self) -> Result<Vec<Tensor>> {
        let batch = std::mem::take(&mut self.batch_buffer);
        Ok(batch)
    }

    /// Cache a tensor with a given key
    pub fn cache_tensor(&mut self, key: String, tensor: Tensor) -> Result<()> {
        self.cache.put(key, tensor);
        Ok(())
    }

    /// Cache statistics
    pub fn cache_stats(&self) -> CacheStatistics {
        self.cache.statistics()
    }

    /// Retrieve a cached tensor
    pub fn get_cached_tensor(&mut self, key: &str) -> Option<&Tensor> {
        self.cache.get(key)
    }

    /// Clear the cache
    pub fn clear_cache(&mut self) {
        self.cache.clear();
    }

    /// Get current batch size
    pub fn current_batch_size(&self) -> usize {
        self.batch_buffer.len()
    }
}

/// Memory optimization utilities
pub struct MemoryOptimizer;

impl MemoryOptimizer {
    /// Optimize tensor memory layout for better cache performance
    pub fn optimize_memory_layout(tensors: &mut [Tensor]) -> Result<()> {
        // Sort tensors by size (larger tensors first) for better memory allocation patterns
        tensors.sort_by(|a, b| {
            let size_a = a.shape().iter().product::<usize>();
            let size_b = b.shape().iter().product::<usize>();
            size_b.cmp(&size_a) // Descending order
        });

        // Apply memory layout optimizations per tensor
        for tensor in tensors.iter_mut() {
            Self::optimize_single_tensor_layout(tensor)?;
        }

        Ok(())
    }

    /// Optimize memory layout for a single tensor
    fn optimize_single_tensor_layout(tensor: &mut Tensor) -> Result<()> {
        match tensor {
            Tensor::F32(ref mut data)
                // For multidimensional tensors, consider reshaping for better cache locality
                // This is a simplified optimization - in practice, you'd analyze access patterns
                if data.ndim() > 2
                    // Ensure the tensor is in contiguous memory layout
                    && !data.is_standard_layout() => {
                        let owned = data.to_owned();
                        *data = owned;
                    },
            Tensor::I64(ref mut data)
                // Similar optimization for integer tensors
                if data.ndim() > 2 && !data.is_standard_layout() => {
                    let owned = data.to_owned();
                    *data = owned;
                },
            _ => {
                // For other tensor types, ensure standard layout if possible
            },
        }
        Ok(())
    }

    /// Analyze memory access patterns and suggest optimizations
    pub fn analyze_memory_patterns(tensors: &[Tensor]) -> Vec<String> {
        let mut recommendations = Vec::new();

        // Check for fragmentation patterns
        let total_elements: usize =
            tensors.iter().map(|t| t.shape().iter().product::<usize>()).sum();

        if total_elements > 1_000_000 {
            recommendations
                .push("Consider using memory pooling for large tensor operations".to_string());
        }

        // Check for small tensor overhead
        let small_tensors =
            tensors.iter().filter(|t| t.shape().iter().product::<usize>() < 1000).count();

        if small_tensors > 10 {
            recommendations
                .push("Consider tensor batching to reduce small tensor overhead".to_string());
        }

        // Check tensor alignment and suggest SIMD optimization
        for (i, tensor) in tensors.iter().enumerate() {
            let shape = tensor.shape();
            if shape.len() >= 2 {
                let last_dim = shape[shape.len() - 1];
                if last_dim % 4 != 0 {
                    recommendations.push(format!(
                        "Tensor {} last dimension ({}) not aligned for SIMD operations",
                        i, last_dim
                    ));
                }
            }
        }

        recommendations
    }

    /// Estimate memory usage for a batch of tensors
    pub fn estimate_memory_usage(tensors: &[Tensor]) -> Result<usize> {
        let mut total_bytes = 0;

        for tensor in tensors {
            let shape = tensor.shape();
            let elements = shape.iter().product::<usize>();
            // Assuming f32 elements (4 bytes each)
            total_bytes += elements * 4;
        }

        Ok(total_bytes)
    }

    /// Check if a batch fits within memory constraints
    pub fn check_memory_constraints(tensors: &[Tensor], max_memory_mb: usize) -> Result<bool> {
        let estimated_bytes = Self::estimate_memory_usage(tensors)?;
        let max_bytes = max_memory_mb * 1024 * 1024;
        Ok(estimated_bytes <= max_bytes)
    }
}

/// Dynamic batching strategy
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BatchingStrategy {
    /// Fixed batch size
    Fixed(usize),
    /// Dynamic batching based on sequence length
    DynamicByLength {
        max_length: usize,
        max_batch_size: usize,
    },
    /// Dynamic batching based on memory constraints
    DynamicByMemory { max_memory_mb: usize },
    /// Adaptive batching that adjusts based on performance metrics
    Adaptive {
        initial_batch_size: usize,
        max_batch_size: usize,
        target_latency_ms: f64,
        adjustment_factor: f64,
    },
    /// Priority-based batching with different priorities
    PriorityBased {
        high_priority_batch_size: usize,
        normal_priority_batch_size: usize,
        low_priority_batch_size: usize,
    },
}

/// Dynamic batch manager
#[derive(Debug)]
pub struct DynamicBatchManager {
    strategy: BatchingStrategy,
    pending_tensors: Vec<(Tensor, usize)>, // (tensor, priority)
    current_batch_size: usize,
    recent_latencies: VecDeque<f64>,
    total_batches_processed: usize,
}

impl DynamicBatchManager {
    /// Create a new dynamic batch manager
    pub fn new(strategy: BatchingStrategy) -> Self {
        let initial_batch_size = match &strategy {
            BatchingStrategy::Fixed(size) => *size,
            BatchingStrategy::DynamicByLength { max_batch_size, .. } => *max_batch_size / 2,
            BatchingStrategy::DynamicByMemory { .. } => 16,
            BatchingStrategy::Adaptive {
                initial_batch_size, ..
            } => *initial_batch_size,
            BatchingStrategy::PriorityBased {
                normal_priority_batch_size,
                ..
            } => *normal_priority_batch_size,
        };

        Self {
            strategy,
            pending_tensors: Vec::new(),
            current_batch_size: initial_batch_size,
            recent_latencies: VecDeque::new(),
            total_batches_processed: 0,
        }
    }

    /// Record latency for adaptive batching
    pub fn record_latency(&mut self, latency_ms: f64) {
        self.recent_latencies.push_back(latency_ms);

        // Keep only recent latencies (last 20 batches)
        if self.recent_latencies.len() > 20 {
            self.recent_latencies.pop_front();
        }

        self.total_batches_processed += 1;

        // Adjust batch size for adaptive strategy
        if let BatchingStrategy::Adaptive {
            target_latency_ms,
            max_batch_size,
            adjustment_factor,
            ..
        } = &self.strategy
        {
            if self.recent_latencies.len() >= 5 {
                let avg_latency: f64 =
                    self.recent_latencies.iter().sum::<f64>() / self.recent_latencies.len() as f64;

                if avg_latency > *target_latency_ms {
                    // Latency too high, reduce batch size
                    self.current_batch_size = std::cmp::max(
                        1,
                        (self.current_batch_size as f64 * (1.0 - adjustment_factor)) as usize,
                    );
                } else if avg_latency < *target_latency_ms * 0.8 {
                    // Latency acceptable, can increase batch size
                    self.current_batch_size = std::cmp::min(
                        *max_batch_size,
                        (self.current_batch_size as f64 * (1.0 + adjustment_factor)) as usize,
                    );
                }
            }
        }
    }

    /// Add a tensor to the pending queue with priority
    pub fn add_tensor(&mut self, tensor: Tensor, priority: usize) -> Result<()> {
        self.pending_tensors.push((tensor, priority));
        // Sort by priority (higher priority first)
        self.pending_tensors.sort_by_key(|item| std::cmp::Reverse(item.1));
        Ok(())
    }

    /// Get the next optimal batch based on the strategy
    pub fn get_next_batch(&mut self) -> Result<Option<Vec<Tensor>>> {
        if self.pending_tensors.is_empty() {
            return Ok(None);
        }

        match &self.strategy {
            BatchingStrategy::Fixed(batch_size) => {
                if self.pending_tensors.len() >= *batch_size {
                    let batch: Vec<Tensor> = self
                        .pending_tensors
                        .drain(0..*batch_size)
                        .map(|(tensor, _)| tensor)
                        .collect();
                    Ok(Some(batch))
                } else {
                    Ok(None)
                }
            },
            BatchingStrategy::DynamicByLength {
                max_length: _,
                max_batch_size,
            } => {
                let batch_size = std::cmp::min(self.pending_tensors.len(), *max_batch_size);
                if batch_size > 0 {
                    let batch: Vec<Tensor> = self
                        .pending_tensors
                        .drain(0..batch_size)
                        .map(|(tensor, _)| tensor)
                        .collect();
                    Ok(Some(batch))
                } else {
                    Ok(None)
                }
            },
            BatchingStrategy::DynamicByMemory { max_memory_mb } => {
                let mut batch = Vec::new();
                let mut current_memory = 0;

                while !self.pending_tensors.is_empty() {
                    let tensor_memory = self.estimate_tensor_memory(&self.pending_tensors[0].0)?;
                    if current_memory + tensor_memory <= *max_memory_mb * 1024 * 1024 {
                        let (tensor, _) = self.pending_tensors.remove(0);
                        batch.push(tensor);
                        current_memory += tensor_memory;
                    } else {
                        break;
                    }
                }

                if batch.is_empty() {
                    Ok(None)
                } else {
                    Ok(Some(batch))
                }
            },
            BatchingStrategy::Adaptive { .. } => {
                if self.pending_tensors.len() >= self.current_batch_size {
                    let batch: Vec<Tensor> = self
                        .pending_tensors
                        .drain(0..self.current_batch_size)
                        .map(|(tensor, _)| tensor)
                        .collect();
                    Ok(Some(batch))
                } else {
                    Ok(None)
                }
            },
            BatchingStrategy::PriorityBased {
                high_priority_batch_size,
                normal_priority_batch_size,
                low_priority_batch_size,
            } => {
                // Group by priority
                let high_priority: Vec<_> = self
                    .pending_tensors
                    .iter()
                    .filter(|(_, priority)| *priority >= 80)
                    .cloned()
                    .collect();
                let normal_priority: Vec<_> = self
                    .pending_tensors
                    .iter()
                    .filter(|(_, priority)| *priority >= 40 && *priority < 80)
                    .cloned()
                    .collect();
                let low_priority: Vec<_> = self
                    .pending_tensors
                    .iter()
                    .filter(|(_, priority)| *priority < 40)
                    .cloned()
                    .collect();

                if high_priority.len() >= *high_priority_batch_size {
                    let batch: Vec<Tensor> = high_priority
                        .into_iter()
                        .take(*high_priority_batch_size)
                        .map(|(tensor, _)| tensor)
                        .collect();
                    // Remove processed tensors
                    self.pending_tensors.retain(|(_, priority)| *priority < 80);
                    Ok(Some(batch))
                } else if normal_priority.len() >= *normal_priority_batch_size {
                    let batch: Vec<Tensor> = normal_priority
                        .into_iter()
                        .take(*normal_priority_batch_size)
                        .map(|(tensor, _)| tensor)
                        .collect();
                    // Remove processed tensors
                    self.pending_tensors.retain(|(_, priority)| *priority < 40 || *priority >= 80);
                    Ok(Some(batch))
                } else if low_priority.len() >= *low_priority_batch_size {
                    let batch: Vec<Tensor> = low_priority
                        .into_iter()
                        .take(*low_priority_batch_size)
                        .map(|(tensor, _)| tensor)
                        .collect();
                    // Remove processed tensors
                    self.pending_tensors.retain(|(_, priority)| *priority >= 40);
                    Ok(Some(batch))
                } else {
                    Ok(None)
                }
            },
        }
    }

    /// Estimate memory usage for a single tensor
    fn estimate_tensor_memory(&self, tensor: &Tensor) -> Result<usize> {
        let shape = tensor.shape();
        let elements = shape.iter().product::<usize>();
        // Assuming f32 elements (4 bytes each)
        Ok(elements * 4)
    }

    /// Get number of pending tensors
    pub fn pending_count(&self) -> usize {
        self.pending_tensors.len()
    }

    /// Get current batch size for adaptive strategies
    pub fn current_batch_size(&self) -> usize {
        self.current_batch_size
    }

    /// Get average latency for performance analysis
    pub fn average_latency(&self) -> f64 {
        if self.recent_latencies.is_empty() {
            0.0
        } else {
            self.recent_latencies.iter().sum::<f64>() / self.recent_latencies.len() as f64
        }
    }

    /// Get batch processing statistics
    pub fn get_batch_statistics(&self) -> BatchStatistics {
        BatchStatistics {
            total_batches_processed: self.total_batches_processed,
            current_batch_size: self.current_batch_size,
            pending_tensors: self.pending_tensors.len(),
            average_latency_ms: self.average_latency(),
            strategy_type: match &self.strategy {
                BatchingStrategy::Fixed(_) => "Fixed".to_string(),
                BatchingStrategy::DynamicByLength { .. } => "DynamicByLength".to_string(),
                BatchingStrategy::DynamicByMemory { .. } => "DynamicByMemory".to_string(),
                BatchingStrategy::Adaptive { .. } => "Adaptive".to_string(),
                BatchingStrategy::PriorityBased { .. } => "PriorityBased".to_string(),
            },
        }
    }
}

/// Performance monitoring utilities
#[derive(Debug, Default)]
pub struct PerformanceMonitor {
    total_inference_time: f64,
    total_inferences: usize,
    batch_sizes: Vec<usize>,
    memory_usage: Vec<usize>,
}

impl PerformanceMonitor {
    /// Record an inference time
    pub fn record_inference(&mut self, time_ms: f64, batch_size: usize, memory_usage: usize) {
        self.total_inference_time += time_ms;
        self.total_inferences += 1;
        self.batch_sizes.push(batch_size);
        self.memory_usage.push(memory_usage);
    }

    /// Get average inference time
    pub fn average_inference_time(&self) -> f64 {
        if self.total_inferences > 0 {
            self.total_inference_time / self.total_inferences as f64
        } else {
            0.0
        }
    }

    /// Get average batch size
    pub fn average_batch_size(&self) -> f64 {
        if self.batch_sizes.is_empty() {
            0.0
        } else {
            self.batch_sizes.iter().sum::<usize>() as f64 / self.batch_sizes.len() as f64
        }
    }

    /// Get peak memory usage
    pub fn peak_memory_usage(&self) -> usize {
        self.memory_usage.iter().max().copied().unwrap_or(0)
    }

    /// Get performance statistics
    pub fn get_statistics(&self) -> PerformanceStatistics {
        PerformanceStatistics {
            total_inferences: self.total_inferences,
            average_inference_time_ms: self.average_inference_time(),
            average_batch_size: self.average_batch_size(),
            peak_memory_usage_bytes: self.peak_memory_usage(),
            throughput_inferences_per_second: if self.total_inference_time > 0.0 {
                (self.total_inferences as f64) / (self.total_inference_time / 1000.0)
            } else {
                0.0
            },
        }
    }
}

/// Cache statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheStatistics {
    pub current_size: usize,
    pub max_size: usize,
    pub hit_rate: f64,
}

/// Performance statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceStatistics {
    pub total_inferences: usize,
    pub average_inference_time_ms: f64,
    pub average_batch_size: f64,
    pub peak_memory_usage_bytes: usize,
    pub throughput_inferences_per_second: f64,
}

/// Advanced performance optimizer with workload analysis
#[derive(Debug)]
pub struct AdvancedPerformanceOptimizer {
    #[allow(dead_code)]
    config: PerformanceConfig,
    workload_history: Vec<WorkloadMetrics>,
    optimization_recommendations: Vec<String>,
}

/// Workload metrics for optimization analysis
#[derive(Debug, Clone)]
pub struct WorkloadMetrics {
    pub batch_size: usize,
    pub sequence_length: usize,
    pub memory_usage: usize,
    pub inference_time_ms: f64,
    pub timestamp: std::time::Instant,
}

impl AdvancedPerformanceOptimizer {
    /// Create a new advanced optimizer
    pub fn new(config: PerformanceConfig) -> Self {
        Self {
            config,
            workload_history: Vec::new(),
            optimization_recommendations: Vec::new(),
        }
    }

    /// Record workload metrics
    pub fn record_workload(&mut self, metrics: WorkloadMetrics) {
        self.workload_history.push(metrics);

        // Keep only recent history (last 1000 entries)
        if self.workload_history.len() > 1000 {
            self.workload_history.remove(0);
        }

        // Generate recommendations based on patterns
        self.generate_recommendations();
    }

    /// Generate optimization recommendations
    fn generate_recommendations(&mut self) {
        self.optimization_recommendations.clear();

        if self.workload_history.len() < 10 {
            return;
        }

        // Analyze recent performance patterns
        let recent_metrics: Vec<_> = self.workload_history.iter().rev().take(50).collect();

        // Check for small batch sizes
        let avg_batch_size: f64 = recent_metrics.iter().map(|m| m.batch_size as f64).sum::<f64>()
            / recent_metrics.len() as f64;

        if avg_batch_size < 8.0 {
            self.optimization_recommendations
                .push("Consider increasing batch size for better throughput".to_string());
        }

        // Check for high memory usage variation
        let memory_usages: Vec<usize> = recent_metrics.iter().map(|m| m.memory_usage).collect();
        let max_memory = memory_usages.iter().max().unwrap_or(&0);
        let min_memory = memory_usages.iter().min().unwrap_or(&0);

        if *max_memory > min_memory * 2 {
            self.optimization_recommendations.push(
                "High memory usage variation detected - consider dynamic batching".to_string(),
            );
        }

        // Check for performance degradation
        if recent_metrics.len() >= 20 {
            let first_half_avg: f64 =
                recent_metrics[10..].iter().map(|m| m.inference_time_ms).sum::<f64>() / 10.0;
            let second_half_avg: f64 =
                recent_metrics[..10].iter().map(|m| m.inference_time_ms).sum::<f64>() / 10.0;

            if second_half_avg > first_half_avg * 1.2 {
                self.optimization_recommendations.push(
                    "Performance degradation detected - consider cache clearing or model reloading"
                        .to_string(),
                );
            }
        }
    }

    /// Get current optimization recommendations
    pub fn get_recommendations(&self) -> &[String] {
        &self.optimization_recommendations
    }

    /// Get workload analysis summary
    pub fn get_workload_analysis(&self) -> WorkloadAnalysis {
        if self.workload_history.is_empty() {
            return WorkloadAnalysis::default();
        }

        let total_metrics = self.workload_history.len();
        let avg_batch_size = self.workload_history.iter().map(|m| m.batch_size as f64).sum::<f64>()
            / total_metrics as f64;

        let avg_inference_time =
            self.workload_history.iter().map(|m| m.inference_time_ms).sum::<f64>()
                / total_metrics as f64;

        let peak_memory = self.workload_history.iter().map(|m| m.memory_usage).max().unwrap_or(0);

        WorkloadAnalysis {
            total_samples: total_metrics,
            average_batch_size: avg_batch_size,
            average_inference_time_ms: avg_inference_time,
            peak_memory_usage_bytes: peak_memory,
            recommendations_count: self.optimization_recommendations.len(),
        }
    }
}

/// Workload analysis summary
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct WorkloadAnalysis {
    pub total_samples: usize,
    pub average_batch_size: f64,
    pub average_inference_time_ms: f64,
    pub peak_memory_usage_bytes: usize,
    pub recommendations_count: usize,
}

/// Batch processing statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchStatistics {
    pub total_batches_processed: usize,
    pub current_batch_size: usize,
    pub pending_tensors: usize,
    pub average_latency_ms: f64,
    pub strategy_type: String,
}

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

    #[test]
    fn test_performance_config_default() {
        let config = PerformanceConfig::default();
        assert_eq!(config.max_batch_size, 32);
        assert!(config.enable_dynamic_batching);
        assert_eq!(config.cache_size, 1000);
        assert!(config.enable_memory_optimization);
    }

    #[test]
    fn test_batch_processor_creation() {
        let config = PerformanceConfig::default();
        let processor = BatchProcessor::new(config);
        assert_eq!(processor.current_batch_size(), 0);
    }

    #[test]
    fn test_memory_optimizer_estimate() {
        // Create a simple test tensor
        let tensor = Tensor::zeros(&[2, 3]).expect("operation failed");
        let tensors = vec![tensor];

        let estimated = MemoryOptimizer::estimate_memory_usage(&tensors).expect("operation failed");
        // 2 * 3 elements * 4 bytes per f32 element = 24 bytes
        assert_eq!(estimated, 24);
    }

    #[test]
    fn test_dynamic_batch_manager() {
        let strategy = BatchingStrategy::Fixed(2);
        let mut manager = DynamicBatchManager::new(strategy);

        let tensor1 = Tensor::zeros(&[1, 2]).expect("operation failed");
        let tensor2 = Tensor::zeros(&[1, 2]).expect("operation failed");

        manager.add_tensor(tensor1, 1).expect("operation failed");
        manager.add_tensor(tensor2, 2).expect("operation failed");

        let batch = manager.get_next_batch().expect("operation failed");
        assert!(batch.is_some());
        assert_eq!(batch.expect("operation failed").len(), 2);
    }

    #[test]
    fn test_performance_monitor() {
        let mut monitor = PerformanceMonitor::default();

        monitor.record_inference(100.0, 4, 1024);
        monitor.record_inference(200.0, 8, 2048);

        let stats = monitor.get_statistics();
        assert_eq!(stats.total_inferences, 2);
        assert_eq!(stats.average_inference_time_ms, 150.0);
        assert_eq!(stats.average_batch_size, 6.0);
        assert_eq!(stats.peak_memory_usage_bytes, 2048);
    }

    #[test]
    fn test_cache_statistics() {
        let config = PerformanceConfig::default();
        let processor = BatchProcessor::new(config);
        let stats = processor.cache_stats();

        assert_eq!(stats.current_size, 0);
        assert_eq!(stats.max_size, 1000);
        assert_eq!(stats.hit_rate, 0.0);
    }

    #[test]
    fn test_advanced_performance_optimizer() {
        let config = PerformanceConfig::default();
        let mut optimizer = AdvancedPerformanceOptimizer::new(config);

        // Record some sample workloads
        for i in 1..=20 {
            let metrics = WorkloadMetrics {
                batch_size: if i < 10 { 2 } else { 16 }, // Small then large batches
                sequence_length: 512,
                memory_usage: 1024 * i,
                inference_time_ms: 100.0 + (i as f64 * 5.0),
                timestamp: std::time::Instant::now(),
            };
            optimizer.record_workload(metrics);
        }

        let analysis = optimizer.get_workload_analysis();
        assert_eq!(analysis.total_samples, 20);
        assert!(analysis.average_batch_size > 2.0); // Should be higher due to mix

        let recommendations = optimizer.get_recommendations();
        assert!(!recommendations.is_empty()); // Should have some recommendations
    }

    #[test]
    fn test_lru_cache() {
        let mut cache = LruCache::new(2);

        let tensor1 = Tensor::zeros(&[1, 2]).expect("operation failed");
        let tensor2 = Tensor::zeros(&[1, 3]).expect("operation failed");
        let tensor3 = Tensor::zeros(&[1, 4]).expect("operation failed");

        // Add tensors
        cache.put("key1".to_string(), tensor1);
        cache.put("key2".to_string(), tensor2);

        // Access key1 to make it recently used
        let _ = cache.get("key1");

        // Add key3 - should evict key2 (least recently used)
        cache.put("key3".to_string(), tensor3);

        // key1 and key3 should be present, key2 should be evicted
        assert!(cache.get("key1").is_some());
        assert!(cache.get("key3").is_some());
        assert!(cache.get("key2").is_none());

        // Check statistics
        let stats = cache.statistics();
        assert_eq!(stats.current_size, 2);
        assert_eq!(stats.max_size, 2);
        assert!(stats.hit_rate > 0.0);
    }

    #[test]
    fn test_adaptive_batching() {
        let strategy = BatchingStrategy::Adaptive {
            initial_batch_size: 4,
            max_batch_size: 16,
            target_latency_ms: 100.0,
            adjustment_factor: 0.2,
        };
        let mut manager = DynamicBatchManager::new(strategy);

        // Record high latency - should reduce batch size
        for _ in 0..10 {
            manager.record_latency(150.0); // Higher than target
        }

        assert!(manager.current_batch_size() < 4); // Should have reduced

        // Record low latency - should increase batch size
        for _ in 0..10 {
            manager.record_latency(50.0); // Lower than target
        }

        // Note: size might not increase immediately due to adaptation logic
        let stats = manager.get_batch_statistics();
        assert_eq!(stats.strategy_type, "Adaptive");
        assert!(stats.average_latency_ms > 0.0);
    }

    #[test]
    fn test_priority_batching() {
        let strategy = BatchingStrategy::PriorityBased {
            high_priority_batch_size: 2,
            normal_priority_batch_size: 4,
            low_priority_batch_size: 8,
        };
        let mut manager = DynamicBatchManager::new(strategy);

        // Add tensors with different priorities
        let tensor = Tensor::zeros(&[1, 2]).expect("operation failed");
        manager.add_tensor(tensor.clone(), 90).expect("operation failed"); // High priority
        manager.add_tensor(tensor.clone(), 50).expect("operation failed"); // Normal priority
        manager.add_tensor(tensor.clone(), 90).expect("operation failed"); // High priority
        manager.add_tensor(tensor.clone(), 20).expect("operation failed"); // Low priority

        // Should get high priority batch first
        let batch = manager.get_next_batch().expect("operation failed");
        assert!(batch.is_some());
        assert_eq!(batch.expect("operation failed").len(), 2); // High priority batch size

        let stats = manager.get_batch_statistics();
        assert_eq!(stats.strategy_type, "PriorityBased");
    }
}

/// Advanced GPU Memory Management
///
/// This module provides sophisticated GPU memory management capabilities
/// for high-performance inference and training workloads.
/// GPU Memory Pool for efficient allocation and deallocation
#[derive(Debug)]
pub struct GpuMemoryPool {
    /// Pool of pre-allocated memory chunks by size
    pools: HashMap<usize, VecDeque<GpuMemoryChunk>>,
    /// Total memory allocated (in bytes)
    total_allocated: usize,
    /// Maximum memory limit (in bytes)
    max_memory_limit: usize,
    /// Memory fragmentation threshold
    fragmentation_threshold: f32,
    /// Memory allocation statistics
    stats: GpuMemoryStats,
}

#[derive(Debug, Clone)]
pub struct GpuMemoryChunk {
    /// Unique identifier for this chunk
    pub id: String,
    /// Size in bytes
    pub size_bytes: usize,
    /// Whether this chunk is currently in use
    pub in_use: bool,
    /// Allocation timestamp
    pub allocated_at: std::time::Instant,
    /// Last access timestamp
    pub last_accessed: std::time::Instant,
    /// Reference count for shared usage
    pub ref_count: usize,
}

#[derive(Debug, Default, Clone)]
pub struct GpuMemoryStats {
    /// Total allocations made
    pub total_allocations: usize,
    /// Total deallocations made
    pub total_deallocations: usize,
    /// Current active allocations
    pub active_allocations: usize,
    /// Peak memory usage (bytes)
    pub peak_memory_usage: usize,
    /// Current memory usage (bytes)
    pub current_memory_usage: usize,
    /// Memory fragmentation ratio (0.0 - 1.0)
    pub fragmentation_ratio: f32,
    /// Average allocation size
    pub average_allocation_size: f32,
    /// Number of cache hits
    pub cache_hits: usize,
    /// Number of cache misses
    pub cache_misses: usize,
}

impl GpuMemoryPool {
    /// Create a new GPU memory pool with specified limit
    pub fn new(max_memory_limit: usize) -> Self {
        Self {
            pools: HashMap::new(),
            total_allocated: 0,
            max_memory_limit,
            fragmentation_threshold: 0.25, // 25% fragmentation threshold
            stats: GpuMemoryStats::default(),
        }
    }

    /// Allocate memory from the pool
    pub fn allocate(&mut self, size_bytes: usize) -> Result<GpuMemoryChunk> {
        // Check if we have available memory
        if self.total_allocated + size_bytes > self.max_memory_limit {
            self.try_defragment()?;
            if self.total_allocated + size_bytes > self.max_memory_limit {
                return Err(TrustformersError::invalid_operation(
                    "GPU memory limit exceeded".to_string(),
                ));
            }
        }

        // Try to find existing chunk from pool
        if let Some(chunk) = self.find_suitable_chunk(size_bytes) {
            self.stats.cache_hits += 1;
            self.stats.active_allocations += 1;
            return Ok(chunk);
        }

        // Allocate new chunk
        let chunk = GpuMemoryChunk {
            id: uuid::Uuid::new_v4().to_string(),
            size_bytes,
            in_use: true,
            allocated_at: std::time::Instant::now(),
            last_accessed: std::time::Instant::now(),
            ref_count: 1,
        };

        self.total_allocated += size_bytes;
        self.stats.total_allocations += 1;
        self.stats.active_allocations += 1;
        self.stats.cache_misses += 1;
        self.stats.current_memory_usage += size_bytes;

        if self.stats.current_memory_usage > self.stats.peak_memory_usage {
            self.stats.peak_memory_usage = self.stats.current_memory_usage;
        }

        // Update average allocation size
        self.stats.average_allocation_size = (self.stats.average_allocation_size
            * (self.stats.total_allocations - 1) as f32
            + size_bytes as f32)
            / self.stats.total_allocations as f32;

        Ok(chunk)
    }

    /// Deallocate memory back to the pool
    pub fn deallocate(&mut self, mut chunk: GpuMemoryChunk) -> Result<()> {
        chunk.in_use = false;
        chunk.ref_count = 0;

        // Add back to appropriate pool
        let pool = self.pools.entry(chunk.size_bytes).or_default();
        pool.push_back(chunk.clone());

        self.stats.total_deallocations += 1;
        self.stats.active_allocations = self.stats.active_allocations.saturating_sub(1);
        self.stats.current_memory_usage =
            self.stats.current_memory_usage.saturating_sub(chunk.size_bytes);

        // Check if we need to free some pooled memory
        self.cleanup_unused_chunks()?;

        Ok(())
    }

    /// Find a suitable chunk from existing pools
    fn find_suitable_chunk(&mut self, size_bytes: usize) -> Option<GpuMemoryChunk> {
        // Look for exact size match first
        if let Some(pool) = self.pools.get_mut(&size_bytes) {
            if let Some(mut chunk) = pool.pop_front() {
                chunk.in_use = true;
                chunk.last_accessed = std::time::Instant::now();
                chunk.ref_count = 1;
                return Some(chunk);
            }
        }

        // Look for larger chunks that can be split
        let suitable_sizes: Vec<usize> = self.pools.keys()
            .filter(|&&size| size > size_bytes && size <= size_bytes * 2) // Avoid too much waste
            .copied()
            .collect();

        for pool_size in suitable_sizes {
            if let Some(pool) = self.pools.get_mut(&pool_size) {
                if let Some(mut chunk) = pool.pop_front() {
                    chunk.in_use = true;
                    chunk.last_accessed = std::time::Instant::now();
                    chunk.ref_count = 1;
                    return Some(chunk);
                }
            }
        }

        None
    }

    /// Cleanup unused chunks to free memory
    fn cleanup_unused_chunks(&mut self) -> Result<()> {
        let now = std::time::Instant::now();
        let cleanup_threshold = std::time::Duration::from_secs(300); // 5 minutes

        for pool in self.pools.values_mut() {
            pool.retain(|chunk| {
                let should_keep =
                    chunk.in_use || now.duration_since(chunk.last_accessed) < cleanup_threshold;
                if !should_keep {
                    self.total_allocated = self.total_allocated.saturating_sub(chunk.size_bytes);
                }
                should_keep
            });
        }

        Ok(())
    }

    /// Attempt to defragment memory
    fn try_defragment(&mut self) -> Result<()> {
        // Calculate current fragmentation ratio
        let total_pooled = self
            .pools
            .values()
            .map(|pool| pool.iter().map(|chunk| chunk.size_bytes).sum::<usize>())
            .sum::<usize>();

        self.stats.fragmentation_ratio = if self.total_allocated > 0 {
            total_pooled as f32 / self.total_allocated as f32
        } else {
            0.0
        };

        // If fragmentation is above threshold, force cleanup
        if self.stats.fragmentation_ratio > self.fragmentation_threshold {
            self.force_cleanup()?;
        }

        Ok(())
    }

    /// Force cleanup of all unused memory
    fn force_cleanup(&mut self) -> Result<()> {
        for pool in self.pools.values_mut() {
            let initial_size: usize = pool.iter().map(|chunk| chunk.size_bytes).sum();
            pool.retain(|chunk| chunk.in_use);
            let final_size: usize = pool.iter().map(|chunk| chunk.size_bytes).sum();
            self.total_allocated = self.total_allocated.saturating_sub(initial_size - final_size);
        }

        // Recalculate fragmentation
        self.try_defragment()?;

        Ok(())
    }

    /// Get memory pool statistics
    pub fn get_statistics(&self) -> GpuMemoryStats {
        self.stats.clone()
    }

    /// Get current memory usage as percentage of limit
    pub fn get_memory_usage_percentage(&self) -> f32 {
        (self.total_allocated as f32 / self.max_memory_limit as f32) * 100.0
    }

    /// Get cache efficiency (hit rate)
    pub fn get_cache_efficiency(&self) -> f32 {
        let total_requests = self.stats.cache_hits + self.stats.cache_misses;
        if total_requests > 0 {
            self.stats.cache_hits as f32 / total_requests as f32
        } else {
            0.0
        }
    }
}

/// Advanced GPU tensor caching with memory-aware eviction
#[derive(Debug)]
pub struct GpuTensorCache {
    /// Memory pool for efficient allocation
    memory_pool: GpuMemoryPool,
    /// Cached tensors with metadata
    tensor_cache: HashMap<String, CachedTensor>,
    /// LRU ordering for eviction
    lru_order: VecDeque<String>,
    /// Maximum cache size (number of tensors)
    max_cache_size: usize,
    /// Cache statistics
    stats: CacheStatistics,
}

#[derive(Debug, Clone)]
pub struct CachedTensor {
    /// The cached tensor data
    pub tensor: Tensor,
    /// Memory chunk information
    pub memory_chunk: GpuMemoryChunk,
    /// Access frequency score
    pub access_frequency: f32,
    /// Importance score (for eviction prioritization)
    pub importance_score: f32,
    /// Last access time
    pub last_access: std::time::Instant,
    /// Creation time
    pub created_at: std::time::Instant,
}

impl GpuTensorCache {
    /// Create a new GPU tensor cache
    pub fn new(max_cache_size: usize, max_memory_limit: usize) -> Self {
        Self {
            memory_pool: GpuMemoryPool::new(max_memory_limit),
            tensor_cache: HashMap::new(),
            lru_order: VecDeque::new(),
            max_cache_size,
            stats: CacheStatistics {
                current_size: 0,
                max_size: max_cache_size,
                hit_rate: 0.0,
            },
        }
    }

    /// Cache a tensor with optional importance score
    pub fn cache_tensor(
        &mut self,
        key: String,
        tensor: Tensor,
        importance_score: Option<f32>,
    ) -> Result<()> {
        // Calculate tensor size (simplified estimation)
        let tensor_size = self.estimate_tensor_size(&tensor);

        // Allocate memory chunk
        let memory_chunk = self.memory_pool.allocate(tensor_size)?;

        // Create cached tensor
        let cached_tensor = CachedTensor {
            tensor,
            memory_chunk,
            access_frequency: 1.0,
            importance_score: importance_score.unwrap_or(0.5),
            last_access: std::time::Instant::now(),
            created_at: std::time::Instant::now(),
        };

        // Check if we need to evict
        if self.tensor_cache.len() >= self.max_cache_size {
            self.evict_least_important()?;
        }

        // Insert new tensor
        self.tensor_cache.insert(key.clone(), cached_tensor);
        self.lru_order.push_back(key);
        self.stats.current_size = self.tensor_cache.len();

        Ok(())
    }

    /// Retrieve a tensor from cache
    pub fn get_tensor(&mut self, key: &str) -> Option<&Tensor> {
        // Check if key exists first
        if !self.tensor_cache.contains_key(key) {
            return None;
        }

        // Update LRU order first
        self.update_lru_order(key);

        // Update access information and return tensor
        if let Some(cached_tensor) = self.tensor_cache.get_mut(key) {
            cached_tensor.access_frequency += 1.0;
            cached_tensor.last_access = std::time::Instant::now();
            Some(&cached_tensor.tensor)
        } else {
            None
        }
    }

    /// Update LRU order for a key
    fn update_lru_order(&mut self, key: &str) {
        // Remove from current position and add to back
        if let Some(pos) = self.lru_order.iter().position(|k| k == key) {
            self.lru_order.remove(pos);
            self.lru_order.push_back(key.to_string());
        }
    }

    /// Evict the least important tensor
    fn evict_least_important(&mut self) -> Result<()> {
        // Calculate eviction scores for all cached tensors
        let mut eviction_candidates: Vec<(String, f32)> = self
            .tensor_cache
            .iter()
            .map(|(key, cached_tensor)| {
                let age_factor = cached_tensor.created_at.elapsed().as_secs() as f32 / 3600.0; // Hours
                let frequency_factor = cached_tensor.access_frequency;
                let importance_factor = cached_tensor.importance_score;

                // Lower score = higher priority for eviction
                let eviction_score = importance_factor * frequency_factor / (1.0 + age_factor);
                (key.clone(), eviction_score)
            })
            .collect();

        // Sort by eviction score (lowest first)
        eviction_candidates
            .sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));

        // Evict the least important tensor
        if let Some((key_to_evict, _)) = eviction_candidates.first() {
            if let Some(cached_tensor) = self.tensor_cache.remove(key_to_evict) {
                self.memory_pool.deallocate(cached_tensor.memory_chunk)?;

                // Remove from LRU order
                if let Some(pos) = self.lru_order.iter().position(|k| k == key_to_evict) {
                    self.lru_order.remove(pos);
                }

                self.stats.current_size = self.tensor_cache.len();
            }
        }

        Ok(())
    }

    /// Estimate tensor size in bytes (simplified)
    fn estimate_tensor_size(&self, tensor: &Tensor) -> usize {
        match tensor {
            Tensor::F32(arr) => arr.len() * 4, // 4 bytes per f32
            Tensor::F64(arr) => arr.len() * 8, // 8 bytes per f64
            _ => 1024,                         // Default estimate for other types
        }
    }

    /// Get comprehensive cache statistics
    pub fn get_comprehensive_stats(&self) -> GpuCacheStatistics {
        let memory_stats = self.memory_pool.get_statistics();
        let fragmentation_ratio = memory_stats.fragmentation_ratio;

        GpuCacheStatistics {
            cache_stats: self.stats.clone(),
            memory_stats,
            memory_usage_percentage: self.memory_pool.get_memory_usage_percentage(),
            cache_efficiency: self.memory_pool.get_cache_efficiency(),
            average_tensor_age: self.calculate_average_tensor_age(),
            fragmentation_ratio,
        }
    }

    /// Calculate average age of cached tensors
    fn calculate_average_tensor_age(&self) -> f32 {
        if self.tensor_cache.is_empty() {
            return 0.0;
        }

        let total_age: f32 = self
            .tensor_cache
            .values()
            .map(|cached_tensor| cached_tensor.created_at.elapsed().as_secs() as f32)
            .sum();

        total_age / self.tensor_cache.len() as f32
    }

    /// Clear all cached tensors
    pub fn clear(&mut self) -> Result<()> {
        for (_, cached_tensor) in self.tensor_cache.drain() {
            self.memory_pool.deallocate(cached_tensor.memory_chunk)?;
        }
        self.lru_order.clear();
        self.stats.current_size = 0;
        Ok(())
    }
}

/// Comprehensive GPU cache statistics
#[derive(Debug, Clone)]
pub struct GpuCacheStatistics {
    pub cache_stats: CacheStatistics,
    pub memory_stats: GpuMemoryStats,
    pub memory_usage_percentage: f32,
    pub cache_efficiency: f32,
    pub average_tensor_age: f32,
    pub fragmentation_ratio: f32,
}

/// GPU memory optimization recommendations
#[derive(Debug, Clone)]
pub struct GpuOptimizationRecommendations {
    /// Recommended actions to improve performance
    pub recommendations: Vec<String>,
    /// Priority level (High, Medium, Low)
    pub priority: String,
    /// Estimated performance improvement percentage
    pub estimated_improvement: f32,
}

/// GPU memory optimizer with intelligent recommendations
pub struct GpuMemoryOptimizer;

impl GpuMemoryOptimizer {
    /// Analyze GPU memory usage and provide optimization recommendations
    pub fn analyze_and_recommend(stats: &GpuCacheStatistics) -> GpuOptimizationRecommendations {
        let mut recommendations = Vec::new();
        let mut priority = "Low".to_string();
        let mut estimated_improvement: f32 = 0.0;

        // Analyze memory usage
        if stats.memory_usage_percentage > 90.0 {
            recommendations.push("Critical: Memory usage is very high. Consider increasing memory limit or improving eviction strategy.".to_string());
            priority = "High".to_string();
            estimated_improvement += 25.0;
        } else if stats.memory_usage_percentage > 75.0 {
            recommendations.push(
                "Warning: Memory usage is high. Monitor for potential memory pressure.".to_string(),
            );
            priority = "Medium".to_string();
            estimated_improvement += 10.0;
        }

        // Analyze fragmentation
        if stats.fragmentation_ratio > 0.4 {
            recommendations.push(
                "High memory fragmentation detected. Consider running defragmentation.".to_string(),
            );
            if priority == "Low" {
                priority = "Medium".to_string();
            }
            estimated_improvement += 15.0;
        }

        // Analyze cache efficiency
        if stats.cache_efficiency < 0.7 {
            recommendations.push(
                "Low cache hit rate. Consider adjusting cache size or eviction policy.".to_string(),
            );
            if priority == "Low" {
                priority = "Medium".to_string();
            }
            estimated_improvement += 20.0;
        }

        // Analyze tensor age
        if stats.average_tensor_age > 3600.0 {
            // 1 hour
            recommendations.push(
                "Cached tensors are aging. Consider more aggressive eviction for unused tensors."
                    .to_string(),
            );
            estimated_improvement += 5.0;
        }

        // Provide specific optimization suggestions
        if stats.memory_stats.active_allocations > 1000 {
            recommendations.push(
                "High number of active allocations. Consider batching or pooling strategies."
                    .to_string(),
            );
            estimated_improvement += 12.0;
        }

        if recommendations.is_empty() {
            recommendations
                .push("GPU memory usage is optimal. No immediate action required.".to_string());
        }

        GpuOptimizationRecommendations {
            recommendations,
            priority,
            estimated_improvement: estimated_improvement.min(50.0), // Cap at 50%
        }
    }

    /// Perform automatic GPU memory optimization
    pub fn auto_optimize(cache: &mut GpuTensorCache) -> Result<Vec<String>> {
        let stats = cache.get_comprehensive_stats();
        let recommendations = Self::analyze_and_recommend(&stats);
        let mut actions_taken = Vec::new();

        // Auto-apply some optimizations based on priority
        if recommendations.priority == "High" {
            // Force cleanup if memory usage is critical
            if stats.memory_usage_percentage > 90.0 {
                cache.memory_pool.force_cleanup()?;
                actions_taken.push("Performed emergency memory cleanup".to_string());
            }
        }

        if stats.fragmentation_ratio > 0.4 {
            cache.memory_pool.try_defragment()?;
            actions_taken.push("Performed memory defragmentation".to_string());
        }

        if actions_taken.is_empty() {
            actions_taken.push("No automatic optimizations were necessary".to_string());
        }

        Ok(actions_taken)
    }
}

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

    #[test]
    fn test_gpu_memory_pool_basic() {
        let mut pool = GpuMemoryPool::new(1024 * 1024); // 1MB limit

        // Test allocation
        let chunk = pool.allocate(1024).expect("operation failed");
        assert_eq!(chunk.size_bytes, 1024);
        assert!(chunk.in_use);
        assert_eq!(pool.get_statistics().active_allocations, 1);

        // Test deallocation
        pool.deallocate(chunk).expect("operation failed");
        assert_eq!(pool.get_statistics().active_allocations, 0);
    }

    #[test]
    fn test_gpu_memory_pool_reuse() {
        let mut pool = GpuMemoryPool::new(1024 * 1024);

        // Allocate and deallocate
        let chunk = pool.allocate(1024).expect("operation failed");
        pool.deallocate(chunk).expect("operation failed");

        // Allocate same size - should reuse
        let stats_before = pool.get_statistics();
        let _chunk2 = pool.allocate(1024).expect("operation failed");
        let stats_after = pool.get_statistics();

        assert_eq!(stats_after.cache_hits, stats_before.cache_hits + 1);
    }

    #[test]
    fn test_gpu_tensor_cache() -> Result<()> {
        let mut cache = GpuTensorCache::new(2, 1024 * 1024);

        let tensor1 = Tensor::zeros(&[10, 10])?;
        let tensor2 = Tensor::zeros(&[5, 5])?;
        let tensor3 = Tensor::zeros(&[20, 20])?;

        // Cache tensors
        cache.cache_tensor("tensor1".to_string(), tensor1, Some(0.8))?;
        cache.cache_tensor("tensor2".to_string(), tensor2, Some(0.6))?;

        // Retrieve cached tensor
        assert!(cache.get_tensor("tensor1").is_some());

        // Cache third tensor (should evict least important)
        cache.cache_tensor("tensor3".to_string(), tensor3, Some(0.9))?;

        // tensor2 should be evicted (lowest importance)
        assert!(cache.get_tensor("tensor2").is_none());
        assert!(cache.get_tensor("tensor1").is_some());
        assert!(cache.get_tensor("tensor3").is_some());

        Ok(())
    }

    #[test]
    fn test_gpu_optimization_recommendations() {
        let stats = GpuCacheStatistics {
            cache_stats: CacheStatistics {
                current_size: 100,
                max_size: 100,
                hit_rate: 0.5, // Low hit rate
            },
            memory_stats: GpuMemoryStats {
                fragmentation_ratio: 0.5, // High fragmentation
                ..Default::default()
            },
            memory_usage_percentage: 95.0, // Very high usage
            cache_efficiency: 0.5,
            average_tensor_age: 7200.0, // 2 hours
            fragmentation_ratio: 0.5,
        };

        let recommendations = GpuMemoryOptimizer::analyze_and_recommend(&stats);

        assert_eq!(recommendations.priority, "High");
        assert!(!recommendations.recommendations.is_empty());
        assert!(recommendations.estimated_improvement > 0.0);
    }
}