oarust 0.19.0

GPU-first semantic computing runtime written in Rust
Documentation
//! Stateless state-slot accumulation and exact categorical cursor sampling.
//! Donors: core flat add.gen.slang, Philox uniform and dense sample_logits.
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),
			}],
		},
	)
}

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)
}