oarust 0.20.1

GPU-first semantic computing runtime written in Rust
Documentation
//! Typed, capability-checked training precision selection.
//!
//! The roadmap's precision policy distinguishes three planes: activation and
//! operand storage, accumulation inside operations, and optimizer state. OA's
//! admitted configurations today are:
//!
//! | request | activation/operand storage | accumulation | optimizer state |
//! |---|---|---|---|
//! | `F32` (default) | F32 | F32 | F32 |
//! | `F16Storage` | F16 operands in lowered matmuls | F32 | F32 |
//!
//! The F16-storage route lowers admitted matmul operations through private
//! cast workspaces into the FP16-storage GEMM kernels; outputs, accumulation,
//! master parameters, and optimizer moments stay F32. Its admitted training
//! companion is [`crate::ml::optim::GradScaler`]. BF16, master weights, and
//! activation checkpointing remain deferred independent qualifications.
//!
//! Two selection channels exist:
//!
//! - **Typed (runtime- and fit-scoped)** — [`PrecisionPolicy::resolve`] validates
//!   the request against the device's enabled capability surface and fails closed
//!   when the request cannot be honored. [`PrecisionPolicy::enter`] activates the
//!   validated selection on one [`crate::Runtime`] for the lifetime of the
//!   returned [`PrecisionScope`], and [`crate::ml::TrainingFitOptions::precision`]
//!   applies the same scope to one managed fit without mutating process state.
//! - **Environment** — `OA_FORCE_PRECISION=FP16` opts the process into the
//!   lowering silently when no runtime-scoped override is active: a device
//!   without the capability falls back to F32 with no signal.
//!   [`PrecisionPolicy::current`] makes both channels honest by reporting the
//!   active scoped policy or what the environment channel actually resolved to
//!   on one runtime.

use crate::{Error, Result, runtime::RuntimeHandle};

/// Requested activation/operand storage precision.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum StoragePrecision {
	/// Four-byte float storage throughout — the default.
	F32,
	/// FP16 operand storage inside lowered matmuls with F32 accumulation.
	F16,
}

/// A typed precision request for one training run or scoped region.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PrecisionPolicy {
	/// Requested activation/operand storage precision.
	pub storage: StoragePrecision,
}

/// The planes a resolved precision selection actually runs at, as reported
/// against one runtime's device contract.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EffectivePrecision {
	/// The request that was resolved.
	pub requested: PrecisionPolicy,
	/// Effective activation/operand storage. Differs from the request when
	/// the environment channel silently fell back.
	pub activation_storage: StoragePrecision,
	/// Accumulation precision inside lowered operations. Always F32 in the
	/// admitted configurations.
	pub accumulation: StoragePrecision,
	/// Optimizer parameter/moment state precision. Always F32 in the
	/// admitted configurations.
	pub optimizer_state: StoragePrecision,
	/// Whether the effective configuration requires a gradient scaler for
	/// training (`F16` storage routes admit only scaled training).
	pub scaler_required: bool,
}

/// RAII guard activating a capability-validated [`PrecisionPolicy`] on one
/// [`crate::Runtime`].
///
/// Restores the runtime's previous precision override (or environment fallback)
/// when dropped or explicitly closed via [`Self::close`]. Dropping never
/// submits or waits on Vulkan work.
pub struct PrecisionScope {
	runtime: RuntimeHandle,
	previous: Option<StoragePrecision>,
	effective: EffectivePrecision,
	active: bool,
}

impl PrecisionScope {
	/// Return the resolved effective precision active inside this scope.
	#[inline]
	#[must_use]
	pub const fn effective(&self) -> EffectivePrecision {
		self.effective
	}

	/// Restore the previous precision policy early (idempotent).
	pub fn close(&mut self) {
		if self.active {
			self.runtime.replace_precision_override(self.previous);
			self.active = false;
		}
	}
}

impl Drop for PrecisionScope {
	fn drop(&mut self) {
		self.close();
	}
}

impl PrecisionPolicy {
	/// The default F32-everywhere policy.
	#[inline]
	#[must_use]
	pub const fn f32() -> Self {
		Self {
			storage: StoragePrecision::F32,
		}
	}

	/// Request FP16 operand storage in lowered matmuls. Requires a gradient
	/// scaler companion for training.
	#[inline]
	#[must_use]
	pub const fn f16_storage() -> Self {
		Self {
			storage: StoragePrecision::F16,
		}
	}

	/// Resolve this request against one runtime's device contract.
	///
	/// Unlike the environment channel, typed resolution fails closed: an
	/// `F16Storage` request on a device whose enabled capability surface
	/// lacks `shaderFloat16` + 16-bit storage-buffer access is an error
	/// rather than a silent F32 fallback.
	///
	/// # Errors
	///
	/// Returns an error when the requested storage precision is not admitted
	/// by the device contract.
	pub fn resolve(&self, runtime: &crate::runtime::Runtime) -> Result<EffectivePrecision> {
		match self.storage {
			StoragePrecision::F32 => Ok(EffectivePrecision {
				requested: *self,
				activation_storage: StoragePrecision::F32,
				accumulation: StoragePrecision::F32,
				optimizer_state: StoragePrecision::F32,
				scaler_required: false,
			}),
			StoragePrecision::F16 => {
				if !runtime.handle().fp16_storage_capable() {
					return Err(Error::invalid_argument(
						"F16-storage precision is not admitted on this device: the enabled \
						 capability surface lacks shaderFloat16 + 16-bit storage-buffer access",
					));
				}
				Ok(EffectivePrecision {
					requested: *self,
					activation_storage: StoragePrecision::F16,
					accumulation: StoragePrecision::F32,
					optimizer_state: StoragePrecision::F32,
					scaler_required: true,
				})
			}
		}
	}

	/// Validate and activate this precision policy on `runtime` until the
	/// returned [`PrecisionScope`] is dropped or closed.
	///
	/// Fails closed before changing the runtime's policy when the device does
	/// not admit the requested storage precision. Scopes nest cleanly and never
	/// affect other runtimes or process environment variables.
	///
	/// # Errors
	///
	/// Returns an error when [`Self::resolve`] rejects the policy on `runtime`.
	pub fn enter(&self, runtime: &crate::runtime::Runtime) -> Result<PrecisionScope> {
		let effective = self.resolve(runtime)?;
		let handle = runtime.handle();
		let previous = handle.replace_precision_override(Some(self.storage));
		Ok(PrecisionScope {
			runtime: handle,
			previous,
			effective,
			active: true,
		})
	}

	/// Report the effective precision currently active on `runtime`.
	///
	/// When a [`PrecisionScope`] is active on `runtime`, reports that scoped
	/// selection; otherwise reports what the process-wide environment channel
	/// (`OA_FORCE_PRECISION`) resolves to — including silent fallbacks, so
	/// requested and effective precision stay distinguishable in any report.
	pub fn current(runtime: &crate::runtime::Runtime) -> EffectivePrecision {
		if let Some(storage) = runtime.handle().precision_override() {
			let requested = Self { storage };
			return requested.resolve(runtime).unwrap_or(EffectivePrecision {
				requested,
				activation_storage: StoragePrecision::F32,
				accumulation: StoragePrecision::F32,
				optimizer_state: StoragePrecision::F32,
				scaler_required: false,
			});
		}
		let requested =
			match crate::core::env_flag::EnvFlag::get_string("OA_FORCE_PRECISION", "").as_str() {
				"FP16" | "BF16" | "Q8" => Self::f16_storage(),
				_ => Self::f32(),
			};
		// BF16 and Q8 tokens reach the same FP16-storage lowering family in
		// the current provider surface; the F32 fallback rule is the
		// provider's: when the capability is absent the lowering is skipped
		// and operands stay F32.
		match requested.resolve(runtime) {
			Ok(effective) => effective,
			Err(_) => EffectivePrecision {
				requested,
				activation_storage: StoragePrecision::F32,
				accumulation: StoragePrecision::F32,
				optimizer_state: StoragePrecision::F32,
				scaler_required: false,
			},
		}
	}
}

impl EffectivePrecision {
	/// Whether the effective planes match the request — false marks a silent
	/// fallback that reports must surface.
	#[inline]
	#[must_use]
	pub const fn is_exact(&self) -> bool {
		matches!(
			(self.activation_storage, self.requested.storage),
			(StoragePrecision::F32, StoragePrecision::F32)
				| (StoragePrecision::F16, StoragePrecision::F16)
		)
	}
}