burn_train/learner/
summary.rs

1use core::cmp::Ordering;
2use std::{
3    fmt::Display,
4    path::{Path, PathBuf},
5};
6
7use crate::{
8    logger::FileMetricLogger,
9    metric::store::{Aggregate, EventStore, LogEventStore, Split},
10};
11
12/// Contains the metric value at a given time.
13pub struct MetricEntry {
14    /// The step at which the metric was recorded (i.e., epoch).
15    pub step: usize,
16    /// The metric value.
17    pub value: f64,
18}
19
20/// Contains the summary of recorded values for a given metric.
21pub struct MetricSummary {
22    /// The metric name.
23    pub name: String,
24    /// The metric entries.
25    pub entries: Vec<MetricEntry>,
26}
27
28impl MetricSummary {
29    fn new<E: EventStore>(
30        event_store: &mut E,
31        metric: &str,
32        split: Split,
33        num_epochs: usize,
34    ) -> Option<Self> {
35        let entries = (1..=num_epochs)
36            .filter_map(|epoch| {
37                event_store
38                    .find_metric(metric, epoch, Aggregate::Mean, split)
39                    .map(|value| MetricEntry { step: epoch, value })
40            })
41            .collect::<Vec<_>>();
42
43        if entries.is_empty() {
44            None
45        } else {
46            Some(Self {
47                name: metric.to_string(),
48                entries,
49            })
50        }
51    }
52}
53
54/// Contains the summary of recorded metrics for the training and validation steps.
55pub struct SummaryMetrics {
56    /// Training metrics summary.
57    pub train: Vec<MetricSummary>,
58    /// Validation metrics summary.
59    pub valid: Vec<MetricSummary>,
60}
61
62/// Detailed training summary.
63pub struct LearnerSummary {
64    /// The number of epochs completed.
65    pub epochs: usize,
66    /// The summary of recorded metrics during training.
67    pub metrics: SummaryMetrics,
68    /// The model name (only recorded within the learner).
69    pub(crate) model: Option<String>,
70}
71
72impl LearnerSummary {
73    /// Creates a new learner summary for the specified metrics.
74    ///
75    /// # Arguments
76    ///
77    /// * `directory` - The directory containing the training artifacts (checkpoints and logs).
78    /// * `metrics` - The list of metrics to collect for the summary.
79    pub fn new<S: AsRef<str>>(directory: impl AsRef<Path>, metrics: &[S]) -> Result<Self, String> {
80        let directory = directory.as_ref();
81        if !directory.exists() {
82            return Err(format!(
83                "Artifact directory does not exist at: {}",
84                directory.display()
85            ));
86        }
87
88        let mut event_store = LogEventStore::default();
89
90        let logger = FileMetricLogger::new(directory);
91        if !logger.split_exists(Split::Train) && !logger.split_exists(Split::Valid) {
92            return Err(format!(
93                "No training or validation artifacts found at: {}",
94                directory.display()
95            ));
96        }
97
98        // Number of recorded epochs
99        let epochs = logger.epochs();
100
101        event_store.register_logger(logger);
102
103        let train_summary = metrics
104            .iter()
105            .filter_map(|metric| {
106                MetricSummary::new(&mut event_store, metric.as_ref(), Split::Train, epochs)
107            })
108            .collect::<Vec<_>>();
109
110        let valid_summary = metrics
111            .iter()
112            .filter_map(|metric| {
113                MetricSummary::new(&mut event_store, metric.as_ref(), Split::Valid, epochs)
114            })
115            .collect::<Vec<_>>();
116
117        Ok(Self {
118            epochs,
119            metrics: SummaryMetrics {
120                train: train_summary,
121                valid: valid_summary,
122            },
123            model: None,
124        })
125    }
126
127    pub(crate) fn with_model(mut self, name: String) -> Self {
128        self.model = Some(name);
129        self
130    }
131}
132
133impl Display for LearnerSummary {
134    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135        // Compute the max length for each column
136        let split_train = "Train";
137        let split_valid = "Valid";
138        let max_split_len = "Split".len().max(split_train.len()).max(split_valid.len());
139        let mut max_metric_len = "Metric".len();
140        for metric in self.metrics.train.iter() {
141            max_metric_len = max_metric_len.max(metric.name.len());
142        }
143        for metric in self.metrics.valid.iter() {
144            max_metric_len = max_metric_len.max(metric.name.len());
145        }
146
147        // Summary header
148        writeln!(
149            f,
150            "{:=>width_symbol$} Learner Summary {:=>width_symbol$}",
151            "",
152            "",
153            width_symbol = 24,
154        )?;
155
156        if let Some(model) = &self.model {
157            writeln!(f, "Model:\n{model}")?;
158        }
159        writeln!(f, "Total Epochs: {epochs}\n\n", epochs = self.epochs)?;
160
161        // Metrics table header
162        writeln!(
163            f,
164            "| {:<width_split$} | {:<width_metric$} | Min.     | Epoch    | Max.     | Epoch    |\n|{:->width_split$}--|{:->width_metric$}--|----------|----------|----------|----------|",
165            "Split",
166            "Metric",
167            "",
168            "",
169            width_split = max_split_len,
170            width_metric = max_metric_len,
171        )?;
172
173        // Table entries
174        fn cmp_f64(a: &f64, b: &f64) -> Ordering {
175            match (a.is_nan(), b.is_nan()) {
176                (true, true) => Ordering::Equal,
177                (true, false) => Ordering::Greater,
178                (false, true) => Ordering::Less,
179                _ => a.partial_cmp(b).unwrap(),
180            }
181        }
182
183        fn fmt_val(val: f64) -> String {
184            if val < 1e-2 {
185                // Use scientific notation for small values which would otherwise be truncated
186                format!("{val:<9.3e}")
187            } else {
188                format!("{val:<9.3}")
189            }
190        }
191
192        let mut write_metrics_summary =
193            |metrics: &[MetricSummary], split: &str| -> std::fmt::Result {
194                for metric in metrics.iter() {
195                    if metric.entries.is_empty() {
196                        continue; // skip metrics with no recorded values
197                    }
198
199                    // Compute the min & max for each metric
200                    let metric_min = metric
201                        .entries
202                        .iter()
203                        .min_by(|a, b| cmp_f64(&a.value, &b.value))
204                        .unwrap();
205                    let metric_max = metric
206                        .entries
207                        .iter()
208                        .max_by(|a, b| cmp_f64(&a.value, &b.value))
209                        .unwrap();
210
211                    writeln!(
212                        f,
213                        "| {:<width_split$} | {:<width_metric$} | {}| {:<9?}| {}| {:<9?}|",
214                        split,
215                        metric.name,
216                        fmt_val(metric_min.value),
217                        metric_min.step,
218                        fmt_val(metric_max.value),
219                        metric_max.step,
220                        width_split = max_split_len,
221                        width_metric = max_metric_len,
222                    )?;
223                }
224
225                Ok(())
226            };
227
228        write_metrics_summary(&self.metrics.train, split_train)?;
229        write_metrics_summary(&self.metrics.valid, split_valid)?;
230
231        Ok(())
232    }
233}
234
235#[derive(Clone)]
236/// Learning summary config.
237pub struct LearnerSummaryConfig {
238    pub(crate) directory: PathBuf,
239    pub(crate) metrics: Vec<String>,
240}
241
242impl LearnerSummaryConfig {
243    /// Create the learning summary.
244    pub fn init(&self) -> Result<LearnerSummary, String> {
245        LearnerSummary::new(&self.directory, &self.metrics[..])
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    #[should_panic = "Summary artifacts should exist"]
255    fn test_artifact_dir_should_exist() {
256        let dir = "/tmp/learner-summary-not-found";
257        let _summary = LearnerSummary::new(dir, &["Loss"]).expect("Summary artifacts should exist");
258    }
259
260    #[test]
261    #[should_panic = "Summary artifacts should exist"]
262    fn test_train_valid_artifacts_should_exist() {
263        let dir = "/tmp/test-learner-summary-empty";
264        std::fs::create_dir_all(dir).ok();
265        let _summary = LearnerSummary::new(dir, &["Loss"]).expect("Summary artifacts should exist");
266    }
267
268    #[test]
269    fn test_summary_should_be_empty() {
270        let dir = Path::new("/tmp/test-learner-summary-empty-metrics");
271        std::fs::create_dir_all(dir).unwrap();
272        std::fs::create_dir_all(dir.join("train/epoch-1")).unwrap();
273        std::fs::create_dir_all(dir.join("valid/epoch-1")).unwrap();
274        let summary = LearnerSummary::new(dir.to_str().unwrap(), &["Loss"])
275            .expect("Summary artifacts should exist");
276
277        assert_eq!(summary.epochs, 1);
278
279        assert_eq!(summary.metrics.train.len(), 0);
280        assert_eq!(summary.metrics.valid.len(), 0);
281
282        std::fs::remove_dir_all(dir).unwrap();
283    }
284
285    #[test]
286    fn test_summary_should_be_collected() {
287        let dir = Path::new("/tmp/test-learner-summary");
288        let train_dir = dir.join("train/epoch-1");
289        let valid_dir = dir.join("valid/epoch-1");
290        std::fs::create_dir_all(dir).unwrap();
291        std::fs::create_dir_all(&train_dir).unwrap();
292        std::fs::create_dir_all(&valid_dir).unwrap();
293
294        std::fs::write(train_dir.join("Loss.log"), "1.0\n2.0").expect("Unable to write file");
295        std::fs::write(valid_dir.join("Loss.log"), "1.0").expect("Unable to write file");
296
297        let summary = LearnerSummary::new(dir.to_str().unwrap(), &["Loss"])
298            .expect("Summary artifacts should exist");
299
300        assert_eq!(summary.epochs, 1);
301
302        // Only Loss metric
303        assert_eq!(summary.metrics.train.len(), 1);
304        assert_eq!(summary.metrics.valid.len(), 1);
305
306        // Aggregated train metric entries for 1 epoch
307        let train_metric = &summary.metrics.train[0];
308        assert_eq!(train_metric.name, "Loss");
309        assert_eq!(train_metric.entries.len(), 1);
310        let entry = &train_metric.entries[0];
311        assert_eq!(entry.step, 1); // epoch = 1
312        assert_eq!(entry.value, 1.5); // (1 + 2) / 2
313
314        // Aggregated valid metric entries for 1 epoch
315        let valid_metric = &summary.metrics.valid[0];
316        assert_eq!(valid_metric.name, "Loss");
317        assert_eq!(valid_metric.entries.len(), 1);
318        let entry = &valid_metric.entries[0];
319        assert_eq!(entry.step, 1); // epoch = 1
320        assert_eq!(entry.value, 1.0);
321
322        std::fs::remove_dir_all(dir).unwrap();
323    }
324}