oarust 0.19.0

GPU-first semantic computing runtime written in Rust
Documentation
//! Mergeable top-k accuracy counting.

use super::classification::AccuracyCount;
use crate::{Error, Matrix, Result};

/// Additive top-k correct/sample counters.
///
/// A sample is correct when its label's logit is at least the k-th largest
/// logit in its row — the inclusive boundary convention, so ties at the
/// threshold count as correct and k ≥ classes is trivially perfect. Like the
/// confusion counts, observation happens at the evaluation plane: logits and
/// labels cross the host boundary once per evaluation batch and the ranking
/// derivation runs host-side. The mergeable state is the same additive
/// correct/samples pair categorical accuracy uses, so partitioned evaluation
/// merges exactly.
pub struct TopKAccuracy {
	k: usize,
	counts: AccuracyCount,
}

impl TopKAccuracy {
	/// Construct empty state for rank `k`.
	#[inline]
	#[must_use]
	pub fn new(k: usize) -> Self {
		Self {
			k: k.max(1),
			counts: AccuracyCount::new(),
		}
	}

	/// Return the rank this instance counts.
	#[must_use]
	pub const fn k(&self) -> usize {
		self.k
	}

	/// Observe one batch of `[N, C]` logits and `[N]` labels on the host.
	///
	/// This is the evaluation-plane boundary: one readback per evaluation
	/// batch, never inside a training loop.
	///
	/// # Errors
	///
	/// Returns an error for mismatched geometry, unsupported dtypes, or
	/// readback failure.
	pub fn update_device(&mut self, logits: &Matrix, labels: &Matrix) -> Result<()> {
		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",
			));
		}
		let logits_host = logits.read_f32()?;
		let labels_host = labels.read::<u32>()?;
		let mut correct = 0_u64;
		for (row, &label) in labels_host.iter().enumerate() {
			let label = label as usize;
			if label >= classes {
				return Err(Error::invalid_argument(format!(
					"top-k accuracy label {label} exceeds the {classes} classes"
				)));
			}
			let base = row * classes;
			let row_logits = &logits_host[base..base + classes];
			let label_score = row_logits[label];
			// Inclusive boundary: correct when at most k − 1 logits strictly
			// exceed the label's, so k-way ties at the threshold all count.
			let strictly_above = row_logits
				.iter()
				.filter(|&&value| value > label_score)
				.count();
			if strictly_above < self.k {
				correct += 1;
			}
		}
		self.counts.update(correct, rows as u64);
		Ok(())
	}

	/// Merge another instance's accumulated counts.
	///
	/// # Errors
	///
	/// Returns an error when the ranks differ.
	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);
		Ok(())
	}

	/// Return correct / samples, or NaN when empty.
	///
	/// # Errors
	///
	/// Returns the resolution error when pending device counts cannot be observed.
	pub fn result(&mut self) -> Result<f64> {
		self.counts.result()
	}

	/// Return the accumulated sample denominator.
	#[must_use]
	pub const fn samples(&self) -> u64 {
		self.counts.counts().1
	}

	/// Drop all accumulated counts.
	pub fn reset(&mut self) {
		self.counts.reset();
	}
}