optirs-learned 0.3.2

OptiRS learned optimizers and meta-learning
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
// Performance tracking for transformer-based optimizer

use super::config::PerformanceConfig;
use super::meta_learning::MetaLearningResult;
use super::TrainingMetrics;
use crate::error::Result;
use scirs2_core::ndarray::Array1;
use scirs2_core::numeric::Float;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::fmt::Debug;
use std::time::{Duration, Instant};

/// Performance metrics for transformer optimizer
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceMetrics {
    /// Training metrics
    pub training_metrics: TrainingMetricsCollection,

    /// Inference metrics
    pub inference_metrics: InferenceMetricsCollection,

    /// Memory usage metrics
    pub memory_metrics: MemoryMetricsCollection,

    /// Computation time metrics
    pub timing_metrics: TimingMetricsCollection,

    /// Model quality metrics
    pub quality_metrics: QualityMetricsCollection,

    /// Resource utilization metrics
    pub resource_metrics: ResourceMetricsCollection,

    /// Optimization metrics
    pub optimization_metrics: OptimizationMetricsCollection,
}

/// Transformer performance tracker
pub struct TransformerPerformanceTracker<
    T: Float + Debug + scirs2_core::ndarray::ScalarOperand + Send + Sync + 'static,
> {
    /// Configuration
    config: PerformanceConfig,

    /// Performance metrics
    metrics: PerformanceMetrics,

    /// Loss history
    loss_history: VecDeque<f64>,

    /// Training step timings
    step_timings: VecDeque<Duration>,

    /// Meta-learning results history
    meta_results_history: VecDeque<MetaLearningResult<T>>,

    /// Training metrics history
    training_history: VecDeque<TrainingMetrics>,

    /// Memory usage samples
    memory_samples: VecDeque<MemorySample>,

    /// Performance baselines
    baselines: PerformanceBaselines,

    /// Alert thresholds
    alert_thresholds: AlertThresholds,

    /// Performance trends
    trends: PerformanceTrends,

    /// Profiling data
    profiling_data: ProfilingData,

    /// Start time for tracking session
    session_start: Instant,
}

impl<T: Float + Debug + scirs2_core::ndarray::ScalarOperand + Send + Sync + 'static> Default
    for TransformerPerformanceTracker<T>
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Float + Debug + scirs2_core::ndarray::ScalarOperand + Send + Sync + 'static>
    TransformerPerformanceTracker<T>
{
    /// Create new performance tracker
    pub fn new() -> Self {
        let config = PerformanceConfig::default();

        Self {
            config,
            metrics: PerformanceMetrics::new(),
            loss_history: VecDeque::new(),
            step_timings: VecDeque::new(),
            meta_results_history: VecDeque::new(),
            training_history: VecDeque::new(),
            memory_samples: VecDeque::new(),
            baselines: PerformanceBaselines::new(),
            alert_thresholds: AlertThresholds::default(),
            trends: PerformanceTrends::new(),
            profiling_data: ProfilingData::new(),
            session_start: Instant::now(),
        }
    }

    /// Create with custom configuration
    pub fn with_config(config: PerformanceConfig) -> Self {
        let mut tracker = Self::new();
        tracker.config = config;
        tracker
    }

    /// Record optimization step performance
    pub fn record_optimization_step(&mut self, duration: Duration, update: &Array1<T>) {
        // Record timing
        self.step_timings.push_back(duration);
        if self.step_timings.len() > self.config.max_history_size {
            self.step_timings.pop_front();
        }

        // Update timing metrics
        self.metrics.timing_metrics.record_step_time(duration);

        // Analyze update quality
        let update_norm = self.compute_array_norm(update);
        self.metrics
            .optimization_metrics
            .record_update_norm(update_norm);

        // Update trends
        self.trends.update_step_timing(duration);

        // Check for performance alerts
        self.check_performance_alerts(duration, update_norm);
    }

    /// Record training epoch performance
    pub fn record_training_epoch(&mut self, metrics: TrainingMetrics) {
        self.training_history.push_back(metrics.clone());
        if self.training_history.len() > self.config.max_history_size {
            self.training_history.pop_front();
        }

        // Update training metrics
        self.metrics.training_metrics.record_epoch(
            metrics.loss,
            metrics.training_time,
            metrics.convergence_rate,
        );

        // Update trends
        self.trends.update_training_loss(metrics.loss);
        self.trends
            .update_convergence_rate(metrics.convergence_rate);

        // Check for convergence alerts
        self.check_convergence_alerts(&metrics);
    }

    /// Record meta-learning step performance
    pub fn record_meta_step(&mut self, result: MetaLearningResult<T>) {
        self.meta_results_history.push_back(result.clone());
        if self.meta_results_history.len() > 100 {
            self.meta_results_history.pop_front();
        }

        // Update meta-learning metrics
        self.metrics.training_metrics.record_meta_step(
            result.meta_loss,
            result.computation_time,
            result.task_adaptations.len(),
        );

        // Update trends
        self.trends.update_meta_loss(result.meta_loss);
        self.trends
            .update_adaptation_efficiency(result.task_adaptations.len() as f64);
    }

    /// Record inference performance
    pub fn record_inference(&mut self, input_size: usize, duration: Duration, output_quality: f64) {
        self.metrics
            .inference_metrics
            .record_inference(input_size, duration, output_quality);

        // Update throughput calculations
        let throughput = input_size as f64 / duration.as_secs_f64();
        self.metrics.inference_metrics.update_throughput(throughput);

        // Update trends
        self.trends.update_inference_latency(duration);
        self.trends.update_inference_quality(output_quality);
    }

    /// Record memory usage
    pub fn record_memory_usage(&mut self, usage: MemoryUsage) {
        let sample = MemorySample {
            timestamp: std::time::SystemTime::now(),
            usage,
        };

        self.memory_samples.push_back(sample.clone());
        if self.memory_samples.len() > self.config.max_history_size {
            self.memory_samples.pop_front();
        }

        // Update memory metrics
        self.metrics.memory_metrics.record_usage(usage);

        // Feed the resource-utilization history too. Without this
        // `average_memory_utilization()` stayed `None` forever even though the
        // caller *was* supplying real samples — the same write-only-history bug
        // the CPU metric had.
        self.metrics
            .resource_metrics
            .record_memory_usage(usage.total_memory as f64);

        // Update trends
        self.trends.update_memory_usage(usage.total_memory);

        // Check for memory alerts
        self.check_memory_alerts(&usage);
    }

    /// Record loss value
    pub fn record_loss(&mut self, loss: f64) {
        self.loss_history.push_back(loss);
        if self.loss_history.len() > self.config.max_history_size {
            self.loss_history.pop_front();
        }

        // Update quality metrics
        self.metrics.quality_metrics.record_loss(loss);

        // Update trends
        self.trends.update_loss(loss);
    }

    /// Profile operation performance
    pub fn profile_operation<F, R>(&mut self, operation_name: &str, operation: F) -> Result<R>
    where
        F: FnOnce() -> Result<R>,
    {
        let start_time = Instant::now();
        let result = operation();
        let duration = start_time.elapsed();

        // Record profiling data
        self.profiling_data
            .record_operation(operation_name.to_string(), duration);

        // Update timing metrics
        self.metrics
            .timing_metrics
            .record_operation_time(operation_name, duration);

        result
    }

    /// Generate performance report
    pub fn generate_report(&self) -> PerformanceReport {
        let session_duration = self.session_start.elapsed();

        PerformanceReport {
            session_duration,
            total_optimization_steps: self.step_timings.len(),
            total_training_epochs: self.training_history.len(),
            total_meta_steps: self.meta_results_history.len(),

            // Average performance metrics
            average_step_time: self.calculate_average_step_time(),
            average_loss: self.calculate_average_loss(),
            current_convergence_rate: self.calculate_current_convergence_rate(),

            // Memory statistics
            peak_memory_usage: self.calculate_peak_memory_usage(),
            average_memory_usage: self.calculate_average_memory_usage(),

            // Quality metrics
            best_loss: self.calculate_best_loss(),
            loss_improvement: self.calculate_loss_improvement(),

            // Performance trends
            loss_trend: self.trends.get_loss_trend(),
            convergence_trend: self.trends.get_convergence_trend(),
            memory_trend: self.trends.get_memory_trend(),

            // Alert summary
            performance_alerts: self.get_recent_alerts(),

            // Resource utilization. `None` means "never sampled", which is a
            // different claim from "measured zero".
            cpu_utilization: self.metrics.resource_metrics.average_cpu_utilization(),
            memory_utilization: self.metrics.resource_metrics.average_memory_utilization(),

            // Model quality assessment
            quality_score: self.calculate_overall_quality_score(),

            // Recommendations
            recommendations: self.generate_recommendations(),
        }
    }

    /// Get loss history
    pub fn get_loss_history(&self) -> &VecDeque<f64> {
        &self.loss_history
    }

    /// Get current performance metrics
    pub fn get_metrics(&self) -> &PerformanceMetrics {
        &self.metrics
    }

    /// Get performance trends
    pub fn get_trends(&self) -> &PerformanceTrends {
        &self.trends
    }

    /// Set performance baselines
    pub fn set_baselines(&mut self, baselines: PerformanceBaselines) {
        self.baselines = baselines;
    }

    /// Reset all performance tracking
    pub fn reset(&mut self) {
        self.metrics = PerformanceMetrics::new();
        self.loss_history.clear();
        self.step_timings.clear();
        self.meta_results_history.clear();
        self.training_history.clear();
        self.memory_samples.clear();
        self.trends.reset();
        self.profiling_data.reset();
        self.session_start = Instant::now();
    }

    /// Helper methods
    fn compute_array_norm(&self, array: &Array1<T>) -> f64 {
        let sum_squares: T = array
            .iter()
            .map(|&x| x * x)
            .fold(T::zero(), |acc, x| acc + x);
        sum_squares.sqrt().to_f64().unwrap_or(0.0)
    }

    fn calculate_average_step_time(&self) -> Duration {
        if self.step_timings.is_empty() {
            Duration::new(0, 0)
        } else {
            let total: Duration = self.step_timings.iter().sum();
            total / self.step_timings.len() as u32
        }
    }

    fn calculate_average_loss(&self) -> f64 {
        if self.loss_history.is_empty() {
            0.0
        } else {
            self.loss_history.iter().sum::<f64>() / self.loss_history.len() as f64
        }
    }

    fn calculate_current_convergence_rate(&self) -> f64 {
        if let Some(recent_training) = self.training_history.back() {
            recent_training.convergence_rate
        } else {
            0.0
        }
    }

    fn calculate_peak_memory_usage(&self) -> usize {
        self.memory_samples
            .iter()
            .map(|sample| sample.usage.total_memory)
            .max()
            .unwrap_or(0)
    }

    fn calculate_average_memory_usage(&self) -> f64 {
        if self.memory_samples.is_empty() {
            0.0
        } else {
            let total: usize = self
                .memory_samples
                .iter()
                .map(|s| s.usage.total_memory)
                .sum();
            total as f64 / self.memory_samples.len() as f64
        }
    }

    fn calculate_best_loss(&self) -> f64 {
        self.loss_history
            .iter()
            .fold(f64::INFINITY, |min, &loss| min.min(loss))
    }

    fn calculate_loss_improvement(&self) -> f64 {
        if self.loss_history.len() < 2 {
            return 0.0;
        }

        // `len() >= 2` was checked above, so both ends exist; reading through
        // the fallible accessors keeps that reasoning local.
        let (Some(&initial_loss), Some(&final_loss)) =
            (self.loss_history.front(), self.loss_history.back())
        else {
            return 0.0;
        };

        if initial_loss > 0.0 {
            (initial_loss - final_loss) / initial_loss
        } else {
            0.0
        }
    }

    fn calculate_overall_quality_score(&self) -> f64 {
        // Weighted combination of various quality metrics
        let loss_score = 1.0 - (self.calculate_average_loss() / 10.0).min(1.0);
        let convergence_score = self.calculate_current_convergence_rate();
        let stability_score = 1.0 - self.trends.get_loss_volatility().min(1.0);

        (loss_score * 0.4 + convergence_score * 0.3 + stability_score * 0.3).clamp(0.0, 1.0)
    }

    fn generate_recommendations(&self) -> Vec<String> {
        let mut recommendations = Vec::new();

        // Loss-based recommendations
        if self.trends.get_loss_trend() > 0.0 {
            recommendations
                .push("Loss is increasing. Consider reducing learning rate.".to_string());
        }

        // Memory-based recommendations
        if self.calculate_peak_memory_usage() > 1024 * 1024 * 1024 {
            // 1GB
            recommendations.push(
                "High memory usage detected. Consider enabling memory compression.".to_string(),
            );
        }

        // Performance-based recommendations
        if self.calculate_average_step_time() > Duration::from_millis(100) {
            recommendations.push(
                "Slow optimization steps. Consider reducing model size or batch size.".to_string(),
            );
        }

        // Convergence-based recommendations
        if self.calculate_current_convergence_rate() < 0.1 {
            recommendations.push(
                "Low convergence rate. Consider adjusting meta-learning parameters.".to_string(),
            );
        }

        recommendations
    }

    fn check_performance_alerts(&mut self, duration: Duration, update_norm: f64) {
        // Check for slow steps
        if duration > self.alert_thresholds.max_step_time {
            self.record_alert(AlertType::SlowStep, format!("Step took {:?}", duration));
        }

        // Check for gradient explosion
        if update_norm > self.alert_thresholds.max_gradient_norm {
            self.record_alert(
                AlertType::GradientExplosion,
                format!("Update norm: {:.6}", update_norm),
            );
        }

        // Check for gradient vanishing
        if update_norm < self.alert_thresholds.min_gradient_norm {
            self.record_alert(
                AlertType::GradientVanishing,
                format!("Update norm: {:.6}", update_norm),
            );
        }
    }

    fn check_convergence_alerts(&mut self, metrics: &TrainingMetrics) {
        // Check for training stagnation
        if metrics.convergence_rate < self.alert_thresholds.min_convergence_rate {
            self.record_alert(
                AlertType::TrainingStagnation,
                format!("Convergence rate: {:.6}", metrics.convergence_rate),
            );
        }

        // Check for loss increase
        if let Some(previous) = self.training_history.iter().rev().nth(1) {
            if metrics.loss > previous.loss * 1.1 {
                // 10% increase
                self.record_alert(
                    AlertType::LossIncrease,
                    format!(
                        "Loss increased from {:.6} to {:.6}",
                        previous.loss, metrics.loss
                    ),
                );
            }
        }
    }

    fn check_memory_alerts(&mut self, usage: &MemoryUsage) {
        // Check for high memory usage
        if usage.total_memory > self.alert_thresholds.max_memory_usage {
            self.record_alert(
                AlertType::HighMemoryUsage,
                format!("Memory usage: {} bytes", usage.total_memory),
            );
        }

        // Check for memory leaks
        if let Some(previous) = self.memory_samples.back() {
            let memory_increase = usage
                .total_memory
                .saturating_sub(previous.usage.total_memory);
            if memory_increase > 1024 * 1024 * 100 {
                // 100MB increase
                self.record_alert(
                    AlertType::PossibleMemoryLeak,
                    format!("Memory increased by {} bytes", memory_increase),
                );
            }
        }
    }

    fn record_alert(&mut self, alert_type: AlertType, message: String) {
        let alert = PerformanceAlert {
            alert_type,
            message,
            timestamp: std::time::SystemTime::now(),
        };

        self.metrics.quality_metrics.record_alert(alert);
    }

    fn get_recent_alerts(&self) -> Vec<PerformanceAlert> {
        self.metrics.quality_metrics.get_recent_alerts(10)
    }
}

/// Performance metrics collections
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrainingMetricsCollection {
    pub total_epochs: usize,
    pub total_training_time: Duration,
    pub average_loss: f64,
    pub best_loss: f64,
    pub convergence_rate: f64,
    pub meta_steps: usize,
    pub task_adaptations: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InferenceMetricsCollection {
    pub total_inferences: usize,
    pub average_latency: Duration,
    pub peak_throughput: f64,
    pub average_quality: f64,
    pub cache_hit_rate: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryMetricsCollection {
    pub peak_usage: usize,
    pub average_usage: f64,
    pub total_allocations: usize,
    pub compression_ratio: f64,
    pub fragmentation_rate: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimingMetricsCollection {
    pub average_step_time: Duration,
    pub total_computation_time: Duration,
    pub operation_timings: HashMap<String, Duration>,
    pub profiling_overhead: Duration,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityMetricsCollection {
    pub loss_statistics: LossStatistics,
    pub convergence_statistics: ConvergenceStatistics,
    pub stability_metrics: StabilityMetrics,
    pub performance_alerts: VecDeque<PerformanceAlert>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceMetricsCollection {
    pub cpu_usage_history: VecDeque<f64>,
    pub memory_usage_history: VecDeque<f64>,
    pub disk_io_metrics: DiskIOMetrics,
    pub network_metrics: NetworkMetrics,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizationMetricsCollection {
    pub update_norm_history: VecDeque<f64>,
    pub parameter_change_rate: f64,
    pub optimization_efficiency: f64,
    pub adaptive_learning_metrics: AdaptiveLearningMetrics,
}

/// Supporting data structures
#[derive(Debug, Clone)]
pub struct MemorySample {
    pub timestamp: std::time::SystemTime,
    pub usage: MemoryUsage,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct MemoryUsage {
    pub total_memory: usize,
    pub model_memory: usize,
    pub cache_memory: usize,
    pub temporary_memory: usize,
}

#[derive(Debug, Clone)]
pub struct PerformanceBaselines {
    pub baseline_loss: f64,
    pub baseline_step_time: Duration,
    pub baseline_memory_usage: usize,
    pub baseline_convergence_rate: f64,
}

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

impl PerformanceBaselines {
    pub fn new() -> Self {
        Self {
            baseline_loss: f64::INFINITY,
            baseline_step_time: Duration::new(0, 0),
            baseline_memory_usage: 0,
            baseline_convergence_rate: 0.0,
        }
    }
}

#[derive(Debug, Clone)]
pub struct AlertThresholds {
    pub max_step_time: Duration,
    pub min_convergence_rate: f64,
    pub max_memory_usage: usize,
    pub max_gradient_norm: f64,
    pub min_gradient_norm: f64,
}

impl Default for AlertThresholds {
    fn default() -> Self {
        Self {
            max_step_time: Duration::from_secs(1),
            min_convergence_rate: 0.01,
            max_memory_usage: 2 * 1024 * 1024 * 1024, // 2GB
            max_gradient_norm: 10.0,
            min_gradient_norm: 1e-8,
        }
    }
}

#[derive(Debug, Clone)]
pub struct PerformanceTrends {
    loss_trend: TrendAnalyzer,
    convergence_trend: TrendAnalyzer,
    memory_trend: TrendAnalyzer,
    timing_trend: TrendAnalyzer,
}

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

impl PerformanceTrends {
    pub fn new() -> Self {
        Self {
            loss_trend: TrendAnalyzer::new(100),
            convergence_trend: TrendAnalyzer::new(50),
            memory_trend: TrendAnalyzer::new(100),
            timing_trend: TrendAnalyzer::new(100),
        }
    }

    pub fn update_loss(&mut self, loss: f64) {
        self.loss_trend.add_sample(loss);
    }

    pub fn update_training_loss(&mut self, loss: f64) {
        self.loss_trend.add_sample(loss);
    }

    pub fn update_meta_loss(&mut self, loss: f64) {
        self.loss_trend.add_sample(loss);
    }

    pub fn update_convergence_rate(&mut self, rate: f64) {
        self.convergence_trend.add_sample(rate);
    }

    pub fn update_adaptation_efficiency(&mut self, efficiency: f64) {
        self.convergence_trend.add_sample(efficiency);
    }

    pub fn update_memory_usage(&mut self, usage: usize) {
        self.memory_trend.add_sample(usage as f64);
    }

    pub fn update_step_timing(&mut self, duration: Duration) {
        self.timing_trend.add_sample(duration.as_secs_f64());
    }

    pub fn update_inference_latency(&mut self, duration: Duration) {
        self.timing_trend.add_sample(duration.as_secs_f64());
    }

    pub fn update_inference_quality(&mut self, _quality: f64) {
        // Could be used for quality trend analysis
    }

    pub fn get_loss_trend(&self) -> f64 {
        self.loss_trend.get_trend()
    }

    pub fn get_convergence_trend(&self) -> f64 {
        self.convergence_trend.get_trend()
    }

    pub fn get_memory_trend(&self) -> f64 {
        self.memory_trend.get_trend()
    }

    pub fn get_loss_volatility(&self) -> f64 {
        self.loss_trend.get_volatility()
    }

    pub fn reset(&mut self) {
        self.loss_trend.reset();
        self.convergence_trend.reset();
        self.memory_trend.reset();
        self.timing_trend.reset();
    }
}

#[derive(Debug, Clone)]
pub struct TrendAnalyzer {
    samples: VecDeque<f64>,
    max_samples: usize,
}

impl TrendAnalyzer {
    pub fn new(max_samples: usize) -> Self {
        Self {
            samples: VecDeque::new(),
            max_samples,
        }
    }

    pub fn add_sample(&mut self, value: f64) {
        self.samples.push_back(value);
        if self.samples.len() > self.max_samples {
            self.samples.pop_front();
        }
    }

    pub fn get_trend(&self) -> f64 {
        if self.samples.len() < 2 {
            return 0.0;
        }

        // Simple linear trend calculation
        let n = self.samples.len() as f64;
        let x_sum = (0..self.samples.len()).map(|i| i as f64).sum::<f64>();
        let y_sum = self.samples.iter().sum::<f64>();
        let xy_sum = self
            .samples
            .iter()
            .enumerate()
            .map(|(i, &y)| i as f64 * y)
            .sum::<f64>();
        let x_sq_sum = (0..self.samples.len())
            .map(|i| (i as f64).powi(2))
            .sum::<f64>();

        let denominator = n * x_sq_sum - x_sum * x_sum;
        if denominator.abs() < 1e-10 {
            0.0
        } else {
            (n * xy_sum - x_sum * y_sum) / denominator
        }
    }

    pub fn get_volatility(&self) -> f64 {
        if self.samples.len() < 2 {
            return 0.0;
        }

        let mean = self.samples.iter().sum::<f64>() / self.samples.len() as f64;
        let variance = self
            .samples
            .iter()
            .map(|&x| (x - mean).powi(2))
            .sum::<f64>()
            / self.samples.len() as f64;

        variance.sqrt()
    }

    pub fn reset(&mut self) {
        self.samples.clear();
    }
}

#[derive(Debug, Clone)]
pub struct ProfilingData {
    operation_timings: HashMap<String, VecDeque<Duration>>,
    total_operations: usize,
}

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

impl ProfilingData {
    pub fn new() -> Self {
        Self {
            operation_timings: HashMap::new(),
            total_operations: 0,
        }
    }

    pub fn record_operation(&mut self, operation: String, duration: Duration) {
        let timings = self.operation_timings.entry(operation).or_default();
        timings.push_back(duration);
        if timings.len() > 1000 {
            timings.pop_front();
        }
        self.total_operations += 1;
    }

    pub fn get_average_time(&self, operation: &str) -> Option<Duration> {
        self.operation_timings.get(operation).map(|timings| {
            let total: Duration = timings.iter().sum();
            total / timings.len() as u32
        })
    }

    pub fn reset(&mut self) {
        self.operation_timings.clear();
        self.total_operations = 0;
    }
}

/// Alert system
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceAlert {
    pub alert_type: AlertType,
    pub message: String,
    pub timestamp: std::time::SystemTime,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AlertType {
    SlowStep,
    GradientExplosion,
    GradientVanishing,
    TrainingStagnation,
    LossIncrease,
    HighMemoryUsage,
    PossibleMemoryLeak,
    ConvergenceFailure,
}

/// Performance report
#[derive(Debug, Clone)]
pub struct PerformanceReport {
    pub session_duration: Duration,
    pub total_optimization_steps: usize,
    pub total_training_epochs: usize,
    pub total_meta_steps: usize,
    pub average_step_time: Duration,
    pub average_loss: f64,
    pub current_convergence_rate: f64,
    pub peak_memory_usage: usize,
    pub average_memory_usage: f64,
    pub best_loss: f64,
    pub loss_improvement: f64,
    pub loss_trend: f64,
    pub convergence_trend: f64,
    pub memory_trend: f64,
    pub performance_alerts: Vec<PerformanceAlert>,
    /// Mean observed CPU utilization fraction, or `None` when no sample was ever
    /// recorded. This was an `f64` that reported `0.0` unconditionally because
    /// nothing ever wrote to the CPU history — a fabricated measurement. Feed it
    /// with `ResourceMetricsCollection::record_cpu_utilization`.
    pub cpu_utilization: Option<f64>,
    /// Mean observed memory usage in bytes, or `None` when no sample was ever
    /// recorded.
    pub memory_utilization: Option<f64>,
    pub quality_score: f64,
    pub recommendations: Vec<String>,
}

/// Additional metric structures (simplified implementations)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LossStatistics {
    pub mean: f64,
    pub std_dev: f64,
    pub min: f64,
    pub max: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConvergenceStatistics {
    pub average_rate: f64,
    pub best_rate: f64,
    pub convergence_episodes: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StabilityMetrics {
    pub loss_volatility: f64,
    pub gradient_stability: f64,
    pub convergence_stability: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiskIOMetrics {
    pub total_reads: usize,
    pub total_writes: usize,
    pub total_bytes_read: usize,
    pub total_bytes_written: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkMetrics {
    pub total_requests: usize,
    pub total_bytes_sent: usize,
    pub total_bytes_received: usize,
    pub average_latency: Duration,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdaptiveLearningMetrics {
    pub learning_rate_adjustments: usize,
    pub batch_size_adjustments: usize,
    pub architecture_modifications: usize,
}

/// Implementation of basic functionality for metric collections
impl Default for PerformanceMetrics {
    fn default() -> Self {
        Self::new()
    }
}

impl PerformanceMetrics {
    pub fn new() -> Self {
        Self {
            training_metrics: TrainingMetricsCollection::new(),
            inference_metrics: InferenceMetricsCollection::new(),
            memory_metrics: MemoryMetricsCollection::new(),
            timing_metrics: TimingMetricsCollection::new(),
            quality_metrics: QualityMetricsCollection::new(),
            resource_metrics: ResourceMetricsCollection::new(),
            optimization_metrics: OptimizationMetricsCollection::new(),
        }
    }
}

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

impl TrainingMetricsCollection {
    pub fn new() -> Self {
        Self {
            total_epochs: 0,
            total_training_time: Duration::new(0, 0),
            average_loss: 0.0,
            best_loss: f64::INFINITY,
            convergence_rate: 0.0,
            meta_steps: 0,
            task_adaptations: 0,
        }
    }

    pub fn record_epoch(&mut self, loss: f64, duration: Duration, convergence: f64) {
        self.total_epochs += 1;
        self.total_training_time += duration;
        self.average_loss =
            (self.average_loss * (self.total_epochs - 1) as f64 + loss) / self.total_epochs as f64;
        self.best_loss = self.best_loss.min(loss);
        self.convergence_rate = convergence;
    }

    pub fn record_meta_step(&mut self, loss: f64, _duration: Duration, adaptations: usize) {
        self.meta_steps += 1;
        self.task_adaptations += adaptations;
        self.best_loss = self.best_loss.min(loss);
    }
}

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

impl InferenceMetricsCollection {
    pub fn new() -> Self {
        Self {
            total_inferences: 0,
            average_latency: Duration::new(0, 0),
            peak_throughput: 0.0,
            average_quality: 0.0,
            cache_hit_rate: 0.0,
        }
    }

    pub fn record_inference(&mut self, _input_size: usize, duration: Duration, quality: f64) {
        self.total_inferences += 1;
        self.average_latency = (self.average_latency * (self.total_inferences - 1) as u32
            + duration)
            / self.total_inferences as u32;
        self.average_quality = (self.average_quality * (self.total_inferences - 1) as f64
            + quality)
            / self.total_inferences as f64;
    }

    pub fn update_throughput(&mut self, throughput: f64) {
        self.peak_throughput = self.peak_throughput.max(throughput);
    }
}

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

impl MemoryMetricsCollection {
    pub fn new() -> Self {
        Self {
            peak_usage: 0,
            average_usage: 0.0,
            total_allocations: 0,
            compression_ratio: 1.0,
            fragmentation_rate: 0.0,
        }
    }

    pub fn record_usage(&mut self, usage: MemoryUsage) {
        self.peak_usage = self.peak_usage.max(usage.total_memory);
        self.total_allocations += 1;
        self.average_usage = (self.average_usage * (self.total_allocations - 1) as f64
            + usage.total_memory as f64)
            / self.total_allocations as f64;
    }
}

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

impl TimingMetricsCollection {
    pub fn new() -> Self {
        Self {
            average_step_time: Duration::new(0, 0),
            total_computation_time: Duration::new(0, 0),
            operation_timings: HashMap::new(),
            profiling_overhead: Duration::new(0, 0),
        }
    }

    pub fn record_step_time(&mut self, duration: Duration) {
        self.total_computation_time += duration;
        // Update average step time logic would go here
    }

    pub fn record_operation_time(&mut self, operation: &str, duration: Duration) {
        self.operation_timings
            .insert(operation.to_string(), duration);
    }
}

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

impl QualityMetricsCollection {
    pub fn new() -> Self {
        Self {
            loss_statistics: LossStatistics {
                mean: 0.0,
                std_dev: 0.0,
                min: f64::INFINITY,
                max: f64::NEG_INFINITY,
            },
            convergence_statistics: ConvergenceStatistics {
                average_rate: 0.0,
                best_rate: 0.0,
                convergence_episodes: 0,
            },
            stability_metrics: StabilityMetrics {
                loss_volatility: 0.0,
                gradient_stability: 0.0,
                convergence_stability: 0.0,
            },
            performance_alerts: VecDeque::new(),
        }
    }

    pub fn record_loss(&mut self, loss: f64) {
        self.loss_statistics.min = self.loss_statistics.min.min(loss);
        self.loss_statistics.max = self.loss_statistics.max.max(loss);
    }

    pub fn record_alert(&mut self, alert: PerformanceAlert) {
        self.performance_alerts.push_back(alert);
        if self.performance_alerts.len() > 100 {
            self.performance_alerts.pop_front();
        }
    }

    pub fn get_recent_alerts(&self, count: usize) -> Vec<PerformanceAlert> {
        self.performance_alerts
            .iter()
            .rev()
            .take(count)
            .cloned()
            .collect()
    }
}

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

impl ResourceMetricsCollection {
    pub fn new() -> Self {
        Self {
            cpu_usage_history: VecDeque::new(),
            memory_usage_history: VecDeque::new(),
            disk_io_metrics: DiskIOMetrics {
                total_reads: 0,
                total_writes: 0,
                total_bytes_read: 0,
                total_bytes_written: 0,
            },
            network_metrics: NetworkMetrics {
                total_requests: 0,
                total_bytes_sent: 0,
                total_bytes_received: 0,
                average_latency: Duration::new(0, 0),
            },
        }
    }

    /// Record an observed CPU utilization fraction in `[0, 1]`.
    ///
    /// Nothing inside this crate can measure process CPU time without an FFI
    /// dependency, so the *caller* supplies the sample. Before this existed
    /// `cpu_usage_history` had no writers at all, which made
    /// `get_average_cpu_usage` return `0.0` forever and let the
    /// performance report present that as a measurement of zero CPU use.
    ///
    /// Out-of-range and non-finite samples are ignored rather than recorded, so a
    /// bad caller cannot corrupt the average.
    pub fn record_cpu_utilization(&mut self, fraction: f64) {
        if !fraction.is_finite() || !(0.0..=1.0).contains(&fraction) {
            return;
        }
        self.cpu_usage_history.push_back(fraction);
        while self.cpu_usage_history.len() > 1000 {
            self.cpu_usage_history.pop_front();
        }
    }

    /// Mean recorded CPU utilization, or `None` when nothing has been recorded.
    ///
    /// `None` means "not measured" and is what the report should show; it is not
    /// the same statement as "0% CPU", which is what the old `f64`-returning
    /// version claimed.
    pub fn average_cpu_utilization(&self) -> Option<f64> {
        if self.cpu_usage_history.is_empty() {
            None
        } else {
            Some(self.cpu_usage_history.iter().sum::<f64>() / self.cpu_usage_history.len() as f64)
        }
    }

    /// Number of CPU samples recorded.
    pub fn cpu_sample_count(&self) -> usize {
        self.cpu_usage_history.len()
    }

    /// Record an observed memory usage in bytes. Called by
    /// `TransformerPerformanceTracker::record_memory_usage`.
    pub fn record_memory_usage(&mut self, bytes: f64) {
        if !bytes.is_finite() || bytes < 0.0 {
            return;
        }
        self.memory_usage_history.push_back(bytes);
        while self.memory_usage_history.len() > 1000 {
            self.memory_usage_history.pop_front();
        }
    }

    /// Number of memory samples recorded.
    pub fn memory_sample_count(&self) -> usize {
        self.memory_usage_history.len()
    }

    /// Mean recorded memory usage in bytes, or `None` when nothing has been
    /// recorded. Fed by `TransformerPerformanceTracker::record_memory_usage`.
    pub fn average_memory_utilization(&self) -> Option<f64> {
        if self.memory_usage_history.is_empty() {
            None
        } else {
            Some(
                self.memory_usage_history.iter().sum::<f64>()
                    / self.memory_usage_history.len() as f64,
            )
        }
    }
}

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

impl OptimizationMetricsCollection {
    pub fn new() -> Self {
        Self {
            update_norm_history: VecDeque::new(),
            parameter_change_rate: 0.0,
            optimization_efficiency: 0.0,
            adaptive_learning_metrics: AdaptiveLearningMetrics {
                learning_rate_adjustments: 0,
                batch_size_adjustments: 0,
                architecture_modifications: 0,
            },
        }
    }

    pub fn record_update_norm(&mut self, norm: f64) {
        self.update_norm_history.push_back(norm);
        if self.update_norm_history.len() > 1000 {
            self.update_norm_history.pop_front();
        }
    }
}

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

    #[test]
    fn test_performance_tracker_creation() {
        let tracker = TransformerPerformanceTracker::<f32>::new();
        assert_eq!(tracker.loss_history.len(), 0);
        assert_eq!(tracker.step_timings.len(), 0);
    }

    #[test]
    fn test_record_loss() {
        let mut tracker = TransformerPerformanceTracker::<f32>::new();
        tracker.record_loss(1.5);
        tracker.record_loss(1.2);
        tracker.record_loss(0.9);

        assert_eq!(tracker.loss_history.len(), 3);
        assert_eq!(tracker.calculate_best_loss(), 0.9);
    }

    #[test]
    fn test_trend_analyzer() {
        let mut analyzer = TrendAnalyzer::new(10);

        for i in 0..5 {
            analyzer.add_sample(i as f64);
        }

        let trend = analyzer.get_trend();
        assert!(trend > 0.0); // Should be positive for increasing sequence
    }

    #[test]
    fn test_performance_report_generation() {
        let mut tracker = TransformerPerformanceTracker::<f32>::new();
        tracker.record_loss(2.0);
        tracker.record_loss(1.5);
        tracker.record_loss(1.0);

        let report = tracker.generate_report();
        assert!(report.loss_improvement > 0.0);
        assert_eq!(report.best_loss, 1.0);
    }

    #[test]
    fn test_profiling() {
        let mut tracker = TransformerPerformanceTracker::<f32>::new();

        let result = tracker.profile_operation("test_op", || {
            std::thread::sleep(Duration::from_millis(10));
            Ok(42)
        });

        assert!(result.is_ok());
        assert_eq!(result.expect("profile_operation should succeed"), 42);
    }

    /// F84: `cpu_usage_history` had no writers anywhere in the crate, so
    /// `get_average_cpu_usage()` returned `0.0` forever and the report presented
    /// that as a measured 0% CPU. An unsampled metric must now report `None`.
    #[test]
    fn cpu_utilization_is_none_until_it_is_actually_sampled() {
        let mut metrics = ResourceMetricsCollection::new();
        assert_eq!(metrics.cpu_sample_count(), 0);
        assert_eq!(
            metrics.average_cpu_utilization(),
            None,
            "an unsampled CPU metric must not claim a value"
        );

        metrics.record_cpu_utilization(0.25);
        metrics.record_cpu_utilization(0.75);
        assert_eq!(metrics.cpu_sample_count(), 2);
        let mean = metrics
            .average_cpu_utilization()
            .expect("two samples were recorded");
        assert!((mean - 0.5).abs() < 1e-12, "mean {mean}");

        // Out-of-range and non-finite samples are ignored, not recorded.
        metrics.record_cpu_utilization(-0.1);
        metrics.record_cpu_utilization(1.5);
        metrics.record_cpu_utilization(f64::NAN);
        assert_eq!(
            metrics.cpu_sample_count(),
            2,
            "invalid samples must not enter the history"
        );
    }

    /// The report must carry the same "not measured" distinction.
    #[test]
    fn a_report_reports_unmeasured_resources_as_none() {
        let mut tracker = TransformerPerformanceTracker::<f32>::new();
        tracker.record_loss(1.0);
        let report = tracker.generate_report();
        assert_eq!(
            report.cpu_utilization, None,
            "nothing sampled the CPU, so the report must say so"
        );
        assert_eq!(report.memory_utilization, None);
    }

    /// `memory_usage_history` also had no writers, so a caller that *was*
    /// supplying real memory samples still got `None` back.
    #[test]
    fn recorded_memory_usage_reaches_the_report() {
        let mut tracker = TransformerPerformanceTracker::<f32>::new();
        tracker.record_loss(1.0);
        let sample = |total: usize| MemoryUsage {
            total_memory: total,
            model_memory: total / 2,
            cache_memory: total / 4,
            temporary_memory: total / 4,
        };
        tracker.record_memory_usage(sample(4096));
        tracker.record_memory_usage(sample(8192));

        let report = tracker.generate_report();
        let mean = report
            .memory_utilization
            .expect("two memory samples were recorded");
        assert!((mean - 6144.0).abs() < 1e-9, "mean {mean}");
        assert_eq!(tracker.metrics.resource_metrics.memory_sample_count(), 2);
    }
}