use crate::{Matrix, Result, ml::matrix::training_accumulate};
use super::{TrainingCallbackContext, TrainingSnapshot};
pub trait TrainingMetric {
fn name(&self) -> &str;
fn reset(&mut self);
fn update_step(&mut self, state: TrainingSnapshot);
fn result(&self) -> f64;
fn commit_epoch(&mut self, _context: &mut TrainingCallbackContext<'_>) -> Result<()> {
Ok(())
}
fn observe_batch(&mut self, _prediction: &Matrix, _target: &Matrix) -> Result<()> {
Ok(())
}
}
pub struct AccuracyMetric {
name: String,
accumulator: Matrix,
cursor: Matrix,
previous_correct: u64,
previous_samples: u64,
last: f64,
}
impl AccuracyMetric {
pub fn new(name: impl Into<String>) -> Result<Self> {
Self::new_with_runtime(&crate::Runtime::current()?, name)
}
pub fn new_with_runtime(runtime: &crate::Runtime, name: impl Into<String>) -> Result<Self> {
Ok(Self {
name: name.into(),
accumulator: Matrix::new_from_f32_on(runtime, [1], &[0.0])?,
cursor: Matrix::new_from_slice_on(runtime, [2], &[0_u32, 0])?,
previous_correct: 0,
previous_samples: 0,
last: f64::NAN,
})
}
pub fn observer(&self) -> AccuracyObserver {
AccuracyObserver {
accumulator: self.accumulator.clone(),
cursor: self.cursor.clone(),
}
}
}
#[derive(Clone)]
pub struct AccuracyObserver {
accumulator: Matrix,
cursor: Matrix,
}
impl AccuracyObserver {
pub fn observe(&self, logits: &Matrix, targets: &Matrix) -> Result<()> {
let correct = logits.categorical_accuracy_count(targets)?;
let correct_f32 = correct.cast_i32_f32()?;
training_accumulate(&self.accumulator, &correct_f32, &self.cursor, 1.0)
}
}
impl TrainingMetric for AccuracyMetric {
fn name(&self) -> &str {
&self.name
}
fn reset(&mut self) {
self.last = f64::NAN;
}
fn update_step(&mut self, _state: TrainingSnapshot) {}
fn result(&self) -> f64 {
self.last
}
fn observe_batch(&mut self, prediction: &Matrix, target: &Matrix) -> Result<()> {
self.observer().observe(prediction, target)
}
fn commit_epoch(&mut self, context: &mut TrainingCallbackContext<'_>) -> Result<()> {
let cumulative = self.accumulator.read_f32()?[0] as u64;
let correct = cumulative - self.previous_correct;
self.previous_correct = cumulative;
let total_samples = context.snapshot().total_samples();
let samples = total_samples - self.previous_samples;
self.previous_samples = total_samples;
self.last = if samples == 0 {
f64::NAN
} else {
correct as f64 / samples as f64
};
context.commit_metric("train", &self.name.clone(), self.last);
Ok(())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LossAggregation {
#[default]
Mean,
Last,
}
pub struct LossMetric {
name: String,
aggregation: LossAggregation,
sum: f64,
last: f64,
count: u64,
}
impl LossMetric {
pub fn new(name: impl Into<String>, aggregation: LossAggregation) -> Self {
Self {
name: name.into(),
aggregation,
sum: 0.0,
last: 0.0,
count: 0,
}
}
pub const fn count(&self) -> u64 {
self.count
}
pub fn mean(&self) -> f64 {
if self.count == 0 {
0.0
} else {
self.sum / self.count as f64
}
}
pub fn last(&self) -> f64 {
if self.count == 0 { 0.0 } else { self.last }
}
}
impl Default for LossMetric {
fn default() -> Self {
Self::new("loss", LossAggregation::Mean)
}
}
impl TrainingMetric for LossMetric {
fn name(&self) -> &str {
&self.name
}
fn reset(&mut self) {
self.sum = 0.0;
self.last = 0.0;
self.count = 0;
}
fn update_step(&mut self, state: TrainingSnapshot) {
if let Some(loss) = state.last_loss() {
self.sum += f64::from(loss);
self.last = f64::from(loss);
self.count = self.count.saturating_add(1);
}
}
fn result(&self) -> f64 {
match self.aggregation {
LossAggregation::Mean => self.mean(),
LossAggregation::Last => self.last(),
}
}
}