oarust 0.20.0

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

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

/// Additive top-k correct/sample counters with device-side reduction.
///
/// 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. Counting
/// executes on the owning device through [`crate::ml::matrix::topk_accuracy_count_checked`],
/// so `[N, C]` logits never cross the host boundary:
/// - [`TopKAccuracy::update_device`] observes only the 2-element `[correct, invalid]`
///   U32 scalar pair (8 bytes) so out-of-range labels fail immediately.
/// - [`TopKAccuracy::record_device`] keeps both scalar counters device-resident and
///   resolves them in bounded concatenated groups when [`TopKAccuracy::resolve`] or
///   [`TopKAccuracy::result`] is called.
pub struct TopKAccuracy {
	k: usize,
	counts: AccuracyCount,
	pending_checked: Vec<(Matrix, Matrix, usize)>,
}

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(),
			pending_checked: Vec::new(),
		}
	}

	/// Return the rank this instance counts.
	#[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))
	}

	/// Reduce one batch of `[N, C]` logits and `[N]` labels on device and observe
	/// only the resulting `[correct, invalid]` scalar pair (8 bytes).
	///
	/// Full logits and labels never cross the host boundary. Out-of-range labels
	/// (`label >= classes`) fail immediately with [`crate::ErrorKind::InvalidArgument`].
	///
	/// # Errors
	///
	/// Returns an error for mismatched geometry, unsupported dtypes, out-of-range
	/// labels, runtime mismatch, or scalar readback failure.
	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(())
	}

	/// Record one batch of `[N, C]` logits and `[N]` labels completely on device
	/// with deferred grouped scalar readback at [`TopKAccuracy::resolve`] or
	/// [`TopKAccuracy::result`].
	///
	/// Zero host readback occurs per batch; out-of-range labels are reported when
	/// pending device counts are resolved.
	///
	/// # Errors
	///
	/// Returns an error for mismatched geometry, unsupported dtypes, runtime
	/// mismatch, or recording failure.
	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(())
	}

	/// Observe every pending device-reduced top-k count in bounded concatenated groups.
	///
	/// # Errors
	///
	/// Returns concatenation, completion, readback, or out-of-range label errors.
	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(())
	}

	/// Return whether unresolved device counts remain.
	#[must_use]
	pub fn has_pending(&self) -> bool {
		self.counts.has_pending() || !self.pending_checked.is_empty()
	}

	/// Merge another instance's accumulated counts, absorbing unresolved device 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);
		self.pending_checked.append(&mut other.pending_checked);
		Ok(())
	}

	/// Resolve pending device counts and return correct / samples, or NaN when empty.
	///
	/// # Errors
	///
	/// Returns the resolution or out-of-range label error when pending device counts
	/// cannot be observed.
	pub fn result(&mut self) -> Result<f64> {
		self.resolve()?;
		self.counts.result()
	}

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

	/// Drop all accumulated counts, including unresolved device counts.
	pub fn reset(&mut self) {
		self.counts.reset();
		self.pending_checked.clear();
	}
}