1use crate::{Matrix, Result, ml::matrix::training_accumulate};
4
5use super::{TrainingCallbackContext, TrainingSnapshot};
6
7pub trait TrainingMetric {
17 fn name(&self) -> &str;
18 fn reset(&mut self);
19 fn update_step(&mut self, state: TrainingSnapshot);
20 fn result(&self) -> f64;
21
22 fn commit_epoch(&mut self, _context: &mut TrainingCallbackContext<'_>) -> Result<()> {
29 Ok(())
30 }
31
32 fn observe_batch(&mut self, _prediction: &Matrix, _target: &Matrix) -> Result<()> {
40 Ok(())
41 }
42}
43
44pub struct AccuracyMetric {
56 name: String,
57 accumulator: Matrix,
58 cursor: Matrix,
59 previous_correct: u64,
60 previous_samples: u64,
61 last: f64,
62}
63
64impl AccuracyMetric {
65 pub fn new(name: impl Into<String>) -> Result<Self> {
75 Self::new_with_runtime(&crate::Runtime::current()?, name)
76 }
77
78 pub fn new_with_runtime(runtime: &crate::Runtime, name: impl Into<String>) -> Result<Self> {
87 Ok(Self {
88 name: name.into(),
89 accumulator: Matrix::new_from_f32_on(runtime, [1], &[0.0])?,
90 cursor: Matrix::new_from_slice_on(runtime, [2], &[0_u32, 0])?,
91 previous_correct: 0,
92 previous_samples: 0,
93 last: f64::NAN,
94 })
95 }
96
97 pub fn observer(&self) -> AccuracyObserver {
103 AccuracyObserver {
104 accumulator: self.accumulator.clone(),
105 cursor: self.cursor.clone(),
106 }
107 }
108}
109
110#[derive(Clone)]
116pub struct AccuracyObserver {
117 accumulator: Matrix,
118 cursor: Matrix,
119}
120
121impl AccuracyObserver {
122 pub fn observe(&self, logits: &Matrix, targets: &Matrix) -> Result<()> {
129 let correct = logits.categorical_accuracy_count(targets)?;
130 let correct_f32 = correct.cast_i32_f32()?;
131 training_accumulate(&self.accumulator, &correct_f32, &self.cursor, 1.0)
132 }
133}
134
135impl TrainingMetric for AccuracyMetric {
136 fn name(&self) -> &str {
137 &self.name
138 }
139
140 fn reset(&mut self) {
141 self.last = f64::NAN;
146 }
147
148 fn update_step(&mut self, _state: TrainingSnapshot) {}
149
150 fn result(&self) -> f64 {
151 self.last
152 }
153
154 fn observe_batch(&mut self, prediction: &Matrix, target: &Matrix) -> Result<()> {
155 self.observer().observe(prediction, target)
156 }
157
158 fn commit_epoch(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<()> {
159 let cumulative = self.accumulator.read_f32()?[0] as u64;
160 let correct = cumulative - self.previous_correct;
161 self.previous_correct = cumulative;
162 let total_samples = context.snapshot().total_samples();
163 let samples = total_samples - self.previous_samples;
164 self.previous_samples = total_samples;
165 self.last = if samples == 0 {
166 f64::NAN
167 } else {
168 correct as f64 / samples as f64
169 };
170 context.commit_metric("train", &self.name.clone(), self.last);
171 Ok(())
172 }
173}
174
175#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
177pub enum LossAggregation {
178 #[default]
179 Mean,
180 Last,
181}
182
183pub struct LossMetric {
185 name: String,
186 aggregation: LossAggregation,
187 sum: f64,
188 last: f64,
189 count: u64,
190}
191
192impl LossMetric {
193 pub fn new(name: impl Into<String>, aggregation: LossAggregation) -> Self {
194 Self {
195 name: name.into(),
196 aggregation,
197 sum: 0.0,
198 last: 0.0,
199 count: 0,
200 }
201 }
202
203 pub const fn count(&self) -> u64 {
204 self.count
205 }
206
207 pub fn mean(&self) -> f64 {
208 if self.count == 0 {
209 0.0
210 } else {
211 self.sum / self.count as f64
212 }
213 }
214
215 pub fn last(&self) -> f64 {
216 if self.count == 0 { 0.0 } else { self.last }
217 }
218}
219
220impl Default for LossMetric {
221 fn default() -> Self {
222 Self::new("loss", LossAggregation::Mean)
223 }
224}
225
226impl TrainingMetric for LossMetric {
227 fn name(&self) -> &str {
228 &self.name
229 }
230
231 fn reset(&mut self) {
232 self.sum = 0.0;
233 self.last = 0.0;
234 self.count = 0;
235 }
236
237 fn update_step(&mut self, state: TrainingSnapshot) {
238 if let Some(loss) = state.last_loss() {
239 self.sum += f64::from(loss);
240 self.last = f64::from(loss);
241 self.count = self.count.saturating_add(1);
242 }
243 }
244
245 fn result(&self) -> f64 {
246 match self.aggregation {
247 LossAggregation::Mean => self.mean(),
248 LossAggregation::Last => self.last(),
249 }
250 }
251}