oarust 0.20.0

GPU-first semantic computing runtime written in Rust
Documentation
//! Stateless state-slot accumulation, exact categorical cursor sampling,
//! and device-reduced top-k accuracy counting.
//! Donors: core flat add.gen.slang, Philox uniform, dense sample_logits,
//! and last-axis categorical_accuracy_count.
use crate::runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch};
use crate::{DType, Error, Matrix, OpAttribute, Result};

/// Accumulate `scale × value` into persistent state inside the recorded graph.
///
/// `target` is both read and written: `target = target + scale × value` in
/// accumulation mode, or `target = scale × value` in overwrite mode. The mode
/// is device-driven through `cursor` word 1 — zero accumulates, nonzero
/// overwrites — so captured programs can reset run-scoped state without any
/// host write. Because the update aliases persistent storage, every replay of
/// a capturing program executes it against the accumulated contents; this is
/// the mechanism metric counters, rollout storage, and running statistics use
/// to advance inside compiled training without per-step host readback.
///
/// `target` and `value` must share shape, F32 storage, and Runtime ownership;
/// `cursor` must be a `[2]` U32 matrix on the same Runtime. Cursors are
/// ordinary matrices initialized at allocation time, so a program can bind a
/// permanent accumulation cursor and a permanent overwrite cursor and select
/// per call site.
///
/// This records GPU work but does not submit or wait.
///
/// # Errors
///
/// Returns an error for mismatched shape, dtype, or Runtime ownership, a
/// non-finite scale, element counts exceeding u32, or recording failure.
pub fn training_accumulate(
	target: &Matrix,
	value: &Matrix,
	cursor: &Matrix,
	scale: f32,
) -> Result<()> {
	if target.dtype() != DType::F32
		|| target.shape() != value.shape()
		|| value.dtype() != DType::F32
		|| !target.runtime().same_as(value.runtime())
		|| cursor.dtype() != DType::U32
		|| cursor.shape() != [2]
		|| !target.runtime().same_as(cursor.runtime())
		|| !scale.is_finite()
	{
		return Err(Error::invalid_argument(
			"compiled accumulation shape/dtype/Runtime mismatch",
		));
	}
	let count = u32::try_from(target.num_elements())
		.map_err(|_| Error::resource_exhausted("gradient too large"))?;
	let buffers = [
		BufferBinding::read_write(target.storage()),
		BufferBinding::read(value.storage()),
		BufferBinding::read(cursor.storage()),
	];
	let push = [PushConstant::U32(count), PushConstant::F32(scale)];
	target.runtime().record_semantic(
		ComputeDispatch {
			kernel: KernelId::MlTrainingAccumulateF32,
			buffers: &buffers,
			push_constants: &push,
			workgroups: KernelId::MlTrainingAccumulateF32.linear_workgroups(count),
			indirect: None,
		},
		SemanticDispatch {
			contract: crate::core::operation::ml::TRAINING_ACCUMULATE,
			inputs: &[target, value, cursor],
			outputs: &[target],
			attributes: &[OpAttribute::Float {
				name: "scale".into(),
				value: f64::from(scale),
			}],
		},
	)
}

/// Count inclusive top-k matches and out-of-range labels on the owning device.
///
/// Returns `(correct, invalid)` where each output is a `[1]` U32 Matrix on the
/// logits runtime. A row is counted as correct when its label is in range
/// (`label < classes`) and fewer than `k` logits strictly exceed `logits[row, label]`.
/// Records GPU work without submitting or reading back.
///
/// # Errors
///
/// Returns an error when `k == 0`, `logits` is not nonempty rank-two-or-greater F32,
/// `labels` does not match the leading shape or use U8/U32/I32, inputs belong to
/// different runtimes, extents overflow the shader ABI, or recording fails.
pub fn topk_accuracy_count_checked(
	logits: &Matrix,
	labels: &Matrix,
	k: usize,
) -> Result<(Matrix, Matrix)> {
	if k == 0 {
		return Err(Error::invalid_argument(
			"topk_accuracy_count requires k >= 1",
		));
	}
	if logits.dtype() != DType::F32 || logits.shape().len() < 2 || logits.num_elements() == 0 {
		return Err(Error::invalid_argument(
			"topk_accuracy_count requires nonempty rank-two-or-greater F32 logits",
		));
	}
	let classes = *logits.shape().last().ok_or_else(|| {
		Error::invalid_argument("topk_accuracy_count logits must expose a class axis")
	})?;
	let label_shape = &logits.shape()[..logits.shape().len() - 1];
	if labels.shape() != label_shape {
		return Err(Error::invalid_argument(format!(
			"topk_accuracy_count labels have shape {:?}; expected {:?}",
			labels.shape(),
			label_shape
		)));
	}
	let label_dtype = match labels.dtype() {
		DType::U8 => 0_u32,
		DType::U32 => 1_u32,
		DType::I32 => 2_u32,
		other => {
			return Err(Error::invalid_argument(format!(
				"topk_accuracy_count labels must use U8, U32, or I32; found {}",
				other.token()
			)));
		}
	};
	let runtime = logits.runtime();
	if !runtime.same_as(labels.runtime()) {
		return Err(Error::invalid_argument(
			"topk_accuracy_count inputs must belong to the same runtime",
		));
	}
	let rows = labels.num_elements();
	let rows_u32 = u32::try_from(rows)
		.map_err(|_| Error::resource_exhausted("topk_accuracy_count rows overflow u32"))?;
	let classes_u32 = u32::try_from(classes)
		.map_err(|_| Error::resource_exhausted("topk_accuracy_count classes overflow u32"))?;
	let k_u32 = u32::try_from(k.min(classes)).unwrap_or(classes_u32);
	let correct = Matrix::allocate(runtime, vec![1], 1, DType::U32)?;
	let invalid = Matrix::allocate(runtime, vec![1], 1, DType::U32)?;
	let buffers = [
		BufferBinding::read(logits.storage()),
		BufferBinding::read(labels.storage()),
		BufferBinding::write(correct.storage()),
		BufferBinding::write(invalid.storage()),
	];
	let push = [
		PushConstant::U32(rows_u32),
		PushConstant::U32(classes_u32),
		PushConstant::U32(k_u32),
		PushConstant::U32(label_dtype),
	];
	runtime.record_semantic(
		ComputeDispatch {
			kernel: KernelId::MlTopKAccuracyCountF32,
			buffers: &buffers,
			push_constants: &push,
			workgroups: [1, 1, 1],
			indirect: None,
		},
		SemanticDispatch {
			contract: crate::core::operation::ml::TOPK_ACCURACY_COUNT,
			inputs: &[logits, labels],
			outputs: &[&correct, &invalid],
			attributes: &[OpAttribute::UnsignedInteger {
				name: "k".into(),
				value: k as u64,
			}],
		},
	)?;
	Ok((correct, invalid))
}

/// Count inclusive top-k matches on the owning device as a `[1]` U32 Matrix.
///
/// Mirrors [`crate::matrix::categorical_accuracy_count`] so captured or deferred
/// accuracy pipelines can accumulate top-k counts on device without reading logits
/// back to the host.
///
/// # Errors
///
/// Returns the same validation and recording errors as [`topk_accuracy_count_checked`].
pub fn topk_accuracy_count(logits: &Matrix, labels: &Matrix, k: usize) -> Result<Matrix> {
	Ok(topk_accuracy_count_checked(logits, labels, k)?.0)
}

pub(in crate::ml) fn sample_categorical_cursor(logits: &Matrix, cursor: &Matrix) -> Result<Matrix> {
	let [rows, categories] = logits.shape() else {
		return Err(Error::invalid_argument(
			"categorical cursor requires [rows,categories]",
		));
	};
	if *rows == 0
		|| *categories < 2
		|| logits.dtype() != DType::F32
		|| cursor.dtype() != DType::U32
		|| cursor.shape() != [7]
		|| !logits.runtime().same_as(cursor.runtime())
	{
		return Err(Error::invalid_argument(
			"categorical cursor shape/dtype/Runtime mismatch",
		));
	}
	let rows =
		u32::try_from(*rows).map_err(|_| Error::resource_exhausted("categorical rows overflow"))?;
	let categories = u32::try_from(*categories)
		.map_err(|_| Error::resource_exhausted("categorical categories overflow"))?;
	let output = Matrix::allocate(
		logits.runtime(),
		vec![rows as usize],
		rows as usize,
		DType::I32,
	)?;
	let buffers = [
		BufferBinding::read(logits.storage()),
		BufferBinding::read(cursor.storage()),
		BufferBinding::write(output.storage()),
	];
	let push = [PushConstant::U32(rows), PushConstant::U32(categories)];
	logits.runtime().record_semantic(
		ComputeDispatch {
			kernel: KernelId::MlSampleCategoricalCursorF32,
			buffers: &buffers,
			push_constants: &push,
			workgroups: KernelId::MlSampleCategoricalCursorF32.linear_workgroups(rows),
			indirect: None,
		},
		SemanticDispatch {
			contract: crate::core::operation::ml::SAMPLE_CATEGORICAL_CURSOR,
			inputs: &[logits, cursor],
			outputs: &[&output],
			attributes: &[],
		},
	)?;
	Ok(output)
}