Skip to main content

oa/ml/
metric.rs

1//! Explicit host observations for machine-learning metrics.
2
3mod classification;
4mod confusion;
5mod curves;
6mod perplexity;
7mod regression;
8mod topk;
9mod weighted;
10
11pub use classification::AccuracyCount;
12pub use confusion::ConfusionCounts;
13pub use curves::StreamingBinaryCurves;
14pub use perplexity::Perplexity;
15pub use regression::RegressionErrors;
16pub use topk::TopKAccuracy;
17pub use weighted::WeightedMean;
18
19use crate::{DType, Error, Matrix, Result, matrix};
20
21/// Read one scalar FP32 loss value.
22///
23/// This is an explicit host-observation boundary: pending work is submitted and
24/// the producing event is awaited before the value is returned.
25///
26/// # Errors
27///
28/// Returns an error unless `loss` contains exactly one F32 value, or submission,
29/// completion, or readback fails.
30pub fn scalar_loss(loss: &Matrix) -> Result<f32> {
31	if loss.dtype() != DType::F32 || loss.num_elements() != 1 {
32		return Err(Error::invalid_argument(format!(
33			"ml scalar_loss requires exactly one F32 value; found shape {:?} {}",
34			loss.shape(),
35			loss.dtype().token()
36		)));
37	}
38	Ok(loss.read_f32()?[0])
39}
40
41/// Compute last-axis categorical accuracy as a fraction in `[0, 1]`.
42///
43/// Argmax and counting execute on the owning device. Only the resulting U32
44/// scalar crosses the host boundary; this function then waits for that scalar.
45/// Equal maximum logits select the first class, matching the OA C++ contract.
46///
47/// # Errors
48///
49/// Returns an error when [`matrix::categorical_accuracy_count`] rejects the
50/// logits or labels, or submission, completion, or scalar readback fails.
51pub fn accuracy(logits: &Matrix, labels: &Matrix) -> Result<f32> {
52	let count = matrix::categorical_accuracy_count(logits, labels)?;
53	let correct = count.read::<u32>()?[0];
54	Ok(correct as f32 / labels.num_elements() as f32)
55}
56
57/// Per-class prediction/label counts behind one-vs-rest metrics.
58///
59/// Logits and labels are read back and the last-axis argmax runs on the host —
60/// the same explicit host-observation boundary as [`scalar_loss`], sized for
61/// evaluation batches rather than hot loops. A class absent from both
62/// predictions and labels reports `0.0` for all derived values rather than a
63/// NaN. Equal maximum logits select the first class, matching the OA device
64/// argmax contract.
65///
66/// # Errors
67///
68/// Returns an error when `logits` is not rank-two F32 `["samples", C]`,
69/// `labels` does not carry one U32/I32 label per row, `class_index` is out of
70/// range for the class axis, or readback fails.
71pub fn precision_recall_f1(
72	logits: &Matrix,
73	labels: &Matrix,
74	class_index: usize,
75) -> Result<ClassificationCounts> {
76	let &[samples, num_classes] = logits.shape() else {
77		return Err(Error::invalid_argument(format!(
78			"metric logits must be rank two; found {:?}",
79			logits.shape(),
80		)));
81	};
82	if logits.dtype() != DType::F32 {
83		return Err(Error::invalid_argument(format!(
84			"metric logits must be F32; found {}",
85			logits.dtype().token(),
86		)));
87	}
88	if class_index >= num_classes {
89		return Err(Error::invalid_argument(format!(
90			"class index {class_index} exceeds the class axis {num_classes}"
91		)));
92	}
93	if labels.num_elements() != samples {
94		return Err(Error::invalid_argument(format!(
95			"metric logits predict {samples} rows; found {} labels",
96			labels.num_elements(),
97		)));
98	}
99	let logits_flat = logits.read_f32()?;
100	let labels_flat = labels.read::<u32>()?;
101	let mut counts = ClassificationCounts::default();
102	for (row, label) in labels_flat.iter().enumerate() {
103		let prediction = logits_flat[row * num_classes..(row + 1) * num_classes]
104			.iter()
105			.enumerate()
106			.max_by(|a, b| a.1.total_cmp(b.1).then(b.0.cmp(&a.0)))
107			.map(|(index, _)| index)
108			.unwrap_or(0);
109		let predicted_class = prediction == class_index;
110		let actual_class = *label as usize == class_index;
111		match (predicted_class, actual_class) {
112			(true, true) => counts.true_positives += 1,
113			(true, false) => counts.false_positives += 1,
114			(false, true) => counts.false_negatives += 1,
115			(false, false) => counts.true_negatives += 1,
116		}
117	}
118	Ok(counts)
119}
120
121/// Per-class prediction/label counts behind [`precision_recall_f1`].
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
123pub struct ClassificationCounts {
124	pub true_positives: u64,
125	pub false_positives: u64,
126	pub true_negatives: u64,
127	pub false_negatives: u64,
128}
129
130impl ClassificationCounts {
131	/// Precision `TP / (TP + FP)`; `0.0` when the class was never predicted.
132	pub fn precision(&self) -> f32 {
133		let predicted = self.true_positives + self.false_positives;
134		if predicted == 0 {
135			return 0.0;
136		}
137		self.true_positives as f32 / predicted as f32
138	}
139
140	/// Recall `TP / (TP + FN)`; `0.0` when the class has no labels.
141	pub fn recall(&self) -> f32 {
142		let actual = self.true_positives + self.false_negatives;
143		if actual == 0 {
144			return 0.0;
145		}
146		self.true_positives as f32 / actual as f32
147	}
148
149	/// Harmonic mean of precision and recall; `0.0` when both are zero.
150	pub fn f1(&self) -> f32 {
151		let (p, r) = (self.precision(), self.recall());
152		if p + r == 0.0 {
153			return 0.0;
154		}
155		2.0 * p * r / (p + r)
156	}
157}
158
159/// Macro-averaged F1 over `num_classes` one-vs-rest counts.
160///
161/// # Errors
162///
163/// Returns an error when `num_classes` is zero or any per-class count fails.
164pub fn macro_f1(logits: &Matrix, labels: &Matrix, num_classes: usize) -> Result<f32> {
165	if num_classes == 0 {
166		return Err(Error::invalid_argument(
167			"macro_f1 requires at least one class",
168		));
169	}
170	let mut total = 0.0;
171	for class_index in 0..num_classes {
172		total += precision_recall_f1(logits, labels, class_index)?.f1();
173	}
174	Ok(total / num_classes as f32)
175}
176
177/// Binary ROC AUC from positive-class `scores` against binary `labels`.
178///
179/// Scores and labels are read back and ranked on the host with the
180/// Mann-Whitney formulation (tied scores share average rank), so the value is
181/// exactly the probability that a random positive outranks a random negative.
182/// This is an evaluation-side host metric, not a capture-safe device op.
183///
184/// # Errors
185///
186/// Returns an error when `scores` is not F32, shapes disagree, labels are not
187/// `0`/`1`, or one class is absent.
188pub fn roc_auc(scores: &Matrix, labels: &Matrix) -> Result<f32> {
189	if scores.dtype() != DType::F32 {
190		return Err(Error::invalid_argument(format!(
191			"roc_auc requires F32 scores; found {}",
192			scores.dtype().token()
193		)));
194	}
195	let scores = scores.read_f32()?;
196	let labels = labels.read::<u32>()?;
197	if scores.len() != labels.len() {
198		return Err(Error::invalid_argument(format!(
199			"roc_auc has {} scores for {} labels",
200			scores.len(),
201			labels.len(),
202		)));
203	}
204	if scores.is_empty() || labels.iter().any(|label| *label > 1) {
205		return Err(Error::invalid_argument(
206			"roc_auc requires a nonempty binary label set",
207		));
208	}
209	let positives = labels.iter().filter(|label| **label == 1).count();
210	if positives == 0 || positives == labels.len() {
211		return Err(Error::invalid_argument(
212			"roc_auc requires at least one positive and one negative label",
213		));
214	}
215	// Average-rank assignment for ties, ascending by score.
216	let mut order: Vec<usize> = (0..scores.len()).collect();
217	order.sort_by(|a, b| scores[*a].total_cmp(&scores[*b]));
218	let mut rank_sum_positive = 0.0_f64;
219	let mut index = 0;
220	while index < order.len() {
221		let mut end = index + 1;
222		while end < order.len() && scores[order[end]] == scores[order[index]] {
223			end += 1;
224		}
225		let average_rank = (index + 1 + end) as f64 / 2.0;
226		for &sample in &order[index..end] {
227			if labels[sample] == 1 {
228				rank_sum_positive += average_rank;
229			}
230		}
231		index = end;
232	}
233	let negatives = (labels.len() - positives) as f64;
234	let positives = positives as f64;
235	Ok(((rank_sum_positive - positives * (positives + 1.0) / 2.0) / (positives * negatives)) as f32)
236}
237
238/// Exact binary PR-AUC (step-wise average precision) from positive-class `scores`
239/// against binary `labels`.
240///
241/// Scores and labels are read back and sorted descending on the host; tied scores
242/// collapse to one threshold step (`sum((recall_i - recall_{i-1}) * precision_i)`).
243/// This is an evaluation-side exact host metric; for bounded-memory streaming
244/// evaluation over partitioned batches, use [`StreamingBinaryCurves`].
245///
246/// # Errors
247///
248/// Returns an error when `scores` is not F32, shapes disagree, labels are not
249/// `0`/`1`, any score is non-finite, or no positive label is present.
250pub fn pr_auc(scores: &Matrix, labels: &Matrix) -> Result<f32> {
251	if scores.dtype() != DType::F32 {
252		return Err(Error::invalid_argument(format!(
253			"pr_auc requires F32 scores; found {}",
254			scores.dtype().token()
255		)));
256	}
257	let scores = scores.read_f32()?;
258	let labels = labels.read::<u32>()?;
259	if scores.len() != labels.len() {
260		return Err(Error::invalid_argument(format!(
261			"pr_auc has {} scores for {} labels",
262			scores.len(),
263			labels.len()
264		)));
265	}
266	if scores.is_empty()
267		|| scores.iter().any(|score| !score.is_finite())
268		|| labels.iter().any(|label| *label > 1)
269	{
270		return Err(Error::invalid_argument(
271			"pr_auc requires finite scores and a nonempty binary label set",
272		));
273	}
274	let total_positives = labels.iter().filter(|label| **label == 1).count();
275	if total_positives == 0 {
276		return Err(Error::invalid_argument(
277			"pr_auc requires at least one positive label",
278		));
279	}
280	let mut order: Vec<usize> = (0..scores.len()).collect();
281	order.sort_by(|a, b| scores[*b].total_cmp(&scores[*a]));
282	let total_pos = total_positives as f64;
283	let mut tp = 0.0_f64;
284	let mut fp = 0.0_f64;
285	let mut prev_recall = 0.0_f64;
286	let mut ap = 0.0_f64;
287	let mut index = 0;
288	while index < order.len() {
289		let mut end = index + 1;
290		while end < order.len() && scores[order[end]] == scores[order[index]] {
291			end += 1;
292		}
293		for &sample in &order[index..end] {
294			if labels[sample] == 1 {
295				tp += 1.0;
296			} else {
297				fp += 1.0;
298			}
299		}
300		let recall = tp / total_pos;
301		let precision = tp / (tp + fp);
302		ap += (recall - prev_recall) * precision;
303		prev_recall = recall;
304		index = end;
305	}
306	Ok(ap as f32)
307}
308
309/// Corpus BLEU over token sequences with a brevity penalty, no smoothing.
310///
311/// Counts clipped n-gram matches up to `max_order` across the corpus and
312/// combines them geometrically. A corpus with no matches at any order returns
313/// `0.0`; hypotheses shorter than references receive the standard
314/// `exp(1 - ref/hyp)` penalty. Inputs are host token sequences — this is an
315/// evaluation-side metric, not a device op.
316///
317/// # Errors
318///
319/// Returns an error when `max_order` is zero, the corpora differ in length, a
320/// hypothesis is empty, or any sequence is shorter than `max_order`.
321pub fn bleu(references: &[Vec<u32>], hypotheses: &[Vec<u32>], max_order: usize) -> Result<f32> {
322	use std::collections::HashMap;
323	if max_order == 0 {
324		return Err(Error::invalid_argument("bleu requires max_order >= 1"));
325	}
326	if references.len() != hypotheses.len() {
327		return Err(Error::invalid_argument(format!(
328			"bleu received {} references for {} hypotheses",
329			references.len(),
330			hypotheses.len(),
331		)));
332	}
333	if hypotheses.iter().any(Vec::is_empty) {
334		return Err(Error::invalid_argument("bleu hypotheses must be nonempty"));
335	}
336	let ngrams = |sequence: &[u32], order: usize| -> HashMap<Vec<u32>, u64> {
337		let mut counts = HashMap::new();
338		for window in sequence.windows(order) {
339			*counts.entry(window.to_vec()).or_insert(0) += 1;
340		}
341		counts
342	};
343	let mut matches = vec![0_u64; max_order];
344	let mut candidates = vec![0_u64; max_order];
345	let (mut ref_len, mut hyp_len) = (0_u64, 0_u64);
346	for (reference, hypothesis) in references.iter().zip(hypotheses.iter()) {
347		ref_len += reference.len() as u64;
348		hyp_len += hypothesis.len() as u64;
349		for (order, (matched, total)) in
350			(1..=max_order).zip(matches.iter_mut().zip(candidates.iter_mut()))
351		{
352			if hypothesis.len() < order {
353				continue;
354			}
355			let reference_counts = ngrams(reference, order);
356			*total += (hypothesis.len() + 1 - order) as u64;
357			for (gram, count) in ngrams(hypothesis, order) {
358				*matched += count.min(reference_counts.get(&gram).copied().unwrap_or(0));
359			}
360		}
361	}
362	if candidates.contains(&0) {
363		return Err(Error::invalid_argument(
364			"bleu requires every hypothesis to cover every n-gram order",
365		));
366	}
367	if matches.contains(&0) {
368		return Ok(0.0);
369	}
370	let log_precision: f64 = matches
371		.iter()
372		.zip(candidates.iter())
373		.map(|(matched, total)| (*matched as f64 / *total as f64).ln())
374		.sum::<f64>()
375		/ max_order as f64;
376	let brevity = if hyp_len >= ref_len {
377		1.0
378	} else {
379		(1.0 - ref_len as f64 / hyp_len as f64).exp()
380	};
381	Ok((brevity * log_precision.exp()) as f32)
382}