Skip to main content

oa/ml/
precision.rs

1//! Typed, capability-checked training precision selection.
2//!
3//! The roadmap's precision policy distinguishes three planes: activation and
4//! operand storage, accumulation inside operations, and optimizer state. OA's
5//! admitted configurations today are:
6//!
7//! | request | activation/operand storage | accumulation | optimizer state |
8//! |---|---|---|---|
9//! | `F32` (default) | F32 | F32 | F32 |
10//! | `F16Storage` | F16 operands in lowered matmuls | F32 | F32 |
11//!
12//! The F16-storage route lowers admitted matmul operations through private
13//! cast workspaces into the FP16-storage GEMM kernels; outputs, accumulation,
14//! master parameters, and optimizer moments stay F32. Its admitted training
15//! companion is [`crate::ml::optim::GradScaler`]. BF16, master weights, and
16//! activation checkpointing remain deferred independent qualifications.
17//!
18//! Two selection channels exist:
19//!
20//! - **Typed (runtime- and fit-scoped)** — [`PrecisionPolicy::resolve`] validates
21//!   the request against the device's enabled capability surface and fails closed
22//!   when the request cannot be honored. [`PrecisionPolicy::enter`] activates the
23//!   validated selection on one [`crate::Runtime`] for the lifetime of the
24//!   returned [`PrecisionScope`], and [`crate::ml::TrainingFitOptions::precision`]
25//!   applies the same scope to one managed fit without mutating process state.
26//! - **Environment** — `OA_FORCE_PRECISION=FP16` opts the process into the
27//!   lowering silently when no runtime-scoped override is active: a device
28//!   without the capability falls back to F32 with no signal.
29//!   [`PrecisionPolicy::current`] makes both channels honest by reporting the
30//!   active scoped policy or what the environment channel actually resolved to
31//!   on one runtime.
32
33use crate::{Error, Result, runtime::RuntimeHandle};
34
35/// Requested activation/operand storage precision.
36#[derive(Clone, Copy, Debug, Eq, PartialEq)]
37pub enum StoragePrecision {
38	/// Four-byte float storage throughout — the default.
39	F32,
40	/// FP16 operand storage inside lowered matmuls with F32 accumulation.
41	F16,
42}
43
44/// A typed precision request for one training run or scoped region.
45#[derive(Clone, Copy, Debug, Eq, PartialEq)]
46pub struct PrecisionPolicy {
47	/// Requested activation/operand storage precision.
48	pub storage: StoragePrecision,
49}
50
51/// The planes a resolved precision selection actually runs at, as reported
52/// against one runtime's device contract.
53#[derive(Clone, Copy, Debug, Eq, PartialEq)]
54pub struct EffectivePrecision {
55	/// The request that was resolved.
56	pub requested: PrecisionPolicy,
57	/// Effective activation/operand storage. Differs from the request when
58	/// the environment channel silently fell back.
59	pub activation_storage: StoragePrecision,
60	/// Accumulation precision inside lowered operations. Always F32 in the
61	/// admitted configurations.
62	pub accumulation: StoragePrecision,
63	/// Optimizer parameter/moment state precision. Always F32 in the
64	/// admitted configurations.
65	pub optimizer_state: StoragePrecision,
66	/// Whether the effective configuration requires a gradient scaler for
67	/// training (`F16` storage routes admit only scaled training).
68	pub scaler_required: bool,
69}
70
71/// RAII guard activating a capability-validated [`PrecisionPolicy`] on one
72/// [`crate::Runtime`].
73///
74/// Restores the runtime's previous precision override (or environment fallback)
75/// when dropped or explicitly closed via [`Self::close`]. Dropping never
76/// submits or waits on Vulkan work.
77pub struct PrecisionScope {
78	runtime: RuntimeHandle,
79	previous: Option<StoragePrecision>,
80	effective: EffectivePrecision,
81	active: bool,
82}
83
84impl PrecisionScope {
85	/// Return the resolved effective precision active inside this scope.
86	#[inline]
87	#[must_use]
88	pub const fn effective(&self) -> EffectivePrecision {
89		self.effective
90	}
91
92	/// Restore the previous precision policy early (idempotent).
93	pub fn close(&mut self) {
94		if self.active {
95			self.runtime.replace_precision_override(self.previous);
96			self.active = false;
97		}
98	}
99}
100
101impl Drop for PrecisionScope {
102	fn drop(&mut self) {
103		self.close();
104	}
105}
106
107impl PrecisionPolicy {
108	/// The default F32-everywhere policy.
109	#[inline]
110	#[must_use]
111	pub const fn f32() -> Self {
112		Self {
113			storage: StoragePrecision::F32,
114		}
115	}
116
117	/// Request FP16 operand storage in lowered matmuls. Requires a gradient
118	/// scaler companion for training.
119	#[inline]
120	#[must_use]
121	pub const fn f16_storage() -> Self {
122		Self {
123			storage: StoragePrecision::F16,
124		}
125	}
126
127	/// Resolve this request against one runtime's device contract.
128	///
129	/// Unlike the environment channel, typed resolution fails closed: an
130	/// `F16Storage` request on a device whose enabled capability surface
131	/// lacks `shaderFloat16` + 16-bit storage-buffer access is an error
132	/// rather than a silent F32 fallback.
133	///
134	/// # Errors
135	///
136	/// Returns an error when the requested storage precision is not admitted
137	/// by the device contract.
138	pub fn resolve(&self, runtime: &crate::runtime::Runtime) -> Result<EffectivePrecision> {
139		match self.storage {
140			StoragePrecision::F32 => Ok(EffectivePrecision {
141				requested: *self,
142				activation_storage: StoragePrecision::F32,
143				accumulation: StoragePrecision::F32,
144				optimizer_state: StoragePrecision::F32,
145				scaler_required: false,
146			}),
147			StoragePrecision::F16 => {
148				if !runtime.handle().fp16_storage_capable() {
149					return Err(Error::invalid_argument(
150						"F16-storage precision is not admitted on this device: the enabled \
151						 capability surface lacks shaderFloat16 + 16-bit storage-buffer access",
152					));
153				}
154				Ok(EffectivePrecision {
155					requested: *self,
156					activation_storage: StoragePrecision::F16,
157					accumulation: StoragePrecision::F32,
158					optimizer_state: StoragePrecision::F32,
159					scaler_required: true,
160				})
161			}
162		}
163	}
164
165	/// Validate and activate this precision policy on `runtime` until the
166	/// returned [`PrecisionScope`] is dropped or closed.
167	///
168	/// Fails closed before changing the runtime's policy when the device does
169	/// not admit the requested storage precision. Scopes nest cleanly and never
170	/// affect other runtimes or process environment variables.
171	///
172	/// # Errors
173	///
174	/// Returns an error when [`Self::resolve`] rejects the policy on `runtime`.
175	pub fn enter(&self, runtime: &crate::runtime::Runtime) -> Result<PrecisionScope> {
176		let effective = self.resolve(runtime)?;
177		let handle = runtime.handle();
178		let previous = handle.replace_precision_override(Some(self.storage));
179		Ok(PrecisionScope {
180			runtime: handle,
181			previous,
182			effective,
183			active: true,
184		})
185	}
186
187	/// Report the effective precision currently active on `runtime`.
188	///
189	/// When a [`PrecisionScope`] is active on `runtime`, reports that scoped
190	/// selection; otherwise reports what the process-wide environment channel
191	/// (`OA_FORCE_PRECISION`) resolves to — including silent fallbacks, so
192	/// requested and effective precision stay distinguishable in any report.
193	pub fn current(runtime: &crate::runtime::Runtime) -> EffectivePrecision {
194		if let Some(storage) = runtime.handle().precision_override() {
195			let requested = Self { storage };
196			return requested.resolve(runtime).unwrap_or(EffectivePrecision {
197				requested,
198				activation_storage: StoragePrecision::F32,
199				accumulation: StoragePrecision::F32,
200				optimizer_state: StoragePrecision::F32,
201				scaler_required: false,
202			});
203		}
204		let requested =
205			match crate::core::env_flag::EnvFlag::get_string("OA_FORCE_PRECISION", "").as_str() {
206				"FP16" | "BF16" | "Q8" => Self::f16_storage(),
207				_ => Self::f32(),
208			};
209		// BF16 and Q8 tokens reach the same FP16-storage lowering family in
210		// the current provider surface; the F32 fallback rule is the
211		// provider's: when the capability is absent the lowering is skipped
212		// and operands stay F32.
213		match requested.resolve(runtime) {
214			Ok(effective) => effective,
215			Err(_) => EffectivePrecision {
216				requested,
217				activation_storage: StoragePrecision::F32,
218				accumulation: StoragePrecision::F32,
219				optimizer_state: StoragePrecision::F32,
220				scaler_required: false,
221			},
222		}
223	}
224}
225
226impl EffectivePrecision {
227	/// Whether the effective planes match the request — false marks a silent
228	/// fallback that reports must surface.
229	#[inline]
230	#[must_use]
231	pub const fn is_exact(&self) -> bool {
232		matches!(
233			(self.activation_storage, self.requested.storage),
234			(StoragePrecision::F32, StoragePrecision::F32)
235				| (StoragePrecision::F16, StoragePrecision::F16)
236		)
237	}
238}