use super::classification::AccuracyCount;
use crate::{Error, Matrix, Result};
pub struct TopKAccuracy {
k: usize,
counts: AccuracyCount,
pending_checked: Vec<(Matrix, Matrix, usize)>,
}
impl TopKAccuracy {
#[inline]
#[must_use]
pub fn new(k: usize) -> Self {
Self {
k: k.max(1),
counts: AccuracyCount::new(),
pending_checked: Vec::new(),
}
}
#[must_use]
pub const fn k(&self) -> usize {
self.k
}
fn validate_batch(&self, logits: &Matrix, labels: &Matrix) -> Result<(usize, usize)> {
let shape = logits.shape();
if shape.len() != 2 || labels.shape() != [shape[0]] {
return Err(Error::invalid_argument(format!(
"top-{} accuracy requires [N, C] logits and [N] labels; found {:?} and {:?}",
self.k,
shape,
labels.shape()
)));
}
let rows = shape[0];
let classes = shape[1];
if rows == 0 || classes == 0 {
return Err(Error::invalid_argument(
"top-k accuracy requires nonempty batches",
));
}
Ok((rows, classes))
}
pub fn update_device(&mut self, logits: &Matrix, labels: &Matrix) -> Result<()> {
let (rows, classes) = self.validate_batch(logits, labels)?;
let (correct, invalid) =
crate::ml::matrix::topk_accuracy_count_checked(logits, labels, self.k)?;
let pair = crate::matrix::concat(&[correct, invalid], 0)?.read::<u32>()?;
if pair[1] > 0 {
return Err(Error::invalid_argument(format!(
"top-{} accuracy found {} out-of-range label(s) for {classes} classes",
self.k, pair[1]
)));
}
self.counts.update(u64::from(pair[0]), rows as u64);
Ok(())
}
pub fn record_device(&mut self, logits: &Matrix, labels: &Matrix) -> Result<()> {
let (rows, classes) = self.validate_batch(logits, labels)?;
let (correct, invalid) =
crate::ml::matrix::topk_accuracy_count_checked(logits, labels, self.k)?;
self.counts.update(0, rows as u64);
self.pending_checked.push((correct, invalid, classes));
Ok(())
}
pub fn resolve(&mut self) -> Result<()> {
self.counts.resolve()?;
if self.pending_checked.is_empty() {
return Ok(());
}
let pending = std::mem::take(&mut self.pending_checked);
for group in pending.chunks(128) {
let mut scalars = Vec::with_capacity(group.len() * 2);
for (correct, invalid, _) in group {
scalars.push(correct.clone());
scalars.push(invalid.clone());
}
let values = crate::matrix::concat(&scalars, 0)?.read::<u32>()?;
for (idx, (_, _, classes)) in group.iter().enumerate() {
let correct = values[idx * 2];
let invalid = values[idx * 2 + 1];
if invalid > 0 {
return Err(Error::invalid_argument(format!(
"top-{} accuracy found {invalid} out-of-range label(s) for {classes} classes",
self.k
)));
}
self.counts.update(u64::from(correct), 0);
}
}
Ok(())
}
#[must_use]
pub fn has_pending(&self) -> bool {
self.counts.has_pending() || !self.pending_checked.is_empty()
}
pub fn merge(&mut self, other: &mut Self) -> Result<()> {
if self.k != other.k {
return Err(Error::invalid_argument(format!(
"cannot merge top-{} accuracy with top-{} accuracy",
self.k, other.k
)));
}
self.counts.merge(&mut other.counts);
self.pending_checked.append(&mut other.pending_checked);
Ok(())
}
pub fn result(&mut self) -> Result<f64> {
self.resolve()?;
self.counts.result()
}
#[must_use]
pub const fn samples(&self) -> u64 {
self.counts.counts().1
}
pub fn reset(&mut self) {
self.counts.reset();
self.pending_checked.clear();
}
}