oarust 0.19.0

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** — [`PrecisionPolicy::resolve`] validates the request against
//!   the device's enabled capability surface and fails closed when the
//!   request cannot be honored. The result reports the effective planes
//!   through [`EffectivePrecision`].
//! - **Environment** — `OA_FORCE_PRECISION=FP16` opts the process into the
//!   lowering silently: a device without the capability falls back to F32
//!   with no signal. [`PrecisionPolicy::current`] makes that channel honest
//!   by reporting what it actually resolved to on one runtime.
//!
//! Precision selection is process-wide in the current implementation: the
//! lowering decision is read per operation from the environment channel. The
//! typed policy validates and reports but does not scope lowering to one
//! fit; callers set the environment mode before training.

use crate::{Error, Result};

/// 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.
#[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,
}

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

	/// Request FP16 operand storage in lowered matmuls. Requires a gradient
	/// scaler companion for training.
	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,
				})
			}
		}
	}

	/// Report what the process-wide environment channel
	/// (`OA_FORCE_PRECISION`) resolves to on one runtime — including silent
	/// fallbacks, so requested and effective precision stay distinguishable
	/// in any report that uses the untyped channel.
	pub fn current(runtime: &crate::runtime::Runtime) -> EffectivePrecision {
		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.
	pub fn is_exact(&self) -> bool {
		self.activation_storage == self.requested.storage
	}
}